From harvesting at is.invalid Tue Dec 1 00:28:33 2015 From: harvesting at is.invalid (Jussi Piitulainen) Date: Tue, 01 Dec 2015 07:28:33 +0200 Subject: I can't understand re.sub References: Message-ID: Erik writes: > On 30/11/15 08:51, Jussi Piitulainen wrote: [- -] >> If you wish to, >> say, replace "spam" in your foo with "REDACTED" but leave it intact in >> "May the spammer be prosecuted", a regex might be attractive after all. > > But that's not what the OP said they wanted to do. They said > everything was very fixed - they did not want a general purpose human > language text processing solution ... ;) Language processing is not what I had in mind here. Merely this, that there is some sort of word boundary, be it punctuation, whitespace, or an end of the string: >>> re.sub(r'\bspam\b', '****', 'spamalot spam') 'spamalot ****' That's not perfect either, but it's simple and might be somewhat proportional to the problem. A real solution should be aware of the actual structure of those lines, assuming they follow some defined syntax. From rantingrickjohnson at gmail.com Tue Dec 1 00:54:09 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 30 Nov 2015 21:54:09 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote: > I'm trying to understand why vars() exists. Does anyone use it? I think your "mental dilemma" stems from the fact that python was originally created to be an easy language for noobs to learn (which it still mostly is), however, over the years, feature creep has expanded this small general purpose language to include many specific applications. The "vars" function is a relic of the early days of Python and has not evolved because 99% of Python hackers find it to be useless. I mean, heck, print did not evolve until Py3! Outside of a few test sessions in my early days with Python, I don't remember ever using the vars function again. Your lament does remind me of a pet peeve i have concerning Python, and that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to achieve the same output. For instance, consider the output of vars(), globals(), locals(), dir(), and obj.__dict__. In many cases, all of these, or at least most of these, will return the same answer(s). Not only is that type of interface repetitive, it superfluously obfuscates the underling paths by which the value is obtained. We may find this difficult to believe, but many a noob has been stumped by the following questions: (1) How do you output a message without the print function? (2) How do you fetch a listing of an object's methods without the dir function? Listen, there is nothing wrong with creating "layers of abstraction". In fact, without abstractions, we could not evolve our technologies, however, if these "layers" are not intentionally crafted in logical order, then we quickly move away from the intuitive structure of a "cake model" and into the dreaded nightmare of the "spaghetti model". We should strive to structure our code in the image of a MandelBot set (think: "levels of detail"), not a hedge maze labyrinth of an "Overlook Hotel"! From ian.liu at chinaregistry.org.cn Tue Dec 1 02:12:58 2015 From: ian.liu at chinaregistry.org.cn (Ian Liu) Date: Tue, 1 Dec 2015 15:12:58 +0800 Subject: python CN domain and keyword Message-ID: <20151201151310456731@chinaregistry.org.cn> (Please forward this to your CEO, because this is urgent. Thanks) We are a Network Service Company which is the domain name registration center in Shanghai, China. On Nov 30, 2015, we received an application from Huasu Holdings Ltd requested "python" as their internet keyword and China (CN) domain names. But after checking it, we find this name conflict with your company name or trademark. In order to deal with this matter better, it's necessary to send email to you and confirm whether this company is your distributor or business partner in China? Kind regards Ian Liu General Manager China Registry (Headquarters) 8052, Douhai Building, No. 59 Baolian Road, Shanghai, China Tel: +86 21 6191 8696 Mobile: +86 138 1642 8671 Fax: +86 21 6191 8697 Web: www.chinaregistry.org.cn From eryksun at gmail.com Tue Dec 1 02:22:30 2015 From: eryksun at gmail.com (eryk sun) Date: Tue, 1 Dec 2015 01:22:30 -0600 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano wrote: > Either way, vars() doesn't solve the problem. What problem does it solve? vars() used to be the way to list local variables. >From 4 May 1994, Python 1.0.2 [1]: vars() returns a dictionary containing the local variables; vars(m) returns a dictionary containing the variables of module m. Note: dir(x) is now equivalent to vars(x).keys(). >From 13 October 1995, Python 1.3 [2]: Two new built-in functions, "globals()" and "locals()", provide access to dictionaries containming [sic] current global and local variables, respectively. (These augment rather than replace "vars()", which returns the current local variables when called without an argument, and a module's global variables when called with an argument of type module.) [1]: https://hg.python.org/cpython/file/v1.3/Misc/HISTORY#l386 [2]: https://hg.python.org/cpython/file/v1.3/Misc/NEWS#l55 From marko at pacujo.net Tue Dec 1 02:34:42 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 01 Dec 2015 09:34:42 +0200 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> Message-ID: <87si3md3l9.fsf@elektro.pacujo.net> Rick Johnson : > python was originally created to be an easy language for noobs to > learn Really? That's would be a silly objective for a programming language. > many a noob has been stumped So? You have to first placate the experts and the "noobs" will follow. Marko From steve+comp.lang.python at pearwood.info Tue Dec 1 02:55:44 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 01 Dec 2015 18:55:44 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> Message-ID: <565d5282$0$14486$c3e8da3@news.astraweb.com> On Tuesday 01 December 2015 16:54, Rick Johnson wrote: > On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote: >> I'm trying to understand why vars() exists. Does anyone use it? > > I think your "mental dilemma" stems from the fact that python was > originally created to be an easy language for noobs to learn (which it > still mostly is), Python was never intended to be "merely" a teaching language. I think Guido's original vision was for it to be a glue language between C libraries, and a scripting language. > however, over the years, feature creep has expanded this > small general purpose language to include many specific applications. The > "vars" function is a relic of the early days of Python and has not evolved > because 99% of Python hackers find it to be useless. I mean, heck, print > did not evolve until Py3! Outside of a few test sessions in my early days > with Python, I don't remember ever using the vars function again. > > Your lament does remind me of a pet peeve i have concerning Python, and > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY > TO DO IT!". In fact, in python there is almost always *MANY* ways to > achieve the same output. You misunderstand the koan. "There should be one way to do it" does not prohibit more than one way. (Although having multiple redundant ways is discouraged.) The koan exists to encourage the existence of *at least* one (but preferably only one) way to do it. "It", of course, is not defined, as if fitting for a koan. (Koans are meant to make you think, and they also act as a way of separating the adults from the kiddies -- do you have the experience to grok the meaning of the koan? For example, some people have been fooled by the apparent similarity of globals(), locals(), dir(), __dict__ and vars(), thinking that this is five ways to do the same thing, right? But no. (1) globals() *always* returns the global namespace. (2) locals() *always* returns the local namespace. It just happens that sometimes the local and global namespaces are the same. (3) dir() is intended as a user-friendly introspection tool at the interactive interpreter. As a result, it is permitted to modify the list of names returned, and in fact it does, suppressing some names which the core developers deem insufficiently "interesting". (4) __dict__ (in the sense of obj.__dict__) is the implementation, not part of Python's high-level interface. Attributes have to be stored somewhere, and Python chooses to reveal that in the documentation, nevertheless if you find yourself writing "__dict__" in production code, you're probably doing something wrong. These three functions, and one attribute, are clearly related, but they are just as clearly solutions to four distinct problems. There may be a little overlap, but at their core, the "it" that they are the way to "do it" are very different things. Which brings us to #5, vars(): "What is vars() good for?" is exactly what I'm asking. It seems to be the high-level interface to the implementation detail of __dict__, but I'm not sure that's needed. When that implementation changes -- classes using __slots__ instead of a dictionary -- we should expect that the high-level interface should adapt, otherwise what's the point of it? But it doesn't. vars() also defaults to returning locals() for no good reason I can see. Whatever the "it" is that vars() is meant to do is a good question, but it clearly isn't the same "it" as that for globals(), locals() and dir(). > We may find this difficult to believe, but many a noob has been stumped by > the following questions: > > (1) How do you output a message without the print function? *scratches head* Why would you want to do that? print is clearly the "one obvious way" to output a message. -- Steve From steve+comp.lang.python at pearwood.info Tue Dec 1 02:57:08 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 01 Dec 2015 18:57:08 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565d52d5$0$14486$c3e8da3@news.astraweb.com> On Tuesday 01 December 2015 18:22, eryk sun wrote: > On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano > wrote: >> Either way, vars() doesn't solve the problem. What problem does it solve? > > vars() used to be the way to list local variables. Oh, snap! Nice bit of detective work. So it's basically a left-over from when dinosaurs roamed the earth. -- Steve From framstag at rus.uni-stuttgart.de Tue Dec 1 03:26:31 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 1 Dec 2015 08:26:31 +0000 (UTC) Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > A better and more general test is: > > if hasattr(a, 'x'): print('attribute of a') Fine! I have now: def a(x=None): if not hasattr(a,'x'): a.x = 0 a.x += 1 print('%d:' % a.x,x) This simply counts the calls of a() But, when I rename the function I have to rename the attribute also. Is it possible to refer the attribute automatically to its function? Something like: def a(x=None): if not hasattr(_function_,'x'): _function_.x = 0 _function_.x += 1 print('%d:' % _function_.x,x) -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From manolo at austrohungaro.com Tue Dec 1 03:44:16 2015 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 1 Dec 2015 09:44:16 +0100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20151201084416.GA2700@beagle> On 12/01/15 at 12:00pm, Steven D'Aprano wrote: > I'm trying to understand why vars() exists. Does anyone use it? Well, I have this little podcast aggregator (https://github.com/manolomartinez/greg) that I and a bunch of other people use. I started writing it some years ago, and the code is a bit of a palimpsest, newer functionality reflecting my (somewhat) better understanding of the language. One of the oldest bits is this main() function: def main(): # parse the args and call whatever function was selected try: args = parser.parse_args(sys.argv[1:]) args.func(vars(args)) except AttributeError as err: if str(err) == "\'Namespace\' object has no attribute \'func\'": parser.print_help() else: print("Something has gone wrong: {}".format(err), file = sys.stderr, flush = True) To judge by this thread, this is probably wrong/noobish? Cheers, Manolo From az at anyad.org Tue Dec 1 03:48:51 2015 From: az at anyad.org (trolling tone) Date: Tue, 1 Dec 2015 09:48:51 +0100 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <565d5ef3$0$688$65785112@news.neostrada.pl> On 01.12.2015 03:19, Skybuck Flying wrote: > Hello, > > The question is: > > Is Microsoft Windows secretly downloading childporn to your computer ?! > > How can you be sure ? It's closed source software. > > It's downloading all kinds of crap via Windows Update. > > Having childporn on your computer is a crime and can result into jail time. > > I think it is safe to say that the era of closed source software is OVER. > > You are responsible for what is on your computer !!!!!!!!! > > Bye, > Skybuck. User agent Microsoft Windows Live Mail 15.4.3555.308 LOL From __peter__ at web.de Tue Dec 1 04:01:54 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 10:01:54 +0100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: Ulli Horlacher wrote: > Steven D'Aprano wrote: > >> A better and more general test is: >> >> if hasattr(a, 'x'): print('attribute of a') > > Fine! > > I have now: > > def a(x=None): > if not hasattr(a,'x'): a.x = 0 > a.x += 1 > print('%d:' % a.x,x) > > This simply counts the calls of a() > > But, when I rename the function I have to rename the attribute also. > Is it possible to refer the attribute automatically to its function? > Something like: > > def a(x=None): > if not hasattr(_function_,'x'): _function_.x = 0 > _function_.x += 1 > print('%d:' % _function_.x,x) Not directly, but there are workarounds: def with_function(f): return functools.partial(f, f) @with_function def foo(self, x=None): if not hasattr(self, "x"): self.x = 0 self.x += 1 print("{} called {} times".format(self.__name__, self.x)) From sylvain.thenault at logilab.fr Tue Dec 1 04:08:18 2015 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Tue, 1 Dec 2015 10:08:18 +0100 Subject: [Pylint-dev] Pylint 1.5.0 / Astroid 1.4.1 released In-Reply-To: References: Message-ID: <20151201090818.GB1976@logilab.fr> On 01 d?cembre 01:42, Claudiu Popa wrote: > Hello, Hi Claudiu, > I'm happy to announce you the release of Pylint 1.5.0, > respectively Astroid 1.4.1. > > It's been over a year since the last major release > and the amount of changes that were brought into pylint > in this time is humongous, with over 30 new checks > and tons of bug fixes. > > I would like to use this occasion for thanking for their contributions > the new committers who joined pylint's team in the past months, > ceridwen and Dmitry, as well as thanking the > contributors that made this release possible. Excellent! Congrat to this new core team which have realized a tremendous amount of work. > Here are some of the major changes of this release: [...] > - We also added a new 'extensions' component, which contains optional > checkers that needs to be activated explicitly. > > These includes 'extensions.check_docs', which verifies a bunch of > properties of the docstrings, such as checking that all function, > method and constructor parameters are mentioned > in the params and types part of the docstring. Also, it checks that > there are no naming inconsistencies between the signature and > the documentation, i.e. also report documented parameters that are missing > in the signature. This is important to find cases where parameters are > renamed only in the code, not in the documentation. > > Activate this checker with: > > --load-plugins=pylint.extensions.check_docs To be fair, there is also `pylint.extensions.check_elif` extension that emit message for 'else: if ' that could be written in 'elif ' Regards, -- Sylvain Th?nault, LOGILAB, Paris (01.45.32.03.12) - Toulouse (05.62.17.16.42) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From snailcoder at retrosite.invalid Tue Dec 1 04:15:25 2015 From: snailcoder at retrosite.invalid (Grobu) Date: Tue, 01 Dec 2015 10:15:25 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: Perhaps you could use a parameter's default value to implement your static variable? Like : # ------------------------------------------------- >>> def test(arg=[0]): ... print arg[0] ... arg[0] += 1 ... >>> test() 0 >>> test() 1 # ------------------------------------------------- From pcmanticore at gmail.com Tue Dec 1 04:34:18 2015 From: pcmanticore at gmail.com (Claudiu Popa) Date: Tue, 1 Dec 2015 11:34:18 +0200 Subject: [Pylint-dev] Pylint 1.5.0 / Astroid 1.4.1 released In-Reply-To: <20151201090818.GB1976@logilab.fr> References: <20151201090818.GB1976@logilab.fr> Message-ID: On Tue, Dec 1, 2015 at 11:08 AM, Sylvain Th?nault wrote: > On 01 d?cembre 01:42, Claudiu Popa wrote: >> Hello, > > Hi Claudiu, > >> I'm happy to announce you the release of Pylint 1.5.0, >> respectively Astroid 1.4.1. >> >> It's been over a year since the last major release >> and the amount of changes that were brought into pylint >> in this time is humongous, with over 30 new checks >> and tons of bug fixes. >> >> I would like to use this occasion for thanking for their contributions >> the new committers who joined pylint's team in the past months, >> ceridwen and Dmitry, as well as thanking the >> contributors that made this release possible. > > Excellent! Congrat to this new core team which have realized a tremendous amount > of work. > > > To be fair, there is also `pylint.extensions.check_elif` extension > that emit message for 'else: if ' that could be written in 'elif ' > > Regards, Oups, sorry about that, it wasn't intentional. It seems it isn't mentioned in the ChangeLog, which was the basis of my mail. Claudiu From nospam at thanks.invalid Tue Dec 1 04:49:12 2015 From: nospam at thanks.invalid (Juha Nieminen) Date: Tue, 1 Dec 2015 09:49:12 +0000 (UTC) Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: In comp.lang.c++ Skybuck Flying wrote: > Is Microsoft Windows secretly downloading childporn to your computer ?! No, because Microsoft is too smart to commit economical suicide. If a troyan/virus is doing so, that's not on Microsoft. --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From wolfgang.maier at biologie.uni-freiburg.de Tue Dec 1 04:58:50 2015 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 1 Dec 2015 10:58:50 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 01.12.2015 09:26, Ulli Horlacher wrote: > Steven D'Aprano wrote: > >> A better and more general test is: >> >> if hasattr(a, 'x'): print('attribute of a') > > Fine! > > I have now: > > def a(x=None): > if not hasattr(a,'x'): a.x = 0 > a.x += 1 > print('%d:' % a.x,x) > > This simply counts the calls of a() > > But, when I rename the function I have to rename the attribute also. > Is it possible to refer the attribute automatically to its function? > Something like: > > def a(x=None): > if not hasattr(_function_,'x'): _function_.x = 0 > _function_.x += 1 > print('%d:' % _function_.x,x) > > I'm wondering whether you have a good reason to stick with a function. What you are trying to achieve seems to be easier and cleaner to implement as a class: class Counter (object): def __init__ (self, start_value=0): self.x = start_value def __call__ (self): self.x += 1 1) solves the renaming problem 2) allows you to have several counters around: counter1 = Counter() counter2 = Counter() counter3 = Counter(35) counter1() counter2() counter1() print (counter1.x, counter2.x, counter3.x) Cheers, Wolfgang From lac at openend.se Tue Dec 1 05:10:23 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 01 Dec 2015 11:10:23 +0100 Subject: python domain in China. This showed up on Python list Message-ID: <201512011010.tB1AANt0032057@fido.openend.se> I think we have just dodged a bullet, let us now go thank the nice people who sent us this and figure out how we should secure the domain. Laura ------- Forwarded Message Return-Path: Date: Tue, 1 Dec 2015 15:12:58 +0800 From: "Ian Liu" To: Subject: python CN domain and keyword Message-ID: <20151201151310456731 at chinaregistry.org.cn> X-mailer: Foxmail 6, 13, 102, 15 [cn] Mime-Version: 1.0 (Please forward this to your CEO, because this is urgent. Thanks) We are a Network Service Company which is the domain name registration center in Shanghai, China. On Nov 30, 2015, we received an application from Huasu Holdings Ltd requested "python" as their internet keyword and China (CN) domain names. But after checking it, we find this name conflict with your company name or trademark. In order to deal with this matter better, it's necessary to send email to you and confirm whether this company is your distributor or business partner in China? Kind regards Ian Liu General Manager China Registry (Headquarters) 8052, Douhai Building, No. 59 Baolian Road, Shanghai, China Tel: +86 21 6191 8696 Mobile: +86 138 1642 8671 Fax: +86 21 6191 8697 Web: www.chinaregistry.org.cn - -- https://mail.python.org/mailman/listinfo/python-list ------- End of Forwarded Message From motoom at xs4all.nl Tue Dec 1 05:35:26 2015 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 1 Dec 2015 11:35:26 +0100 Subject: python domain in China. This showed up on Python list In-Reply-To: <201512011010.tB1AANt0032057@fido.openend.se> References: <201512011010.tB1AANt0032057@fido.openend.se> Message-ID: Hi, > On 01 Dec 2015, at 11:10, Laura Creighton wrote: > > I think we have just dodged a bullet, let us now go thank the > nice people who sent us this and figure out how we should > secure the domain. I received exactly the same email a while ago, claiming that someone was registering the name 'Michiel' in China as 'internet keyword' (whatever that may be), and whether I knew them. I responded 'no', and have never since heard from them. Greetings, From __peter__ at web.de Tue Dec 1 05:40:15 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 11:40:15 +0100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> Message-ID: Manolo Mart?nez wrote: > On 12/01/15 at 12:00pm, Steven D'Aprano wrote: > > I'm trying to understand why vars() exists. Does anyone use it? > > Well, I have this little podcast aggregator > (https://github.com/manolomartinez/greg) that I and a bunch of other > people use. I started writing it some years ago, and the code is a bit > of a palimpsest, newer functionality reflecting my (somewhat) better > understanding of the language. One of the oldest bits is this main() > function: > > def main(): # parse the args and call whatever function was selected > try: > args = parser.parse_args(sys.argv[1:]) > args.func(vars(args)) > except AttributeError as err: > if str(err) == "\'Namespace\' object has no attribute \'func\'": > parser.print_help() > else: > print("Something has gone wrong: {}".format(err), file = sys.stderr, flush = True) > > > To judge by this thread, this is probably wrong/noobish? What probably is typical for a beginner in that snippet is that you don't trust the exception system and handle exceptions that will never occur once the script is debugged. Just write args = parser.parse_args() args.func(vars(args)) Now vars(). I see nothing wrong with it, but when I look into one of your func implementations > def info(args): # Provides information of a number of feeds > session = Session(args) > if "all" in args["names"]: > feeds = session.list_feeds() > else: > feeds = args["names"] > for feed in feeds: > pretty_print(session, feed) I come to the conclusion that passing args directly could make your life easier: def info(args): """Provides information of a number of feeds""" session = Session(args) if "all" in args.names: feeds = session.list_feeds() else: feeds = args.names for feed in feeds: pretty_print(session, feed) As far as I can see there is only one place where the key is not a constant, and you can rewrite that from > try: > if args[value]: > return args[value] > except KeyError: > pass to try: answer = getattr(args, value) if answer: return answer except AttributeError: pass From __peter__ at web.de Tue Dec 1 05:49:37 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 11:49:37 +0100 Subject: Generate config file from template using Python search and replace. References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> Message-ID: Mr Zaug wrote: > On Monday, November 30, 2015 at 4:14:48 AM UTC-5, Peter Otten wrote: >> Mr Zaug wrote: >> >> > On Sunday, November 29, 2015 at 5:50:51 PM UTC-5, Peter Otten wrote: >> >> Mr Zaug wrote: >> >> >> >> > When I run this script on OS X El Capitan, I see, >> >> > >> >> > # permission sensitive cache >> >> > $include "_dispatcher_shared_auth-checker: >> >> > >> >> > Was I supposed to incorporate it into the script I posted? >> >> >> >> Are you referring to my post? I'm sorry, I can't make sense of your >> >> question. >> > >> > Yes. The snippet you posted went way over my head. When I ran it, it >> > printed >> > >> > # permission sensitive cache >> > $include "_dispatcher_shared_auth-checker: >> >> It's hard to tell from that problem description what might have gone >> wrong. However: >> >> In your template file you have to enclose all words you want to replace >> in braces ("you have foo options" becomes "you have {foo} options"), to >> replace all literal { with {{ and all literal } with }}. >> >> Did you do that? > > Yup, I sure did. So here is my current script. The only remaining task now > is figuring out how to write the contents to a new file. > > #!/usr/bin/env python > import os > import sys > > script, template_file = sys.argv > print "Opening the template file..." > > print "What is the serial number of the site?", > nnn = raw_input() [...] > with open (template_file, "r") as a_string: > data=a_string.read().replace('{SERVER_NAME}', > server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}', > content_path).replace('{DAMPATH}', dampath).replace('{ENV}', > env).replace('{CACHE_DOCROOT}', cache_docroot) If all other braces are properly escaped you can use format instead of replace: data = a_string.read().format( SERVER_NAME=server_name, BRAND=brand, CONTENT_PATH=content_path DAMPATH=dampath, ENV=env, CACHE_DOCROOT=cache_doc_root) From clp2 at rebertia.com Tue Dec 1 05:51:21 2015 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 1 Dec 2015 02:51:21 -0800 Subject: python domain in China. This showed up on Python list In-Reply-To: <201512011010.tB1AANt0032057@fido.openend.se> References: <201512011010.tB1AANt0032057@fido.openend.se> Message-ID: On Tue, Dec 1, 2015 at 2:10 AM, Laura Creighton wrote: > I think we have just dodged a bullet, let us now go thank the > nice people who sent us this and figure out how we should > secure the domain. > > Laura > > > ------- Forwarded Message > > Return-Path: > Date: Tue, 1 Dec 2015 15:12:58 +0800 > From: "Ian Liu" > To: > Subject: python CN domain and keyword I hate to break it to you, but this seems to be just another of those come-ons spammed out by various scummy businesses that trawl WHOIS databases for people to scam into buying extra/unnecessary domain names. Google "chinese domain scam" for more info. I've received similar spams after having registered some .com domains that no corporation could possibly legitimately want the .cn equivalents of. Additionally, the two most obvious relevant domains were already registered by non-PSF parties years ago, and aren't set to expire imminently. Per https://ewhois.cnnic.cn : Domain Name: python.cn Registrant: ??????????? Registrant Contact Email: ****@happylatte.com Registration Time: 2003-03-17 12:20:05 Expiration Time: 2017-03-17 12:48:36 Domain Name: python.org.cn Registrant Contact Email: ****@lxl.cn Registration Time: 2007-04-12 14:02:16 Expiration Time: 2016-04-12 14:02:16 Regards, Chris From __peter__ at web.de Tue Dec 1 06:01:14 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 12:01:14 +0100 Subject: python response slow when running external DLL References: <3ec6a016-dae5-4986-b035-c1a8cd4dc3e7@googlegroups.com> Message-ID: jfong at ms4.hinet.net wrote: > Peter Otten at 2015/11/28 UTC+8 6:14:09PM wrote? >> No, the point of both recipes is that tkinter operations are only ever >> invoked from the main thread. The main thread has polling code that >> repeatedly looks if there are results from the helper thread. As far I >> understand the polling method has the structure >> >> f(): >> # did we get something back from the other thread? >> # a queue is used to avoid race conditions >> >> # if yes react. >> # var_status.set() goes here >> >> # reschedule f to run again in a few millisecs; >> # that's what after() does > > Have no idea how the main thread poll on all those events (or it use a > queue)? All I know now is that the main thread(mainloop()?) can be easily > blocked by event handlers if the handler didn't run as a separate thread. > >> > ..... >> > ..... >> > #do the rest >> > var_status.set('Download...') >> > _thread.start_new_thread(td_download, ()) #must use threading >> > >> > def td_download(): >> > result = mydll.SayHello() >> > if result: >> > var_status.set("Download Fail at %s" % hex(result)) >> > showerror('Romter', 'Download Fail') >> > else: >> > var_status.set('Download OK') >> > showinfo('Romter', 'Download OK') >> >> As td_download() runs in the other thread the var_status.set() methods >> are problematic. > > No idea what kind of problem it will encounter. Can you explain? While the var_status.set() invoked from the second thread modifies some internal data the main thread could kick in and modify (parts of) that same data, thus bringing tkinter into an broken state. A simple example that demonstrates the problem: import random import threading import time account = 70 def withdraw(delay, amount): global account if account >= amount: print("withdrawing", amount) account -= amount else: print("failed to withdraw", amount) threads = [] for i in range(10): t = threading.Thread( target=withdraw, kwargs=dict(delay=.1, amount=random.randrange(1, 20))) threads.append(t) t.start() for t in threads: t.join() Before every withdrawal there seems to be a check that ensures that there is enough money left, but when you run the script a few times you will still sometimes end with a negative balance. That happens when thread A finds enough money, then execution switches to thread B which also finds enough money, then both threads perform a withdrawal -- oops there wasn't enough money for both. >> Another complication that inevitably comes with concurrency: what if the >> user triggers another download while one download is already running? If >> you don't keep track of all downloads the message will already switch to >> "Download OK" while one download is still running. > > Hummm...this thought never comes to my mind. After take a quick test I > found, you are right, a second "download" was triggered immediately. > That's a shock to me. I suppose the same event shouldn't be triggered > again, or at least not triggered immediately, before its previous handler > was completed. ...I will take a check later on Borland C++ builder to see > how it reacts! > > Anyway to prevent this happens? if Python didn't take care it for us. A simple measure would be to disable the button until the download has ended. From kevingloveruk at gmail.com Tue Dec 1 06:17:19 2015 From: kevingloveruk at gmail.com (Kevin Glover) Date: Tue, 1 Dec 2015 03:17:19 -0800 (PST) Subject: Exclude text within quotation marks and words beginning with a capital letter Message-ID: I am working on a program that is written in Python 2.7 to be compatible with the POS tagger that I import from Pattern. The tagger identifies all the nouns in a text. I need to exclude from the tagger any text that is within quotation marks, and also any word that begins with an upper case letter (including words at the beginning of sentences). Any advice on coding that would be gratefully received. Thanks. Kevin From burak.arslan at arskom.com.tr Tue Dec 1 06:20:57 2015 From: burak.arslan at arskom.com.tr (Burak Arslan) Date: Tue, 1 Dec 2015 13:20:57 +0200 Subject: New JSON encoding method proposal for custom objects In-Reply-To: <6f5cd8a5-6e14-4069-8dfe-4a1a00c05827@googlegroups.com> References: <6f5cd8a5-6e14-4069-8dfe-4a1a00c05827@googlegroups.com> Message-ID: <565D8299.7070700@arskom.com.tr> hey, On 11/30/15 14:35, cescus92 at gmail.com wrote: > > Hello everyone and thank you for your interest! > > The Peter's code is very similar to what I think the default JSON encoder should be. > > The advantage of the method that I propose is that you should not care anymore about which encoder you're going to use even in case of different class instances. Imagine if you could just do > > json.dumps({[1,2,3], Obj(), [DifferentObj()] }) > > FWIW, Spyne can to the exact same thing -- i.e. serialize an object given its definition to whatever format you want. (currently xml, json, yaml and msgpack are supported). Here's a json example: >>> from spyne import * >>> from spyne.util.dictdoc import get_object_as_json, get_json_as_object >>> get_object_as_json([1,2,3], Array(Integer)) '[1, 2, 3]' >>> >>> from datetime import datetime >>> >>> class SomeObject(ComplexModel): ... s = Unicode ... i = Integer ... dt = DateTime ... >>> get_object_as_json(SomeObject(s='str', i=42, dt=datetime.now()), complex_as=list) '[42, "str", "2015-12-01T12:57:23.751631"]' >>> >>> get_json_as_object('[42, "str", "2015-12-01T12:55:21.777108"]', SomeObject, complex_as=list) SomeObject(i=42, s=u'str', dt=datetime.datetime(2015, 12, 1, 12, 55, 21, 777108)) >>> >>> More info: http://spyne.io Best, Burak PS: The astute reader will notice that element order in SomeObject could be totally random. * In Python 3, we solve that by returning an odict() in the __prepare__ of the ComplexModel metaclass. * In Python 2, we solve that by somehow getting hold of AST of the class definition and deducing the order from there. Yes you read that right! I know, it's horrible! Don't worry, it's turned off by default. We recommend the workaround in [1] for Python 2. See [2] and [3] to see how we integrated it. [1]: http://spyne.io/docs/2.10/manual/03_types.html#complex [2]: https://github.com/arskom/spyne/pull/313 [3]: https://github.com/arskom/spyne/blob/2768c7ff0b5f58aa0e47859fcd69e5bb7aa31aba/spyne/util/meta.py From framstag at rus.uni-stuttgart.de Tue Dec 1 06:47:59 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 1 Dec 2015 11:47:59 +0000 (UTC) Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: Wolfgang Maier wrote: > I'm wondering whether you have a good reason to stick with a function. Easy handling, no programming overhead. Clean, orthogonal code. > What you are trying to achieve seems to be easier and cleaner to > implement as a class: > > class Counter (object): > def __init__ (self, start_value=0): > self.x = start_value > > def __call__ (self): > self.x += 1 > > 1) solves the renaming problem > 2) allows you to have several counters around: > > counter1 = Counter() > counter2 = Counter() > counter3 = Counter(35) > counter1() > counter2() > counter1() > print (counter1.x, counter2.x, counter3.x) Implementing a counter was only an example for a static variable, not the primary goal. With a class, I find it irritating the first function call have to be different than the subsequent ones: def main(): a=A(1) a(1) a(5) a(0) print(a.n) class A(object): def __init__ (self,*arg): self.n = 0 def __call__(self,x): self.n += 1 print('%d:' % self.n,x) main() -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From lac at openend.se Tue Dec 1 06:49:06 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 01 Dec 2015 12:49:06 +0100 Subject: python domain in China. This showed up on Python list In-Reply-To: References: <201512011010.tB1AANt0032057@fido.openend.se> Message-ID: <201512011149.tB1Bn60g001408@fido.openend.se> In a message of Tue, 01 Dec 2015 02:51:21 -0800, Chris Rebert writes: >I hate to break it to you, but this seems to be just another of those >come-ons spammed out by various scummy businesses that trawl WHOIS >databases for people to scam into buying extra/unnecessary domain >names. Google "chinese domain scam" for more info. I've received >similar spams after having registered some .com domains that no >corporation could possibly legitimately want the .cn equivalents of. Ah... Thank you Chris. Sure fooled me. Laura From cescus92 at gmail.com Tue Dec 1 07:08:26 2015 From: cescus92 at gmail.com (cescus92 at gmail.com) Date: Tue, 1 Dec 2015 04:08:26 -0800 (PST) Subject: New JSON encoding method proposal for custom objects In-Reply-To: References: <6f5cd8a5-6e14-4069-8dfe-4a1a00c05827@googlegroups.com> Message-ID: Hello Burak, thank you for the reply. > FWIW, Spyne can to the exact same thing -- i.e. serialize an object > given its definition to whatever format you want. (currently xml, json, > yaml and msgpack are supported). My aim is to propose a built-in method to accomplish this common and simple task that, IMHO, shouln't require the use of extra code for legibility's sake. Anyway the whole Spyne framework is very interesting, thank you for having shared that! Probably it's going to be useful for a project of mine :) Have a nice day, Francesco From __peter__ at web.de Tue Dec 1 07:17:47 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 13:17:47 +0100 Subject: New JSON encoding method proposal for custom objects References: <6f5cd8a5-6e14-4069-8dfe-4a1a00c05827@googlegroups.com> Message-ID: cescus92 at gmail.com wrote: >> Go to python-ideas for a lengthy discussion ;) > Where can I find it? At the same place where you already found python-list, or here: https://mail.python.org/mailman/listinfo/python-ideas From cescus92 at gmail.com Tue Dec 1 07:24:30 2015 From: cescus92 at gmail.com (cescus92 at gmail.com) Date: Tue, 1 Dec 2015 04:24:30 -0800 (PST) Subject: New JSON encoding method proposal for custom objects In-Reply-To: References: <6f5cd8a5-6e14-4069-8dfe-4a1a00c05827@googlegroups.com> Message-ID: > At the same place where you already found python-list, or here: > > https://mail.python.org/mailman/listinfo/python-ideas Yeah, I've found it after a simple search.. I thought it was like an hidden place for just some python's guru lol! Thank you! :) From __peter__ at web.de Tue Dec 1 07:43:56 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 13:43:56 +0100 Subject: Exclude text within quotation marks and words beginning with a capital letter References: Message-ID: Kevin Glover wrote: > I am working on a program that is written in Python 2.7 to be compatible > with the POS tagger that I import from Pattern. The tagger identifies all > the nouns in a text. I need to exclude from the tagger any text that is > within quotation marks, and also any word that begins with an upper case > letter (including words at the beginning of sentences). > > Any advice on coding that would be gratefully received. Thanks. How about removing them afterwards? >>> def skip_quoted(pairs): ... quoted = False ... for a, b in pairs: ... if a == '"': ... quoted = not quoted ... elif not quoted: ... yield a, b ... >>> from pattern.en import tag >>> [p for p in skip_quoted(tag('Did you say "Hello world"?')) if not p[0] [0].isupper()] [(u'you', u'PRP'), (u'say', u'VB'), (u'?', u'.')] From matthew.herzog at gmail.com Tue Dec 1 08:18:56 2015 From: matthew.herzog at gmail.com (Mr Zaug) Date: Tue, 1 Dec 2015 05:18:56 -0800 (PST) Subject: Generate config file from template using Python search and replace. In-Reply-To: References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> Message-ID: Oh, that's much easier to read. Thanks! From matthew.herzog at gmail.com Tue Dec 1 09:18:53 2015 From: matthew.herzog at gmail.com (Mr Zaug) Date: Tue, 1 Dec 2015 06:18:53 -0800 (PST) Subject: Generate config file from template using Python search and replace. In-Reply-To: References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> Message-ID: <076b883f-f649-48e0-a064-f05d4d6c5909@googlegroups.com> Actually, I don't understand what you mean by "all other braces." What braces are you talking about? The placeholders in the template file (the file being read in) have braces around them but they are not escaped. Also, do I really need curly braces to tell Python what my placeholders are? From __peter__ at web.de Tue Dec 1 09:41:04 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 15:41:04 +0100 Subject: Generate config file from template using Python search and replace. References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> <076b883f-f649-48e0-a064-f05d4d6c5909@googlegroups.com> Message-ID: Mr Zaug wrote: > Actually, I don't understand what you mean by "all other braces." What > braces are you talking about? The placeholders in the template file (the > file being read in) have braces around them but they are not escaped. The example you provide was $include "_dispatcher_publish_filters.any" /1000 { /type "allow" /glob "* /CONTENT_PATH/*.html*" } /1001 { /type "allow" /glob "POST /DAMPATH/www/*.html *" } If you want to use string formatting to replace CONTENT_PATH and DAMPATH in the above excerpt you have to change the template to $include "_dispatcher_publish_filters.any" /1000 {{ /type "allow" /glob "* /{CONTENT_PATH}/*.html*" }} /1001 {{ /type "allow" /glob "POST /{DAMPATH}/www/*.html *" }} > Also, do I really need curly braces to tell Python what my placeholders > are? Let's take a slightly modified example to answer that one: $include "_dispatcher_publish_filters.any" /1000 { /type "allow" /glob "* /CONTENT_PATH/*.html*" } /1001 { /type "allow" /glob "POST /DAMPATH/www/*.html *" } /1002 { /type "allow" /glob "* /ALTERNATIVE_CONTENT_PATH/*.html*" } If you try to fill in the CONTENT_PATH with data = data.replace("CONTENT_PATH", "foo") the result will be $include "_dispatcher_publish_filters.any" /1000 { /type "allow" /glob "* /foo/*.html*" } /1001 { /type "allow" /glob "POST /DAMPATH/www/*.html *" } /1002 { /type "allow" /glob "* /ALTERNATIVE_foo/*.html*" } Look at the butchered line starting with /1002, a problem that MRAB already pointed out before. The braces are not necessary if the string you are replacing doesn't occur elsewhere in the template, but they make the replacement process both flexible and unambiguous. From matthew.herzog at gmail.com Tue Dec 1 10:21:51 2015 From: matthew.herzog at gmail.com (Mr Zaug) Date: Tue, 1 Dec 2015 07:21:51 -0800 (PST) Subject: Generate config file from template using Python search and replace. In-Reply-To: References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> <076b883f-f649-48e0-a064-f05d4d6c5909@googlegroups.com> Message-ID: That makes sense. So I still can't see how to write the string object to a file whist naming the file with whatever values I provided for the NNN and BRAND variables. Printing the contents of the string object is working with all the expected substitutions. Do I need to convert the string object into a file before I write it? Or do I need to open a new file and somehow stuff the string object into it? From __peter__ at web.de Tue Dec 1 10:43:33 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 16:43:33 +0100 Subject: Generate config file from template using Python search and replace. References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> <076b883f-f649-48e0-a064-f05d4d6c5909@googlegroups.com> Message-ID: Mr Zaug wrote: > That makes sense. > > So I still can't see how to write the string object to a file whist naming > the file with whatever values I provided for the NNN and BRAND variables. > > Printing the contents of the string object is working with all the > expected substitutions. Do I need to convert the string object into a file > before I write it? Or do I need to open a new file and somehow stuff the > string object into it? Yes, open a new file and write the string using the write() method. You can use string formatting to build the filename, too: text = ... # the string you want to write nnn = raw_input("What is the serial number of the site? ") brand = raw_input("What is the brand, or product name? ") filename = "{NNN}{BRAND}_farm.any".format(BRAND=brand, NNN=nnn) with open(filename, "w") as outstream: outstream.write(text) From ian.g.kelly at gmail.com Tue Dec 1 10:53:40 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Dec 2015 09:53:40 -0600 Subject: Question about code writing '% i, callback' In-Reply-To: References: <25af8ac3-5fc7-44bd-a73f-7a870b69515a@googlegroups.com> <53ef7ef4-cfec-4c91-a45c-5b847dde8fad@googlegroups.com> Message-ID: On Mon, Nov 30, 2015 at 7:44 PM, Dennis Lee Bieber wrote: > On Mon, 30 Nov 2015 10:55:23 -0800 (PST), fl declaimed > the following: > >>Thanks Ian. I created the class because I want to use the original example >>line >> >> UI.Button("button %s" % i, callback) >> >>Is there another way to use the above line without my class definition? >>I do feel that my created class does not match well with the above line >>because the first item "button %s" does not fit __self__ in the class. > > The first item passed to a method call is the instance object... In > this case, whatever "UI" is bound to. > > If it helps, think of > > UI.Button("string", callback) > as > Button(UI, "string", callback) This is only correct if "UI" is bound to an instance of a class and "Button" is a method of that class. If UI is a class itself or a module, then those are not equivalent. From gordon at panix.com Tue Dec 1 11:56:04 2015 From: gordon at panix.com (John Gordon) Date: Tue, 1 Dec 2015 16:56:04 +0000 (UTC) Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> Message-ID: In <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd at googlegroups.com> Rick Johnson writes: > Your lament does remind me of a pet peeve i have concerning Python, and > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) > WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to > achieve the same output.=20 The koan reads: There should be one-- and preferably only one --obvious way to do it. You left out the rather important word "obvious". -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From jorge.conrado at cptec.inpe.br Tue Dec 1 12:21:47 2015 From: jorge.conrado at cptec.inpe.br (jorge.conrado at cptec.inpe.br) Date: Tue, 01 Dec 2015 15:21:47 -0200 Subject: 4D arrays Message-ID: <08275b89237d46ae87ff574db3748dc2@cptec.inpe.br> Hi, I use the IDL but now I'm change to PYTHON. I have a 4D array (time, level,lon,lat). I would like to get a 2D array for a specific time (time1) and level (level1). In IDL I use: 2Darray = 4Darray(time1,level1,*,*). How can I get the 2D array in Python Conrado From __peter__ at web.de Tue Dec 1 12:47:09 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 18:47:09 +0100 Subject: 4D arrays References: <08275b89237d46ae87ff574db3748dc2@cptec.inpe.br> Message-ID: jorge.conrado at cptec.inpe.br wrote: > I use the IDL but now I'm change to PYTHON. I have a 4D array (time, > level,lon,lat). I would like to get a 2D array for a specific time > (time1) and level (level1). In IDL I use: 2Darray = > 4Darray(time1,level1,*,*). How can I get the 2D array in Python With numpy you can use slicing. Create a 4D array with pointless data in it: >>> import numpy >>> a = numpy.arange(2*3*4*5).reshape((2, 3, 4, 5)) >>> a array([[[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [ 10, 11, 12, 13, 14], [ 15, 16, 17, 18, 19]], [[ 20, 21, 22, 23, 24], [ 25, 26, 27, 28, 29], [ 30, 31, 32, 33, 34], [ 35, 36, 37, 38, 39]], [[ 40, 41, 42, 43, 44], [ 45, 46, 47, 48, 49], [ 50, 51, 52, 53, 54], [ 55, 56, 57, 58, 59]]], [[[ 60, 61, 62, 63, 64], [ 65, 66, 67, 68, 69], [ 70, 71, 72, 73, 74], [ 75, 76, 77, 78, 79]], [[ 80, 81, 82, 83, 84], [ 85, 86, 87, 88, 89], [ 90, 91, 92, 93, 94], [ 95, 96, 97, 98, 99]], [[100, 101, 102, 103, 104], [105, 106, 107, 108, 109], [110, 111, 112, 113, 114], [115, 116, 117, 118, 119]]]]) Extract 2D arrays: >>> a[:,2,3] array([[ 55, 56, 57, 58, 59], [115, 116, 117, 118, 119]]) >>> a[1,:,2] array([[ 70, 71, 72, 73, 74], [ 90, 91, 92, 93, 94], [110, 111, 112, 113, 114]]) From matthew.herzog at gmail.com Tue Dec 1 13:43:18 2015 From: matthew.herzog at gmail.com (Mr Zaug) Date: Tue, 1 Dec 2015 10:43:18 -0800 (PST) Subject: Generate config file from template using Python search and replace. In-Reply-To: References: <73046000-f634-40f2-9c83-f03a5db134e6@googlegroups.com> <4f923003-4f85-4a69-bfda-165194211bb4@googlegroups.com> <0dd0db34-7f8f-4e8b-ad6a-c82ad19c2e5e@googlegroups.com> <8c787187-910c-40df-9235-9e4c2dafb19c@googlegroups.com> <076b883f-f649-48e0-a064-f05d4d6c5909@googlegroups.com> Message-ID: <30445b71-9fdf-414d-b46b-35c3f3cb6398@googlegroups.com> Ye, this does work. Many thanks! filename = "{NNN}_{BRAND}_farm.any".format(BRAND=brand, NNN=nnn) with open(filename, "w") as outstream: outstream.write(data) From hayesstw at telkomsa.net Tue Dec 1 13:49:24 2015 From: hayesstw at telkomsa.net (Steve Hayes) Date: Tue, 01 Dec 2015 20:49:24 +0200 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying" wrote: >Hello, > >The question is: > >Is Microsoft Windows secretly downloading childporn to your computer ?! You download things FROM a computer, you upload them TO a computer. Since you don't even know that much about computers, anything else you say is obviously not worth readin. -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From breamoreboy at yahoo.co.uk Tue Dec 1 13:57:38 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 1 Dec 2015 18:57:38 +0000 Subject: activestate recipe for code to source and back fails on 3.3+, core Python bug? Message-ID: The recipe in question is here http://code.activestate.com/recipes/578353-code-to-source-and-back. I've called it c2sab in the test code below. The problem is that the class name gets dropped during the round trip, but only if a list, dict or set comprehension or a generator expression is involved, and only from the code.co_consts tuple. Hopefully the code and output that follows makes sense. import c2sab import inspect class Comps(): def listcomp(self): self.lc = [x for x in range(10)] def genexpr(self): self.ge = (x for x in range(10)) def dictcomp(self): self.dc = {x: x**2 for x in range(10)} def setcomp(self): self.sc = {x for x in range(10)} methods = inspect.getmembers(Comps, inspect.isfunction) for _, method in methods: print('Processing', method.__name__) code = method.__code__ recode = c2sab.recompile(*c2sab.uncompile(code)) for offset, co_consts in enumerate(zip(code.co_consts, recode.co_consts)): old = co_consts[0] new = co_consts[1] if old != new: print('offset {} code |{}| not equal to recode |{}|'.format(offset, old, new)) print() Processing dictcomp offset 2 code |Comps.dictcomp..| not equal to recode |dictcomp..| Processing genexpr offset 2 code |Comps.genexpr..| not equal to recode |genexpr..| Processing listcomp offset 2 code |Comps.listcomp..| not equal to recode |listcomp..| Processing setcomp offset 2 code |Comps.setcomp..| not equal to recode |setcomp..| I can reproduce the above on 3.3 to 3.6 inclusive on Windows 10. This has no impact on 3.2 or lower as the field in question is new in co_consts for 3.3. So is my analysis correct? If yes I'll be reporting a bug although I've no idea what against, if no what have I overlooked? -- 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.com Tue Dec 1 14:05:38 2015 From: random832 at fastmail.com (Random832) Date: Tue, 1 Dec 2015 19:05:38 +0000 (UTC) Subject: "Downloading" References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 2015-12-01, Steve Hayes wrote: > You download things FROM a computer, you upload them TO a computer. I'm a little bit confused as to what kinds of file transfers you think don't have at least two endpoints. From kst-u at mib.org Tue Dec 1 14:11:04 2015 From: kst-u at mib.org (Keith Thompson) Date: Tue, 01 Dec 2015 11:11:04 -0800 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: Steve Hayes writes: > On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying" > wrote: >>The question is: >> >>Is Microsoft [snip] > > You download things FROM a computer, you upload them TO a computer. > > Since you don't even know that much about computers, anything else you > say is obviously not worth readin. Nor is it worth replying to. *Please* don't feed the troll. (Followups set.) -- Keith Thompson (The_Other_Keith) kst-u at mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From ian.g.kelly at gmail.com Tue Dec 1 15:19:57 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Dec 2015 14:19:57 -0600 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Tue, Dec 1, 2015 at 12:49 PM, Steve Hayes wrote: > On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying" > wrote: > >>Hello, >> >>The question is: >> >>Is Microsoft Windows secretly downloading childporn to your computer ?! > > You download things FROM a computer, you upload them TO a computer. You download things FROM one computer to another. You upload things from one computer TO another. The only semantic difference is in which end of the transfer is "local". Otherwise, it's like saying "up the street" versus "down the street", so what difference does it make? From denismfmcmahon at gmail.com Tue Dec 1 15:32:33 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 1 Dec 2015 20:32:33 -0000 (UTC) Subject: Could you explain this rebinding (or some other action) on "nums = nums"? References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: > In the case of: > > tup[1] += [6, 7] > > what it's trying to do is: > > tup[1] = tup[1].__iadd__([6, 7]) > > tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but > then Python tries to put the result that the method returns into tup[1]. > That fails because tup itself is a tuple, which is immutable. I think I might have found a bug: $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> tup = [1,2,3],[4,5,6] >>> tup ([1, 2, 3], [4, 5, 6]) >>> tup[1] [4, 5, 6] >>> tup[1] += [7,8,9] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> tup[1] [4, 5, 6, 7, 8, 9] >>> tup ([1, 2, 3], [4, 5, 6, 7, 8, 9]) >>> quit() -- Denis McMahon, denismfmcmahon at gmail.com From rantingrickjohnson at gmail.com Tue Dec 1 15:33:43 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 1 Dec 2015 12:33:43 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565d5282$0$14486$c3e8da3@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> Message-ID: <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote: > Python was never intended to be "merely" a teaching language. I think > Guido's original vision was for it to be a glue language between C > libraries, and a scripting language. It's a well know fact that GvR was inspired to create Python from his experiences working with a language called ABC -- and ABC was designed *EXCLUSIVELY* to be a beginners language. GvR has even written that one of his objections to ABC's design was it's tendency to create new jargon-isms to replace old jargon-isms. The language designers "thought" they could ease the learning curve simply thru virtue of symbols, but all they did was to further confuse noobs. GvR saw the folly of this, and set out to prevent such design flaws in his language, however, i argue that interfaces like the "print function" are making the same mistakes. The linking of abstraction layers is even *MORE* important than intuitive naming conventions. But sometimes the name is the only path by which you can provide the link. As is the case with the print function. > > Rick said: > > (1) How do you output a message without the print function? > Steven said: > *scratches head* > > Why would you want to do that? print is clearly the "one obvious way" to > output a message. Well of course the answers are *OBVIOUS* when you already *KNOW* them Steven! Climb down off your high horse for a moment, and take yourself back to a time *BEFORE* you had any knowledge of output streams. I am not arguing that "abstractions are evil", no, my position is that abstractions must be constructed in a manner that provides a clear trail of bread crumbs which lead to the underlying processes. With print, not only is the engine in another dimension, but the hood is as well! How is a noob to discover the engine when he cannot find the hood? Ponder the following example code (as a noob!): stdout.write("Dude, i found my car, the hood, and the effing engine!!!") Even a noob can intuit what is going on here. First we have an *OBJECT* named "stdout, and we can extrapolate that stdout is an abbreviation for StandardOutput. Next, we see a method called "write", and, if our IQ is above room temperature, then we can extrapolate what that method will do. Now ponder this code (as a noob!): print("Dude, where's the intuitiveness?") What the heck does print do? Where will the string go after i execute this line of code? Should i turn my printer on? Should i check my ink levels? And what OEM drivers are required? Not only is "print" un-intuitive (by nature of it's naming), it is obfuscating the path to the underlying process of "sending data to an output stream". From ian.g.kelly at gmail.com Tue Dec 1 15:44:38 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Dec 2015 14:44:38 -0600 Subject: Could you explain this rebinding (or some other action) on "nums = nums"? In-Reply-To: References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon wrote: > On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: > >> In the case of: >> >> tup[1] += [6, 7] >> >> what it's trying to do is: >> >> tup[1] = tup[1].__iadd__([6, 7]) >> >> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but >> then Python tries to put the result that the method returns into tup[1]. >> That fails because tup itself is a tuple, which is immutable. > > I think I might have found a bug: > > $ python > Python 2.7.3 (default, Jun 22 2015, 19:33:41) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> tup = [1,2,3],[4,5,6] >>>> tup > ([1, 2, 3], [4, 5, 6]) >>>> tup[1] > [4, 5, 6] >>>> tup[1] += [7,8,9] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment >>>> tup[1] > [4, 5, 6, 7, 8, 9] >>>> tup > ([1, 2, 3], [4, 5, 6, 7, 8, 9]) >>>> quit() No, that's the expected result. As MRAB wrote, the list *is* mutated when its __iadd__ method is called. The TypeError happens afterward when the assignment is attempted. From rantingrickjohnson at gmail.com Tue Dec 1 16:15:08 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 1 Dec 2015 13:15:08 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> Message-ID: <4327593e-9b6a-49f0-9b11-addda7906a29@googlegroups.com> On Tuesday, December 1, 2015 at 10:56:27 AM UTC-6, John Gordon wrote: > Rick Johnson writes: > > Your lament does remind me of a pet peeve i have concerning Python, and > > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) > > WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to > > achieve the same output.=20 > > The koan reads: > > There should be one-- and preferably only one --obvious way to do it. > > You left out the rather important word "obvious". Indeed you are correct about the wording, but your interpretation is wrong. In fact, adding the word "obvious" only adds more truth to my argument. The word "obvious" does not imply that the choose method is "one *OBVIOUS* choice in a set of many choices", no, the word obvious merely implies intuitiveness. Let's dissect the "koan" component by component: "There should be one" This component is less of a request, and more of a demand. It seems the author wishes to stress that whatever follows, there should only be one of them. "and preferably only one" Interesting. Utilizing his advanced intellect, the author realizes that confining any set of choices to a length of one is not always possible, however, he *AGAIN* stresses the importance of length one! I'm beginning to see a common and obvious theme here, do you? "obvious way to do it" And finally we encounter the obviousness of the one chosen way! The three components can be summarized as follows: First he demands a length of one, then he allows for exceptions while again stressing the importance of "one", and finally he stresses the importance of intuitiveness by using the word "obvious". In *NONE* of these components does the author *ENCOURAGE* a set of choices, no, he consistently stresses the importance of "one". And although it seems he has lost his will within the middle component (by entertaining the "unpreferred" possibility of more than one choice) he did not do so because his argument for "one" is weak, rather because, he knows that conflict and contrarianism is inevitable in a world that is ruled by selfish hairless apes! He has both demanded, and made an impassioned plea for, the "one obvious way" to do it. Any other interpretation is pure emotional projection. PS: Now that I've defeated the claim that "the koan is encouraging more than one way", as a last resort, they will dismiss the koan as unimportant. This is not my first experience here folks!!! PPS: Koan must be word of the day. From tjreedy at udel.edu Tue Dec 1 16:18:49 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Dec 2015 16:18:49 -0500 Subject: Could you explain this rebinding (or some other action) on "nums = nums"? In-Reply-To: References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On 12/1/2015 3:32 PM, Denis McMahon wrote: > On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: > >> In the case of: >> >> tup[1] += [6, 7] >> >> what it's trying to do is: >> >> tup[1] = tup[1].__iadd__([6, 7]) >> >> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but >> then Python tries to put the result that the method returns into tup[1]. >> That fails because tup itself is a tuple, which is immutable. > > I think I might have found a bug: What you found is an specific example of what MRAB said in general above. > $ python > Python 2.7.3 (default, Jun 22 2015, 19:33:41) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> tup = [1,2,3],[4,5,6] >>>> tup > ([1, 2, 3], [4, 5, 6]) >>>> tup[1] > [4, 5, 6] >>>> tup[1] += [7,8,9] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment The bug is trying to replace a member of a tuple. The correct code, to avoid the exception while extending the list, is tup[1].extend([7,8,9]) >>>> tup[1] > [4, 5, 6, 7, 8, 9] -- Terry Jan Reedy From manolo at austrohungaro.com Tue Dec 1 16:31:00 2015 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 1 Dec 2015 22:31:00 +0100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> Message-ID: <20151201213100.GA9665@beagle.localdomain> Peter, thanks for taking the time to look into my code. On 12/01/15 at 11:40am, Peter Otten wrote: > Manolo Mart?nez wrote: > > def main(): # parse the args and call whatever function was > selected > > try: > > args = parser.parse_args(sys.argv[1:]) > > args.func(vars(args)) > > except AttributeError as err: > > if str(err) == "\'Namespace\' object has no > attribute \'func\'": > > parser.print_help() > > else: > > print("Something has gone wrong: > {}".format(err), file = sys.stderr, flush = True) > > What probably is typical for a beginner in that snippet is that you don't > trust the exception system and handle exceptions that will never occur once > the script is debugged. Just write > > args = parser.parse_args() > args.func(vars(args)) Well, one fully possible situation is for the user to mistype a subcommand. In that case, the script outputs the help provided by argparse, so that they know what is and isn't meaningful. That is what the "if str(err)..." is doing. The else clause is there to output the traceback (in full trust of the exception system ;) in case the error was not due to the user mistyping. Is there a better way to do this? > Now vars(). I see nothing wrong with it, but when I look into one of your > func implementations > > > def info(args): # Provides information of a number of feeds > > session = Session(args) > > if "all" in args["names"]: > > feeds = session.list_feeds() > > else: > > feeds = args["names"] > > for feed in feeds: > > pretty_print(session, feed) > > I come to the conclusion that passing args directly could make your life > easier: > > def info(args): > """Provides information of a number of feeds""" > session = Session(args) > if "all" in args.names: > feeds = session.list_feeds() > else: > feeds = args.names > for feed in feeds: > pretty_print(session, feed) > > As far as I can see there is only one place where the key is not a constant, > and you can rewrite that from > > > try: > > if args[value]: > > return args[value] > > except KeyError: > > pass > > to > > try: > answer = getattr(args, value) > if answer: > return answer > except AttributeError: > pass > This is very helpful, thanks a lot! Manolo From python at lucidity.plus.com Tue Dec 1 16:31:15 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 1 Dec 2015 21:31:15 +0000 Subject: I can't understand re.sub In-Reply-To: References: Message-ID: <565E11A3.4040201@lucidity.plus.com> On 01/12/15 05:28, Jussi Piitulainen wrote: > A real solution should be aware of the actual structure of those lines, > assuming they follow some defined syntax. I think that we are in violent agreement on this ;) E. From denismfmcmahon at gmail.com Tue Dec 1 16:36:18 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 1 Dec 2015 21:36:18 -0000 (UTC) Subject: Could you explain this rebinding (or some other action) on "nums = nums"? References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On Tue, 01 Dec 2015 16:18:49 -0500, Terry Reedy wrote: > On 12/1/2015 3:32 PM, Denis McMahon wrote: >> On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: >> >>> In the case of: >>> >>> tup[1] += [6, 7] >>> >>> what it's trying to do is: >>> >>> tup[1] = tup[1].__iadd__([6, 7]) >>> >>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but >>> then Python tries to put the result that the method returns into >>> tup[1]. >>> That fails because tup itself is a tuple, which is immutable. >> >> I think I might have found a bug: > > What you found is an specific example of what MRAB said in general > above. > >> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) >> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" >> for more information. >>>>> tup = [1,2,3],[4,5,6] >>>>> tup >> ([1, 2, 3], [4, 5, 6]) >>>>> tup[1] >> [4, 5, 6] >>>>> tup[1] += [7,8,9] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment > > The bug is trying to replace a member of a tuple. The correct code, to > avoid the exception while extending the list, is > > tup[1].extend([7,8,9]) > >>>>> tup[1] >> [4, 5, 6, 7, 8, 9] You snipped the important bit of my original post, which was the state of tup after the TypeError occurred. After the error, >>> tup[1] [4, 5, 6, 7, 8, 9] >>> tup ([1, 2, 3], [4, 5, 6, 7, 8, 9]) The "bug" I refer to is that despite giving the TypeError, the tuple allowed the assignment of the mutated list to replace the original list. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Tue Dec 1 16:37:56 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 1 Dec 2015 21:37:56 -0000 (UTC) Subject: Could you explain this rebinding (or some other action) on "nums = nums"? References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On Tue, 01 Dec 2015 14:44:38 -0600, Ian Kelly wrote: > On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon > wrote: >> On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: >> >>> In the case of: >>> >>> tup[1] += [6, 7] >>> >>> what it's trying to do is: >>> >>> tup[1] = tup[1].__iadd__([6, 7]) >>> >>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but >>> then Python tries to put the result that the method returns into >>> tup[1]. >>> That fails because tup itself is a tuple, which is immutable. >> >> I think I might have found a bug: >> >> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) >> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" >> for more information. >>>>> tup = [1,2,3],[4,5,6] >>>>> tup >> ([1, 2, 3], [4, 5, 6]) >>>>> tup[1] >> [4, 5, 6] >>>>> tup[1] += [7,8,9] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >>>>> tup[1] >> [4, 5, 6, 7, 8, 9] >>>>> tup >> ([1, 2, 3], [4, 5, 6, 7, 8, 9]) >>>>> quit() > > No, that's the expected result. As MRAB wrote, the list *is* mutated > when its __iadd__ method is called. The TypeError happens afterward when > the assignment is attempted. The assignment succeeds. That's imo a bug. If it's a TypeError to try and assign a value to tup[1], then tup[1] should not allow the mutated list to be assigned. -- Denis McMahon, denismfmcmahon at gmail.com From omar.aboumrad at gmail.com Tue Dec 1 17:24:41 2015 From: omar.aboumrad at gmail.com (Omar Abou Mrad) Date: Wed, 2 Dec 2015 00:24:41 +0200 Subject: Pylint 1.5.0 / Astroid 1.4.1 released In-Reply-To: References: Message-ID: On Tue, Dec 1, 2015 at 1:42 AM, Claudiu Popa wrote: > Hello, > > > I'm happy to announce you the release of Pylint 1.5.0, > respectively Astroid 1.4.1. > > > > Claudiu > -- > https://mail.python.org/mailman/listinfo/python-list > Awesome! Congrats! From python at lucidity.plus.com Tue Dec 1 17:34:13 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 1 Dec 2015 22:34:13 +0000 Subject: Could you explain this rebinding (or some other action) on "nums = nums"? In-Reply-To: References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: <565E2065.1050704@lucidity.plus.com> On 01/12/15 21:37, Denis McMahon wrote: > The assignment succeeds. That's imo a bug. If it's a TypeError to try and > assign a value to tup[1], then tup[1] should not allow the mutated list > to be assigned. Nothing got assigned. That original list object remains in that slot. However, it has been mutated since it was originally assigned. But I can see what you're getting at - what you're asking for is that the *container* object whose element is being assigned to is first queried as to whether it will accept a mutated element being assigned to it before that element is mutated. This looks to be a fundamental issue with the augmented assignment mechanism. E. From tjreedy at udel.edu Tue Dec 1 17:37:34 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Dec 2015 17:37:34 -0500 Subject: Could you explain this rebinding (or some other action) on "nums = nums"? In-Reply-To: References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> Message-ID: On 12/1/2015 4:36 PM, Denis McMahon wrote: > On Tue, 01 Dec 2015 16:18:49 -0500, Terry Reedy wrote: > >> On 12/1/2015 3:32 PM, Denis McMahon wrote: >>> On Tue, 01 Dec 2015 03:32:31 +0000, MRAB wrote: >>> >>>> In the case of: >>>> >>>> tup[1] += [6, 7] >>>> >>>> what it's trying to do is: >>>> >>>> tup[1] = tup[1].__iadd__([6, 7]) >>>> >>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but >>>> then Python tries to put the result that the method returns into >>>> tup[1]. >>>> That fails because tup itself is a tuple, which is immutable. >>> >>> I think I might have found a bug: >> >> What you found is an specific example of what MRAB said in general >> above. >> >>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) >>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" >>> for more information. >>>>>> tup = [1,2,3],[4,5,6] >>>>>> tup >>> ([1, 2, 3], [4, 5, 6]) >>>>>> tup[1] >>> [4, 5, 6] >>>>>> tup[1] += [7,8,9] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'tuple' object does not support item assignment >> >> The bug is trying to replace a member of a tuple. The correct code, to >> avoid the exception while extending the list, is >> >> tup[1].extend([7,8,9]) >> >>>>>> tup[1] >>> [4, 5, 6, 7, 8, 9] > > You snipped the important bit of my original post, which was the state of > tup after the TypeError occurred. No I did not. The change to tup[1] right there above, after giving the correct way to make the change. > After the error, >>>> tup[1] > [4, 5, 6, 7, 8, 9] This is exactly what I posted. >>>> tup > ([1, 2, 3], [4, 5, 6, 7, 8, 9]) This is a repeat of the same thing and adds no new info. > The "bug" I refer to is that despite giving the TypeError, the tuple > allowed the assignment of the mutated list to replace the original list. No it did not. As MRAB noted, the list is mutated and the attempted assignment causes an exeption. This has been discussed before more than once ever since augmented *assignment* was introduced. >>> tup = ([],[]) >>> id(tup[1]) 711662188872 >>> tup[1] += [1] Traceback (most recent call last): File "", line 1, in tup[1] += [1] TypeError: 'tuple' object does not support item assignment >>> tup[1] [1] >>> id(tup[1]) 711662188872 >>> tup[1] = tup[1].extend([2]) Traceback (most recent call last): File "", line 1, in tup[1] = tup[1].extend([2]) TypeError: 'tuple' object does not support item assignment >>> tup[1] [1, 2] >>> id(tup[1]) 711662188872 Reading the augmented assignment doc carefully should make it clear that "tup[1] += [1]" is the same as "tup[1] = tup[1].extend([2])" except that evaluation of "tup[1]" happens just once instead of twice. -- Terry Jan Reedy From __peter__ at web.de Tue Dec 1 17:41:20 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Dec 2015 23:41:20 +0100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> Message-ID: Manolo Mart?nez wrote: > Peter, thanks for taking the time to look into my code. > > On 12/01/15 at 11:40am, Peter Otten wrote: >> Manolo Mart?nez wrote: >> > def main(): # parse the args and call whatever function was >> selected >> > try: >> > args = parser.parse_args(sys.argv[1:]) >> > args.func(vars(args)) >> > except AttributeError as err: >> > if str(err) == "\'Namespace\' object has no >> attribute \'func\'": >> > parser.print_help() >> > else: >> > print("Something has gone wrong: >> {}".format(err), file = sys.stderr, flush = True) >> >> What probably is typical for a beginner in that snippet is that you don't >> trust the exception system and handle exceptions that will never occur >> once the script is debugged. Just write >> >> args = parser.parse_args() >> args.func(vars(args)) > > Well, one fully possible situation is for the user to mistype a > subcommand. In that case, the script outputs the help provided by > argparse, so that they know what is and isn't meaningful. That is what > the "if str(err)..." is doing. > > The else clause is there to output the traceback (in full trust of the > exception system ;) in case the error was not due to the user mistyping. > > Is there a better way to do this? As far as I can see in a correctly written script the AttributeError cannot be triggered by the user as argparse handles this case automatically by showing the help. For example: $ cat subparsers.py #!/usr/bin/env python3 import argparse def foo(args): print(args) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() foo_parser = subparsers.add_parser("foo") foo_parser.set_defaults(func=foo) bar_parser = subparsers.add_parser("bar") # programming error --> missing func attribute args = parser.parse_args() args.func(args) main() $ ./subparsers.py foo Namespace(func=) $ ./subparsers.py bar Traceback (most recent call last): File "./subparsers.py", line 23, in main() File "./subparsers.py", line 20, in main args.func(args) AttributeError: 'Namespace' object has no attribute 'func' $ ./subparsers.py baz # erroneous user input usage: subparsers.py [-h] {foo,bar} ... subparsers.py: error: invalid choice: 'baz' (choose from 'foo', 'bar') The traceback may be a bit intimidating, but with your error handling the user will get $ cat subparsers2.py #!/usr/bin/env python3 import argparse def foo(args): print(args) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() foo_parser = subparsers.add_parser("foo") foo_parser.set_defaults(func=foo) bar_parser = subparsers.add_parser("bar") # programming error --> missing func attribute try: args = parser.parse_args() args.func(args) except AttributeError as err: if str(err) == "\'Namespace\' object has no attribute \'func\'": print("WE ARE HERE") parser.print_help() else: print("Something has gone wrong: {}".format(err), file = sys.stderr, flush = True) main() $ ./subparsers2.py foo Namespace(func=) $ ./subparsers2.py baz # erroneous user input does not trigger your error handling usage: subparsers2.py [-h] {foo,bar} ... subparsers2.py: error: invalid choice: 'baz' (choose from 'foo', 'bar') $ ./subparsers2.py bar # but an error in your script does WE ARE HERE usage: subparsers2.py [-h] {foo,bar} ... positional arguments: {foo,bar} optional arguments: -h, --help show this help message and exit which is very confusing. Again, don't replace the traceback unless you are absolutely sure you can do better than the Python interpreter. By the way, I recommend coverage.py to find dead code. I have not used it for too long, and I regret it ;) From python at lucidity.plus.com Tue Dec 1 17:44:53 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 1 Dec 2015 22:44:53 +0000 Subject: Could you explain this rebinding (or some other action) on "nums = nums"? In-Reply-To: <565E2065.1050704@lucidity.plus.com> References: <94c2e42e-1e5f-40cf-9259-26035e277bf3@googlegroups.com> <565E2065.1050704@lucidity.plus.com> Message-ID: <565E22E5.3030307@lucidity.plus.com> Apologies for self-replying, On 01/12/15 22:34, Erik wrote: > what you're asking for is that > the *container* object whose element is being assigned to is first > queried as to whether it will accept a mutated element being assigned to > it before that element is mutated. What I said above is rubbish. The situation is approximately similar to: a = [4, 5, 6] t = ([1, 2, 4], a) a.append(7) a.append(8) a.append(9) The point is, you're mutating something that an immutable object contains. In the example you give, that's caught because of the subsequent explicit assignment. In the example above, it's not caught. But it's the same thing. E. From rosuav at gmail.com Tue Dec 1 18:05:57 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 10:05:57 +1100 Subject: "Downloading" In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, Dec 2, 2015 at 6:05 AM, Random832 wrote: > On 2015-12-01, Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > > I'm a little bit confused as to what kinds of file transfers > you think don't have at least two endpoints. >From some other computer to the one you're controlling it from. A download is initiated by the recipient; an upload is initiated by the sender. ChrisA From ian.g.kelly at gmail.com Tue Dec 1 18:28:30 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Dec 2015 17:28:30 -0600 Subject: "Downloading" In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Tue, Dec 1, 2015 at 5:05 PM, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 6:05 AM, Random832 wrote: >> On 2015-12-01, Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> I'm a little bit confused as to what kinds of file transfers >> you think don't have at least two endpoints. > > From some other computer to the one you're controlling it from. A > download is initiated by the recipient; an upload is initiated by the > sender. What about transfers that are initiated by neither? scp remote_host1:path/to/file remote_host2:path/to/destination From rosuav at gmail.com Tue Dec 1 18:32:51 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 10:32:51 +1100 Subject: "Downloading" In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, Dec 2, 2015 at 10:28 AM, Ian Kelly wrote: > On Tue, Dec 1, 2015 at 5:05 PM, Chris Angelico wrote: >> On Wed, Dec 2, 2015 at 6:05 AM, Random832 wrote: >>> On 2015-12-01, Steve Hayes wrote: >>>> You download things FROM a computer, you upload them TO a computer. >>> >>> I'm a little bit confused as to what kinds of file transfers >>> you think don't have at least two endpoints. >> >> From some other computer to the one you're controlling it from. A >> download is initiated by the recipient; an upload is initiated by the >> sender. > > What about transfers that are initiated by neither? > > scp remote_host1:path/to/file remote_host2:path/to/destination I'd punt and call it a "transfer", same as you just did :) ChrisA From python at lucidity.plus.com Tue Dec 1 18:37:26 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 1 Dec 2015 23:37:26 +0000 Subject: "Downloading" In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <565E2F36.6030808@lucidity.plus.com> On 01/12/15 23:28, Ian Kelly wrote: > What about transfers that are initiated by neither? > > scp remote_host1:path/to/file remote_host2:path/to/destination Regardless of how the transfer is invoked, in traditional parlance the source uploads, the target downloads. Why is this on the Python list? ;) E. From steve at pearwood.info Tue Dec 1 18:42:39 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 10:42:39 +1100 Subject: python domain in China. This showed up on Python list References: <201512011010.tB1AANt0032057@fido.openend.se> Message-ID: <565e3070$0$1621$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Dec 2015 10:49 pm, Laura Creighton wrote: > In a message of Tue, 01 Dec 2015 02:51:21 -0800, Chris Rebert writes: >>I hate to break it to you, but this seems to be just another of those >>come-ons spammed out by various scummy businesses that trawl WHOIS >>databases for people to scam into buying extra/unnecessary domain >>names. Google "chinese domain scam" for more info. I've received >>similar spams after having registered some .com domains that no >>corporation could possibly legitimately want the .cn equivalents of. > > Ah... Thank you Chris. Sure fooled me. You're not the only one. At my day job, we get dozens of these, about one or two a month, and the first time it happened, I responded, at which point they told us that if we paid $MANY we could register the domain .cn before somebody else did. At that point, we lost interest, as we have no business interests in China. If somebody wants to register our name in China, let them. -- Steven From steve at pearwood.info Tue Dec 1 18:46:55 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 10:46:55 +1100 Subject: "Downloading" References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <565e3173$0$1611$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 06:05 am, Random832 wrote: > On 2015-12-01, Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > > I'm a little bit confused as to what kinds of file transfers > you think don't have at least two endpoints. If you have a computer with two network connections, plug a cable from one to the other, and now you can download stuff from yourself in half the time it would take to download from the Cloud. -- Steven From rosuav at gmail.com Tue Dec 1 18:56:28 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 10:56:28 +1100 Subject: "Downloading" In-Reply-To: <565e3173$0$1611$c3e8da3$5496439d@news.astraweb.com> References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> <565e3173$0$1611$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Dec 2, 2015 at 10:46 AM, Steven D'Aprano wrote: > On Wed, 2 Dec 2015 06:05 am, Random832 wrote: > >> On 2015-12-01, Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> I'm a little bit confused as to what kinds of file transfers >> you think don't have at least two endpoints. > > If you have a computer with two network connections, plug a cable from one > to the other, and now you can download stuff from yourself in half the time > it would take to download from the Cloud. If you have a computer with both wired and wireless network, plug half a cable into the wired network, and download stuff from yourself over 401.5?! ChrisA From greg.ewing at canterbury.ac.nz Tue Dec 1 19:14:29 2015 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 02 Dec 2015 13:14:29 +1300 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> Message-ID: Rick Johnson wrote: > the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO > IT!". You're misquoting the Zen. It says there should be one *obvious* way to do it. -- Greg From skybuck2000 at hotmail.com Tue Dec 1 19:22:28 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Wed, 2 Dec 2015 01:22:28 +0100 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <32371$565e3a1e$d47876e2$6836@news.ziggo.nl> It's not YOU doing it. Since you obviously don't understand that it's not worth reading anything else you wrote LOL. Bye, Skybuck. From steve at pearwood.info Tue Dec 1 19:57:58 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 11:57:58 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> Message-ID: <565e4219$0$1612$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 07:33 am, Rick Johnson wrote: > On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote: >> Python was never intended to be "merely" a teaching language. I think >> Guido's original vision was for it to be a glue language between C >> libraries, and a scripting language. > > It's a well know fact that GvR was inspired to create Python from his > experiences working with a language called ABC -- and ABC was designed > *EXCLUSIVELY* to be a beginners language. Certainly. But do you have any evidence that *Python* was designed to be exclusively a beginner's language? It is possible to be inspired by a teaching language without aiming to be limited to the functionality of a teaching language. >> > Rick said: >> > (1) How do you output a message without the print function? >> > Steven said: >> *scratches head* >> >> Why would you want to do that? print is clearly the "one obvious way" to >> output a message. > > Well of course the answers are *OBVIOUS* when you already *KNOW* them > Steven! Climb down off your high horse for a moment, and take yourself > back to a time *BEFORE* you had any knowledge of output streams. What's an output stream? All I know is that if you want to print a message, calling "print" is the obvious way to do it. Using the word "print" for writing text on the screen is very common, although not ubiquitous. Rosetta Code includes over 300 examples of the "Hello World" program, and a quick glance at the page shows that (apart from deliberately obfuscatory languages and assembly languages), print is one of the more common functions used: http://rosettacode.org/wiki/Hello_world/Text Others include: echo puts write writeln printf println display console.log cout say System.Console.WriteLine which vary in their obviousness. [...] > Ponder the following example code (as a noob!): > > stdout.write("Dude, i found my car, the hood, and the effing engine!!!") > > Even a noob can intuit what is going on here. First we have an *OBJECT* > named "stdout, and we can extrapolate that stdout is an abbreviation for > StandardOutput. Next, we see a method called "write", and, if our IQ is > above room temperature, then we can extrapolate what that method will do. Are you serious? You think that a complete beginner to programming is going to have an intuitive grasp of stdout? What did you say earlier about putting aside my knowledge of output streams? > Now ponder this code (as a noob!): > > print("Dude, where's the intuitiveness?") > > What the heck does print do? It's a standard English word, and has been since at least 1469, and possibly as long ago as 1150. As a native English speaker, I'm surprised that your vocabulary is so lacking that you need help with that, especially as an American. Didn't they teach you "printing" (block letters) and "cursive" (joined up letters) handwriting when you were at school? > Where will the string go after i execute this > line of code? Should i turn my printer on? Should i check my ink levels? > And what OEM drivers are required? That's an interesting point. In, oh, a dozen or more years of dealing with Python beginners, I have come across *exactly one* beginner who assumed that print would send output to the printer. Where there's one, there are probably more, but I think it is fair to say that the idea of *printing to the screen* is commonplace, and these days probably even more common than the idea of printing to paper. I expect that kids learning BASIC in the 1970s probably had more difficulty with the concept, but even then, that difficulty would extend to as long as it takes somebody to say "it prints the message to the screen". > Not only is "print" un-intuitive (by nature of it's naming), it is > obfuscating the path to the underlying process of "sending data to an > output stream". A wise man once said to me, "take yourself back to a time *BEFORE* you had any knowledge of output streams". Although I suspect perhaps he was more of a wise guy than a wise man. -- Steven From steve at pearwood.info Tue Dec 1 20:02:31 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 12:02:31 +1100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Dec 2015 08:15 pm, Grobu wrote: > Perhaps you could use a parameter's default value to implement your > static variable? > > Like : > # ------------------------------------------------- > >>> def test(arg=[0]): > ... print arg[0] > ... arg[0] += 1 > ... Awesome! I'm not being sarcastic, I'm serious. Thank you Grobu, for demonstrating the existence of something we debated a few days ago. In another *painfully* long thread about mutable default arguments, I suggested the same idea: using a mutable default as static storage. It is very gratifying to see that other people have independently come up with the same idea. -- Steven From steve at pearwood.info Tue Dec 1 20:12:56 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 12:12:56 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565e459b$0$1615$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Dec 2015 07:44 pm, Manolo Mart?nez wrote: > On 12/01/15 at 12:00pm, Steven D'Aprano wrote: >> I'm trying to understand why vars() exists. Does anyone use it? > > Well, I have this little podcast aggregator > (https://github.com/manolomartinez/greg) that I and a bunch of other > people use. I started writing it some years ago, and the code is a bit > of a palimpsest, newer functionality reflecting my (somewhat) better > understanding of the language. One of the oldest bits is this main() > function: > > def main(): # parse the args and call whatever function was selected > try: > args = parser.parse_args(sys.argv[1:]) > args.func(vars(args)) > except AttributeError as err: > if str(err) == "\'Namespace\' object has no attribute \'func\'": > parser.print_help() > else: > print("Something has gone wrong: {}".format(err), > file = sys.stderr, flush = True) > > > To judge by this thread, this is probably wrong/noobish? I've seen worse :-) Checking the error message in that way is risky. As an absolute last resort, I guess it works, but it's hack-ish (not in a good way) and fragile. The problem is, error messages are not part of the Python API and are subject to change without warning. (Aside: when I design my language, I'm going to ensure that error messages vary from one exception to the next, specifically to discourage this :-) Today, you get an error message "'Namespace' object has no attribute 'func'" (note that there is no need to escape the single quotes) but there's no guarantee that this will always be the same. Tomorrow it could silently change to: '"Namespace" instance does not have a "func" attribute.' and your code will break. Better and safer is: def main(): # parse the args and call whatever function was selected args = parser.parse_args(sys.argv[1:]) try: func = args.func except AttributeError as err: parser.print_help() else: func(vars(args)) -- Steven From python at lucidity.plus.com Tue Dec 1 20:16:37 2015 From: python at lucidity.plus.com (Erik) Date: Wed, 2 Dec 2015 01:16:37 +0000 Subject: static variables In-Reply-To: <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565E4675.7050102@lucidity.plus.com> On 02/12/15 01:02, Steven D'Aprano wrote: > On Tue, 1 Dec 2015 08:15 pm, Grobu wrote: >> # ------------------------------------------------- >> >>> def test(arg=[0]): >> ... print arg[0] >> ... arg[0] += 1 > Awesome! Hideous! > using a mutable default as static storage. Exposing something a caller can override as a local, static, supposedly "private" value is IMHO a tad ... ugly? (*) E. (*) No I don't want to resurrect that thread. From steve at pearwood.info Tue Dec 1 20:24:46 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 12:24:46 +1100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 12:16 pm, Erik wrote: > On 02/12/15 01:02, Steven D'Aprano wrote: >> On Tue, 1 Dec 2015 08:15 pm, Grobu wrote: >>> # ------------------------------------------------- >>> >>> def test(arg=[0]): >>> ... print arg[0] >>> ... arg[0] += 1 >> Awesome! > > Hideous! > >> using a mutable default as static storage. > > Exposing something a caller can override as a local, static, supposedly > "private" value is IMHO a tad ... ugly? (*) Heh, I agree, and as I suggested, it might be good to have an actual mechanism for static locals. But using a class is no better: your "static storage" is exposed as an instance attribute, and even if you flag it private, *somebody* is going to mess with it. A closure works, but that obfuscates the code: def make_test(): arg = [0] def test(): print arg[0] arg[0] += 1 return test test = make_test() Or in Python 3: def make_test(): arg = 0 def test(): nonlocal arg print arg arg += 1 return test test = make_test() Python has three not-entirely-awful solutions to the problem of static locals, but no really great or obvious one. -- Steven From ben+python at benfinney.id.au Tue Dec 1 20:47:40 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 02 Dec 2015 12:47:40 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> Message-ID: <851tb58vur.fsf@benfinney.id.au> Steven D'Aprano writes: > You misunderstand the koan. > > "There should be one way to do it" does not prohibit more than one > way. Further, that's omitting a very important modifier from the koan. Even without the parenthetical, the koan reads: There should be one obvious way to do it. So yes, there can certainly be multiple ways to do it. But it's very important that there be one *obvious* way. In other words: Don't present the user with a multitude of options with no *obvious* choice for those who don't care (yet) to learn about the choice. Make one of them *obvious* so that's the usually-correct choice. > (Although having multiple redundant ways is discouraged.) The koan > exists to encourage the existence of *at least* one (but preferably > only one) way to do it. And the Pythonic approach is to make an *obvious* way to do it. As you say, ?print? is that one obvious way for emitting simple text output. -- \ ?What's another word for Thesaurus?? ?Steven Wright | `\ | _o__) | Ben Finney From robertvstepp at gmail.com Tue Dec 1 21:20:51 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 1 Dec 2015 20:20:51 -0600 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano wrote: > > Either way, vars() doesn't solve the problem. What problem does it solve? > I'm way out of my depth here (I normally post on Tutor, as Steve knows), but when I looked vars() up in Lutz's "Python Pocket Reference, 5th ed.", he ended his description of it with: "... Hint: useful for referring to variables in string formatting." This is probably something obvious to you, but I thought I'd throw it out there in case it's of any value, since I did not see this mentioned elsewhere in this thread. Just trying to learn more ... -- boB From dbezan at yahoo.com Tue Dec 1 22:11:31 2015 From: dbezan at yahoo.com (bezan deme) Date: Wed, 2 Dec 2015 03:11:31 +0000 (UTC) Subject: Installation of Python troubles References: <1177707260.13720398.1449025891153.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1177707260.13720398.1449025891153.JavaMail.yahoo@mail.yahoo.com> Dear supporters, I tried several times to install the Python 3.5.0 (windows x86 executable installer) in my PC then in my LT and in both cases I failed. Last time, few hours ago, I tried it again, then it opened a window with a sole "cancel" button on it. I waited for 10-15 min without anything to seem to happen, then I tried to click on the open parts of the window just above the "cancel" button. Then it started a procedure of "uninstalling the Python" and after 5-10 minutes it delivered the message of "successfully uninstalling" a program which was neven installed, with a "close" button!I have downloaded the .exe Python version for 32-bit machine of 27,950KB size, for more than 3 times, in case s/th went wrong with the connection, from your main website.I tried it in 2 PC's and 3 laptops, with similar results (the installation process failed - unspecified error, etc.). Could you suggest something??Thanks,Demetris From jfong at ms4.hinet.net Tue Dec 1 22:58:15 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Tue, 1 Dec 2015 19:58:15 -0800 (PST) Subject: python response slow when running external DLL In-Reply-To: References: <3ec6a016-dae5-4986-b035-c1a8cd4dc3e7@googlegroups.com> Message-ID: <78fd0a4e-50d0-49fd-8a36-94e376e45fc9@googlegroups.com> Peter Otten at 2015/12/1 UTC+8 7:01:55PM wrote? > While the var_status.set() invoked from the second thread modifies some > internal data the main thread could kick in and modify (parts of) that same > data, thus bringing tkinter into an broken state. A simple example that > demonstrates the problem: > > import random > import threading > import time > > account = 70 > > def withdraw(delay, amount): > global account > if account >= amount: > print("withdrawing", amount) > account -= amount > else: > print("failed to withdraw", amount) > > threads = [] > for i in range(10): > t = threading.Thread( > target=withdraw, > kwargs=dict(delay=.1, > amount=random.randrange(1, 20))) > threads.append(t) > t.start() > > for t in threads: > t.join() It's a simple and vivid example. You must be in the banking business:-) In this exercise, I can just use update_idletasks() method to solve the deferred display problem of tkinter, and forget all about thread. But what if I really want to use thread for the long-running DLL function in the download hander? I didn't figure out a correct way of doing it at this moment. Maybe queue is the answer but I am not familiar with it yet. def download(): var_status.set(...) #showing a start-up message result = SayHello() #this is a long-running function if result.... #according to the result, display more messages .... > > Before every withdrawal there seems to be a check that ensures that there is > enough money left, but when you run the script a few times you will still > sometimes end with a negative balance. That happens when thread A finds > enough money, then execution switches to thread B which also finds enough > money, then both threads perform a withdrawal -- oops there wasn't enough > money for both. > > >> Another complication that inevitably comes with concurrency: what if the > >> user triggers another download while one download is already running? If > >> you don't keep track of all downloads the message will already switch to > >> "Download OK" while one download is still running. > > > > Hummm...this thought never comes to my mind. After take a quick test I > > found, you are right, a second "download" was triggered immediately. > > That's a shock to me. I suppose the same event shouldn't be triggered > > again, or at least not triggered immediately, before its previous handler > > was completed. ...I will take a check later on Borland C++ builder to see > > how it reacts! > > > > Anyway to prevent this happens? if Python didn't take care it for us. > > A simple measure would be to disable the button until the download has > ended. Good! simple and work. I shouldn't say "Python should take care of it", but "tk" should do. It's annoying the widget's command was re-triggered before it was finished. (my personal opinion:-) From ian.g.kelly at gmail.com Tue Dec 1 23:48:57 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Dec 2015 22:48:57 -0600 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> Message-ID: On Dec 1, 2015 1:36 PM, "Rick Johnson" wrote: > > On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote: > > Python was never intended to be "merely" a teaching language. I think > > Guido's original vision was for it to be a glue language between C > > libraries, and a scripting language. > > It's a well know fact that GvR was inspired to create Python from his experiences working with a language called ABC -- and ABC was designed *EXCLUSIVELY* to be a beginners language. Which is exactly what made ABC itself unsuitable for Guido's purpose, which was to create an *applications* language with better productivity than C to support users of Amoeba, the OS that he was working on at the time. > I am not arguing that "abstractions are evil", no, my position is that abstractions must be constructed in a manner that provides a clear trail of bread crumbs which lead to the underlying processes. With print, not only is the engine in another dimension, but the hood is as well! How is a noob to discover the engine when he cannot find the hood? > > Ponder the following example code (as a noob!): > > stdout.write("Dude, i found my car, the hood, and the effing engine!!!") > > Even a noob can intuit what is going on here. First we have an *OBJECT* named "stdout, and we can extrapolate that stdout is an abbreviation for StandardOutput. Next, we see a method called "write", and, if our IQ is above room temperature, then we can extrapolate what that method will do. This is absurd. You postulate a beginner so rank that they can't understand what "print" means, yet you expect them to intuitively know: 1) what an object is; 2) what a method is; 3) that a method is identified by placing a period between the object and the name of the method; 4) what "output" is in the context of programming; 5) and not be confused about what makes the output "standard". > Now ponder this code (as a noob!): > > print("Dude, where's the intuitiveness?") > > What the heck does print do? Where will the string go after i execute this line of code? Should i turn my printer on? Should i check my ink levels? And what OEM drivers are required? You're describing this as if your hypothetical beginner were learning Python in a vacuum. In reality, people learn from a teacher, or a book, or at minimum a tutorial. Here's how you teach somebody what "print" does: instruct them to type print("hello world") at the interactive prompt. Note that Python writes "hello world" as a result. If they really want, they can check their printer and see that nothing came out. That's it. The student now understands what "print" means. From __peter__ at web.de Wed Dec 2 02:51:56 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Dec 2015 08:51:56 +0100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e459b$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > and your code will break. Better and safer is: > > > def main(): # parse the args and call whatever function was selected > args = parser.parse_args(sys.argv[1:]) > try: > func = args.func > except AttributeError as err: > parser.print_help() > else: > func(vars(args)) I don't think this is any better. You are reponding on a programming error in the script as if the user had provided erroneous input. Very confusing. Just args.func(vars(args)) will produce a traceback if the programmer made an error and a help message if the user provides arguments that are not recognized. That's how it should be. From antoon.pardon at rece.vub.ac.be Wed Dec 2 03:21:49 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 09:21:49 +0100 Subject: static variables In-Reply-To: <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565EAA1D.501@rece.vub.ac.be> Op 02-12-15 om 02:24 schreef Steven D'Aprano: > Python has three not-entirely-awful solutions to the problem of static > locals, but no really great or obvious one. I think python is unsuited for an obvious solution for static locals. Because you need to initialise your static variable somewhere. If you initialise whithin the body of your function, you will have a statement that is essentialy a declaration instead of an executable statement. Which goes totally against the dynamic nature op python. -- Antoon From storchaka at gmail.com Wed Dec 2 03:22:05 2015 From: storchaka at gmail.com (Serhiy Storchaka) Date: Wed, 2 Dec 2015 10:22:05 +0200 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 01.12.15 03:00, Steven D'Aprano wrote: > I'm trying to understand why vars() exists. Does anyone use it? I use vars() exclusively for introspection in interactive environment. As well as dir() and help(). Sad that it doesn't work with __slots__. From iamsexyarpit at gmail.com Wed Dec 2 03:31:39 2015 From: iamsexyarpit at gmail.com (Arpit Arya) Date: Wed, 2 Dec 2015 14:01:39 +0530 Subject: regarding download issues from sharepoint site Message-ID: hi, i am facing problem downloading files from sharepoint site and to display it on my web portal. i have used requests_ntlm module which gives successful authorisation but i am stuck in next step i.e. to download data from sharepoint site and dispaly on portal. please help me out Regards Arpit From antoon.pardon at rece.vub.ac.be Wed Dec 2 03:34:32 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 09:34:32 +0100 Subject: static variables In-Reply-To: <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565EAD18.2040701@rece.vub.ac.be> Op 02-12-15 om 02:24 schreef Steven D'Aprano: > Heh, I agree, and as I suggested, it might be good to have an actual > mechanism for static locals. But using a class is no better: your "static > storage" is exposed as an instance attribute, and even if you flag it > private, *somebody* is going to mess with it. Why don't you invoke the consenting adults now? People have come here arguing for all kind of extra features, which would somehow defend against messing with certain variable or attributes the author wants protected. The general respons has always been, that we are consenting adults here. Static variables, are just a feature to protect what is essentially a global variable against messing from somewhere else. So why is this feature worthy of discussion and others are not? -- Antoon. From nospam at thanks.invalid Wed Dec 2 03:57:44 2015 From: nospam at thanks.invalid (Juha Nieminen) Date: Wed, 2 Dec 2015 08:57:44 +0000 (UTC) Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: In comp.lang.c++ Steve Hayes wrote: > You download things FROM a computer, you upload them TO a computer. It's a matter of perspective. If a hacker breaks into your computer and starts a download from somewhere else into your computer, isn't the hacker "downloading" things to your computer? --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From manolo at austrohungaro.com Wed Dec 2 04:09:54 2015 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 2 Dec 2015 10:09:54 +0100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> Message-ID: <20151202090954.GC9665@beagle.localdomain> Dear Peter, and Steven, thanks again for engaging with my script. I'm fully aware that this is not the tutor mailing list :) Peter Otten wrote: > As far as I can see in a correctly written script the AttributeError cannot > be triggered by the user as argparse handles this case automatically by > showing the help. This... is true. I could have sworn that's not the way argparse behaved when I wrote that snippet, but I've been very wrong before about similar things. Anyway my main() function looks much better now :) > By the way, I recommend coverage.py to find dead code. I have not used > it for too long, and I regret it ;) I blush to confess I would first need to write a test suite. But yeah, will do both, thanks for the recommendation. Cheers, Manolo From manolo at austrohungaro.com Wed Dec 2 04:17:17 2015 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 2 Dec 2015 10:17:17 +0100 Subject: 4D arrays In-Reply-To: References: <08275b89237d46ae87ff574db3748dc2@cptec.inpe.br> Message-ID: <20151202091717.GD9665@beagle.localdomain> On 12/01/15 at 06:47pm, Peter Otten wrote: > Extract 2D arrays: > > >>> a[:,2,3] > array([[ 55, 56, 57, 58, 59], > [115, 116, 117, 118, 119]]) > >>> a[1,:,2] > array([[ 70, 71, 72, 73, 74], > [ 90, 91, 92, 93, 94], > [110, 111, 112, 113, 114]]) The first one is equivalent to a[:, 2, 3, :], which is perhaps clearer in this context: you are singling out row 2 in axis 1, and row 3 in axis 2, and taking everything from axes 0 and 3. Mutatis mutandis with the second example and a[1, :, 2, :], which is different from a[1, :, :, 2], etc. Manolo From rosuav at gmail.com Wed Dec 2 04:23:22 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 20:23:22 +1100 Subject: static variables In-Reply-To: <565EAA1D.501@rece.vub.ac.be> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> Message-ID: On Wed, Dec 2, 2015 at 7:21 PM, Antoon Pardon wrote: > I think python is unsuited for an obvious solution for static locals. > Because you need to initialise your static variable somewhere. If you > initialise whithin the body of your function, you will have a statement > that is essentialy a declaration instead of an executable statement. > Which goes totally against the dynamic nature op python. It ought to be initialized at the same time the function is defined - just like argument defaults, only without them being visible as arguments. If Python had a keyword that meant "currently-executing-function", that would work out well for attributes (and might also make recursion more optimizable); otherwise, default args are probably the cleanest way we have. ChrisA From rosuav at gmail.com Wed Dec 2 04:26:08 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 20:26:08 +1100 Subject: Installation of Python troubles In-Reply-To: <1177707260.13720398.1449025891153.JavaMail.yahoo@mail.yahoo.com> References: <1177707260.13720398.1449025891153.JavaMail.yahoo.ref@mail.yahoo.com> <1177707260.13720398.1449025891153.JavaMail.yahoo@mail.yahoo.com> Message-ID: On Wed, Dec 2, 2015 at 2:11 PM, bezan deme via Python-list wrote: > I tried several times to install the Python 3.5.0 (windows x86 executable installer) in my PC then in my LT and in both cases I failed. Last time, few hours ago, I tried it again, then it opened a window with a sole "cancel" button on it. Is this Windows XP? If so, you'll need to get a better operating system - either a newer version of Windows (7, 8, 10), or something Unix-based (Linux, *BSD, Mac OS). Windows XP doesn't support Python 3.5, and vice versa. ChrisA From rosuav at gmail.com Wed Dec 2 04:28:57 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 20:28:57 +1100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka wrote: > On 01.12.15 03:00, Steven D'Aprano wrote: >> >> I'm trying to understand why vars() exists. Does anyone use it? > > > I use vars() exclusively for introspection in interactive environment. As > well as dir() and help(). Sad that it doesn't work with __slots__. Maybe the upshot of all this is a post to python-ideas recommending that vars() grow support for __slots__ types? If it's most often used interactively, this would make it more useful there, and it wouldn't break backward compatibility unless there's some way that people are depending on it raising an exception. ChrisA From rosuav at gmail.com Wed Dec 2 04:33:17 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 20:33:17 +1100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <20151202090954.GC9665@beagle.localdomain> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> <20151202090954.GC9665@beagle.localdomain> Message-ID: On Wed, Dec 2, 2015 at 8:09 PM, Manolo Mart?nez wrote: > Peter Otten wrote: >> As far as I can see in a correctly written script the AttributeError cannot >> be triggered by the user as argparse handles this case automatically by >> showing the help. > > This... is true. I could have sworn that's not the way argparse behaved > when I wrote that snippet, but I've been very wrong before about similar > things. Anyway my main() function looks much better now :) I would recommend not using argparse directly. Pick up a wrapper like clize, and then define everything through docstrings. Clize usage example: https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py https://pypi.python.org/pypi/clize ChrisA From manolo at austrohungaro.com Wed Dec 2 04:40:33 2015 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 2 Dec 2015 10:40:33 +0100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> <20151202090954.GC9665@beagle.localdomain> Message-ID: <20151202094033.GA12749@beagle> On 12/02/15 at 08:33pm, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 8:09 PM, Manolo Mart?nez > > This... is true. I could have sworn that's not the way argparse behaved > > when I wrote that snippet, but I've been very wrong before about similar > > things. Anyway my main() function looks much better now :) > > I would recommend not using argparse directly. Pick up a wrapper like > clize, and then define everything through docstrings. > > Clize usage example: > https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py > > https://pypi.python.org/pypi/clize I try to do as much as I can with standard library tools. As a user, I find it somewhat off-putting when a tiny project asks you to install any number of seemingly unrelated libraries. But clize does look like a good idea, thanks for the pointer. Manolo From rjh at cpax.org.uk Wed Dec 2 04:42:50 2015 From: rjh at cpax.org.uk (Richard Heathfield) Date: Wed, 2 Dec 2015 09:42:50 +0000 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 02/12/15 08:57, Juha Nieminen wrote: > In comp.lang.c++ Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > > It's a matter of perspective. If a hacker breaks into your computer and > starts a download from somewhere else into your computer, isn't the hacker > "downloading" things to your computer? My understanding of the term has always been that you upload from a smaller device to a larger, and download from a larger device to a smaller. Thus, from your laptop you might *up*load data to a Web server or a mainframe, but you would *down*load data to your phone or tablet. If the devices are of comparable size and power, you aren't upping or downing anything - you're just transferring data from one computer to another. I suppose we could say "crossloading"? -- Richard Heathfield Email: rjh at cpax dot org dot uk "Usenet is a strange place" - dmr 29 July 1999 Sig line 4 vacant - apply within From antoon.pardon at rece.vub.ac.be Wed Dec 2 04:47:15 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 10:47:15 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> Message-ID: <565EBE23.9020402@rece.vub.ac.be> Op 02-12-15 om 10:23 schreef Chris Angelico: > On Wed, Dec 2, 2015 at 7:21 PM, Antoon Pardon > wrote: >> I think python is unsuited for an obvious solution for static locals. >> Because you need to initialise your static variable somewhere. If you >> initialise whithin the body of your function, you will have a statement >> that is essentialy a declaration instead of an executable statement. >> Which goes totally against the dynamic nature op python. > It ought to be initialized at the same time the function is defined - > just like argument defaults, only without them being visible as > arguments. I am not talking about the time. That could be done with something declarative too. I am talking about where to put in the code. > If Python had a keyword that meant > "currently-executing-function", that would work out well for > attributes (and might also make recursion more optimizable); > otherwise, default args are probably the cleanest way we have. No it wouldn't. Lets call that keyword cef. The fact that you can write: def foo(): cef.attr instead of def foo() foo.attr changes nothing about foo.attr being globally accessible. -- Antoon. From lcargill99 at comcast.com Wed Dec 2 05:09:32 2015 From: lcargill99 at comcast.com (Les Cargill) Date: Wed, 2 Dec 2015 04:09:32 -0600 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: Juha Nieminen wrote: > In comp.lang.c++ Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > > It's a matter of perspective. If a hacker breaks into your computer and > starts a download from somewhere else into your computer, isn't the hacker > "downloading" things to your computer? > > --- news://freenews.netfront.net/ - complaints: news at netfront.net --- > Down is towards an end node; up is towards the backbone. Servers live closer to the backbone. Usually. Or rather did when the nomenclature was forged. -- Les Cargill From marko at pacujo.net Wed Dec 2 05:18:56 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Dec 2015 12:18:56 +0200 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> Message-ID: <87a8ptcfvz.fsf@elektro.pacujo.net> Antoon Pardon : > def foo() > foo.attr > > changes nothing about foo.attr being globally accessible. I don't know why global accessibility is such a problem. Anyway, in practice I handle such "static" variables as module globals. If you want a more puristic solution, you could do: def _make_f(): x = 0 def f(): nonlocal x x += 1 return x return f f = _make_f() print(f()) => 1 print(f()) => 2 print(f()) => 3 Marko From steve at pearwood.info Wed Dec 2 05:22:32 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Dec 2015 21:22:32 +1100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 07:34 pm, Antoon Pardon wrote: > Op 02-12-15 om 02:24 schreef Steven D'Aprano: >> Heh, I agree, and as I suggested, it might be good to have an actual >> mechanism for static locals. But using a class is no better: your "static >> storage" is exposed as an instance attribute, and even if you flag it >> private, *somebody* is going to mess with it. > > Why don't you invoke the consenting adults now? Because I don't wish to. I can invoke consenting adults to defend people drinking soft drinks and eating chocolate, doesn't mean I have to invoke consenting adults to defend the practice of middle-class film-makers goading homeless people into fighting and other dangerous acts for trivial amounts of money. https://en.wikipedia.org/wiki/Bumfights > People have come here > arguing for all kind of extra features, which would somehow defend > against messing with certain variable or attributes the author wants > protected. The general respons has always been, that we are consenting > adults here. Yes, and that's fine. Consider the word *judgement* -- in our (the collective community) judgement, certain things are acceptable for consenting adults and others are not. But if it makes you feel better, if I were to champion this feature, I would suggest that the initialised static variable be stored in a writable dunder attribute of the function, just like default values are today. If you wanted to inspect, or even modify, the static variables, you could access function.__static__[x]. > Static variables, are just a feature to protect what is essentially > a global variable against messing from somewhere else. No, that's not the reason for static variables. The primary reasons for static variables are efficiency and encapsulation. Efficiency: consider a function that requires a considerable amount of initialisation, which only needs to be done once. In older languages like Pascal which lack static variables, you might perform that initialisation every time you call the function. Or, you might break encapsulation by storing something that belongs with the function outside the function. Static variables let you have your cake and eat it too: you can keep the variable with the function, avoiding namespace pollution, which still allowing the efficiency of having that variable calculated once only. > So why is > this feature worthy of discussion and others are not? Because I say so. Since it's my suggestion, that's the only reason I need. -- Steven From __peter__ at web.de Wed Dec 2 05:48:35 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Dec 2015 11:48:35 +0100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> <20151202090954.GC9665@beagle.localdomain> <20151202094033.GA12749@beagle> Message-ID: Manolo Mart?nez wrote: > On 12/02/15 at 08:33pm, Chris Angelico wrote: >> On Wed, Dec 2, 2015 at 8:09 PM, Manolo Mart?nez >> > This... is true. I could have sworn that's not the way argparse behaved >> > when I wrote that snippet, but I've been very wrong before about >> > similar things. Anyway my main() function looks much better now :) >> >> I would recommend not using argparse directly. Pick up a wrapper like >> clize, and then define everything through docstrings. >> >> Clize usage example: >> https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py >> >> https://pypi.python.org/pypi/clize > > I try to do as much as I can with standard library tools. As a user, I > find it somewhat off-putting when a tiny project asks you to install any > number of seemingly unrelated libraries. But clize does look like a good > idea, thanks for the pointer. Same here ;) From antoon.pardon at rece.vub.ac.be Wed Dec 2 05:56:45 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 11:56:45 +0100 Subject: static variables In-Reply-To: <87a8ptcfvz.fsf@elektro.pacujo.net> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> <87a8ptcfvz.fsf@elektro.pacujo.net> Message-ID: <565ECE6D.4090500@rece.vub.ac.be> Op 02-12-15 om 11:18 schreef Marko Rauhamaa: > Antoon Pardon : > >> def foo() >> foo.attr >> >> changes nothing about foo.attr being globally accessible. > I don't know why global accessibility is such a problem. Some people seem to have a problem with global variables. -- Antoon. From rosuav at gmail.com Wed Dec 2 06:02:06 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 22:02:06 +1100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <20151201084416.GA2700@beagle> <20151201213100.GA9665@beagle.localdomain> <20151202090954.GC9665@beagle.localdomain> <20151202094033.GA12749@beagle> Message-ID: On Wed, Dec 2, 2015 at 9:48 PM, Peter Otten <__peter__ at web.de> wrote: >> I try to do as much as I can with standard library tools. As a user, I >> find it somewhat off-putting when a tiny project asks you to install any >> number of seemingly unrelated libraries. But clize does look like a good >> idea, thanks for the pointer. > > Same here ;) I found out about clize by developing my own module that did the same job - and then found that, by compromising VERY slightly on some specifics, I could turn my usage directly to clize :) One thing I didn't want to compromise on was the simplicity of setup that I'd had - just slap a decorator onto every function that you want to make into a callable. So I made my own decorator that collects up the functions. Total cost: Three lines at the top, two at the bottom (if name is main, clize.run), and one line per function, plus the encoded docstring. That's a LOT cheaper than argparse normally is. ChrisA From antoon.pardon at rece.vub.ac.be Wed Dec 2 06:09:58 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 12:09:58 +0100 Subject: static variables In-Reply-To: <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565ED186.7020006@rece.vub.ac.be> Op 02-12-15 om 11:22 schreef Steven D'Aprano: > On Wed, 2 Dec 2015 07:34 pm, Antoon Pardon wrote: > >> Op 02-12-15 om 02:24 schreef Steven D'Aprano: >>> Heh, I agree, and as I suggested, it might be good to have an actual >>> mechanism for static locals. But using a class is no better: your "static >>> storage" is exposed as an instance attribute, and even if you flag it >>> private, *somebody* is going to mess with it. >> Why don't you invoke the consenting adults now? > Because I don't wish to. > > I can invoke consenting adults to defend people drinking soft drinks and > eating chocolate, doesn't mean I have to invoke consenting adults to defend > the practice of middle-class film-makers goading homeless people into > fighting and other dangerous acts for trivial amounts of money. > > https://en.wikipedia.org/wiki/Bumfights If you want your arguments to be taken seriously, then you better should. If you use an argument when it suits you and ignore it when it doesn't you are showing you don't really have an argument. You are just showing your preference and making it sound like an argument. >> People have come here >> arguing for all kind of extra features, which would somehow defend >> against messing with certain variable or attributes the author wants >> protected. The general respons has always been, that we are consenting >> adults here. > Yes, and that's fine. Consider the word *judgement* -- in our (the > collective community) judgement, certain things are acceptable for > consenting adults and others are not. Which makes "consenting adults" just empty posturing that means nothing more than /we like it that way/ or /we don't have a problem with that./ > But if it makes you feel better, if I were to champion this feature, I would > suggest that the initialised static variable be stored in a writable dunder > attribute of the function, just like default values are today. If you > wanted to inspect, or even modify, the static variables, you could access > function.__static__[x]. > > >> Static variables, are just a feature to protect what is essentially >> a global variable against messing from somewhere else. > No, that's not the reason for static variables. The primary reasons for > static variables are efficiency and encapsulation. No it isn't. Global variables are just as efficient and encapsulation is just one means to protect a variable against messing. Efficiency: consider a function that requires a considerable amount of initialisation, which only needs to be done once. In older languages like Pascal which lack static variables, you might perform that initialisation every time you call the function. Or, you might break encapsulation by storing something that belongs with the function outside the function. Static variables let you have your cake and eat it too: you can keep the variable with the function, avoiding namespace pollution, which still allowing the efficiency of having that variable calculated once only. >> So why is >> this feature worthy of discussion and others are not? > Because I say so. Since it's my suggestion, that's the only reason I need. > > > From marko at pacujo.net Wed Dec 2 06:30:31 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Dec 2015 13:30:31 +0200 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> <87a8ptcfvz.fsf@elektro.pacujo.net> Message-ID: <8737vlccko.fsf@elektro.pacujo.net> Antoon Pardon : > Op 02-12-15 om 11:18 schreef Marko Rauhamaa: >> I don't know why global accessibility is such a problem. > > Some people seem to have a problem with global variables. Well, *I* don't go around defining global variables, but there are times when they are the way to go. For example, if a module function uses a regular expression, the regular expression should be compiled into a (module) global variable. Module functions and classes are global variables as well: >>> import math >>> def f(x): return -1 ... >>> math.sqrt = f >>> math.sqrt(3) -1 Marko From eryksun at gmail.com Wed Dec 2 06:34:25 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 2 Dec 2015 05:34:25 -0600 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Dec 2, 2015 at 3:28 AM, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka wrote: >> >> I use vars() exclusively for introspection in interactive environment. As >> well as dir() and help(). Sad that it doesn't work with __slots__. > > Maybe the upshot of all this is a post to python-ideas recommending > that vars() grow support for __slots__ types? If it's most often used > interactively, this would make it more useful there, and it wouldn't > break backward compatibility unless there's some way that people are > depending on it raising an exception. Let vars() continue in its antediluvian ways. Maybe the standard library could add an inspect.getdata function that returns a union of an object's __dict__ items and data-descriptor attributes. From jkjkelly9 at gmail.com Wed Dec 2 07:08:02 2015 From: jkjkelly9 at gmail.com (Packie Kelly) Date: Wed, 2 Dec 2015 12:08:02 +0000 Subject: Installation Problem Message-ID: Hi my name is Patrick, I have a problem regarding the installation of the latest version of python, everytime I install the program I keep getting the message modify, repair, uninstall. I've tried different versions but with no luck. Before you ask I have already completely removed the program. Looking forward to your reply From ganesh1pal at gmail.com Wed Dec 2 07:11:21 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 2 Dec 2015 17:41:21 +0530 Subject: how to make the below code look better Message-ID: Hello team, I need suggestion to improve the below code , Iam on Linux and python 2.7 if not os.path.ismount("/tmp"): sys.exit("/tmp not mounted.") else: if create_dataset() and check_permission(): try: run_full_back_up() run_partial_back_up() except Exception, e: logging.error(e) sys.exit("Running backup failed") if not validation_errors(): sys.exit("Validation failed") else: try: compare_results() except Exception, e: logging.error(e) sys.exit("Comparing result failed") Question 1: 1. if create_dataset() and check_permission(): Iam assuming that if statement will be executed only if both the functions are true ? 2. Can I have a if statement within if else ? , some how I feel its messy 3. Any other suggestion ? please From bc at freeuk.com Wed Dec 2 07:20:15 2015 From: bc at freeuk.com (BartC) Date: Wed, 2 Dec 2015 12:20:15 +0000 Subject: how to make the below code look better In-Reply-To: References: Message-ID: On 02/12/2015 12:11, Ganesh Pal wrote: > if not os.path.ismount("/tmp"): > sys.exit("/tmp not mounted.") > else: > if create_dataset() and check_permission(): > try: > run_full_back_up() > run_partial_back_up() > except Exception, e: > logging.error(e) > sys.exit("Running backup failed") > if not validation_errors(): > sys.exit("Validation failed") > else: > try: > compare_results() > except Exception, e: > logging.error(e) > sys.exit("Comparing result failed") > 3. Any other suggestion ? please You could make the indentation more consistent. Example: if not os.path.ismount("/tmp"): sys.exit("/tmp not mounted.") else: if create_dataset() and check_permission(): try: run_full_back_up() run_partial_back_up() except Exception, e: logging.error(e) sys.exit("Running backup failed") if not validation_errors(): sys.exit("Validation failed") else: try: compare_results() except Exception, e: logging.error(e) sys.exit("Comparing result failed") -- Bartc From rosuav at gmail.com Wed Dec 2 07:30:36 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 23:30:36 +1100 Subject: how to make the below code look better In-Reply-To: References: Message-ID: On Wed, Dec 2, 2015 at 11:11 PM, Ganesh Pal wrote: > I need suggestion to improve the below code , Iam on Linux and python 2.7 > > if not os.path.ismount("/tmp"): > sys.exit("/tmp not mounted.") > else: > if create_dataset() and check_permission(): > try: > run_full_back_up() > run_partial_back_up() > except Exception, e: > logging.error(e) > sys.exit("Running backup failed") > if not validation_errors(): > sys.exit("Validation failed") > else: > try: > compare_results() > except Exception, e: > logging.error(e) > sys.exit("Comparing result failed") > > Question 1: > > 1. if create_dataset() and check_permission(): > Iam assuming that if statement will be executed only if both the > functions are true ? If both the functions return true values, yes. You have an indentation error there, but I'm assuming you meant to have the try/except indented further. > 2. Can I have a if statement within if else ? , some how I feel its messy Certainly you can! However, most (maybe all) of your 'if' statements are checking for error conditions, so the easiest solution is to simply exit right away (either with sys.exit or by raising an exception). > 3. Any other suggestion ? please The first suggestion I'd make is to avoid the comma syntax for exception handling. Replace "except Exception, e:" with "except Exception as e:". That's a trivial change of syntax that shouldn't affect your code at all; consider it low-hanging fruit. The second thing to look at is the way you're 'handling' those errors. All you do is log the error and exit. So you can skip the except clauses altogether, and just do this: if not os.path.ismount("/tmp"): sys.exit("/tmp not mounted.") if create_dataset() and check_permission(): run_full_back_up() run_partial_back_up() if not validation_errors(): # CHECK ME sys.exit("Validation failed") compare_results() Check the logic of validation_errors, though. If it returns something True, does that mean there were errors or there weren't? If it means there were errors, then the 'not' seems to me to be wrong; but if it means there weren't, then I would rename it "validation_successful" rather than "validation_errors". Also worth checking: If you can't create the data set or the permission check fails, what should it do? Should it terminate with an error? Currently, it carries on and does the validation, which is probably not right. If it ought to terminate straight away, you can write the whole program in "fail and bail" style: if not create_dataset(): sys.exit("Data set creation failed") if not check_permission(): sys.exit("Permission check failed") Even better: Make those functions raise exceptions on failure, instead of returning False. They can give extra information that way, and all your main routine needs to do is: create_dataset() check_permission() To advise further, we'd need to see what those functions are doing. The main routine you have here is pretty simple, and anything you do is probably going to be fine. ChrisA From rosuav at gmail.com Wed Dec 2 07:31:54 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Dec 2015 23:31:54 +1100 Subject: how to make the below code look better In-Reply-To: References: Message-ID: On Wed, Dec 2, 2015 at 11:20 PM, BartC wrote: > You could make the indentation more consistent. Example: You fixed one indentation error... > if create_dataset() and check_permission(): > try: > run_full_back_up() > run_partial_back_up() > except Exception, e: > logging.error(e) > sys.exit("Running backup failed") ... but introduced another :) > try: > compare_results() > except Exception, e: > logging.error(e) > sys.exit("Comparing result failed") These last three lines need to be unindented one level. Otherwise, Bart's recommendation is a good one. ChrisA From steve at pearwood.info Wed Dec 2 08:11:56 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Dec 2015 00:11:56 +1100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: > If you want your arguments to be taken seriously, then you better should. > If you use an argument when it suits you and ignore it when it doesn't > you are showing you don't really have an argument. You are just showing > your preference and making it sound like an argument. "A foolish consistency is the hobgoblin of little minds." Thank you for your feedback. If you ever decide to post here to make constructive comments or to help others, instead of just flaunting your imagined superiority and whinging and moaning about the rest of us, then I'll start to take your arguments seriously too. -- Steven From rosuav at gmail.com Wed Dec 2 08:12:49 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Dec 2015 00:12:49 +1100 Subject: Installation Problem In-Reply-To: References: Message-ID: On Wed, Dec 2, 2015 at 11:08 PM, Packie Kelly wrote: > Hi my name is Patrick, > > I have a problem regarding the installation of the latest version of > python, everytime I install the program I keep getting the message modify, > repair, uninstall. I've tried different versions but with no luck. Before > you ask I have already completely removed the program. > > Looking forward to your reply My crystal ball says you're using Windows XP. Your options, if that is the case, are: 1) Downgrade to Python 3.4 2) Upgrade to Windows 7/8/10 3) Install a better operating system, like Linux, *BSD, or Mac OS Otherwise, tell us some more about your system - what kind of computer are you running, what OS are you using, etc, etc - and where you got Python from, etc. We'll then be better able to advise. ChrisA From steve at pearwood.info Wed Dec 2 08:17:16 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Dec 2015 00:17:16 +1100 Subject: static variables References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565EAA1D.501@rece.vub.ac.be> <87a8ptcfvz.fsf@elektro.pacujo.net> <8737vlccko.fsf@elektro.pacujo.net> Message-ID: <565eef5f$0$1619$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 10:30 pm, Marko Rauhamaa wrote: > Antoon Pardon : > >> Op 02-12-15 om 11:18 schreef Marko Rauhamaa: >>> I don't know why global accessibility is such a problem. >> >> Some people seem to have a problem with global variables. > > Well, *I* don't go around defining global variables, but there are times > when they are the way to go. For example, if a module function uses a > regular expression, the regular expression should be compiled into a > (module) global variable. > > Module functions and classes are global variables as well: Actually, those examples are more usually global *constants* (or at least the closest thing that Python has to constants). While we can rebind math.sqrt, as in your example, treating it as a variable, we normally would not do so. We would normally treat such module level objects as constants. -- Steven From steve at pearwood.info Wed Dec 2 08:28:08 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Dec 2015 00:28:08 +1100 Subject: how to make the below code look better References: Message-ID: <565ef1eb$0$1604$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Dec 2015 11:11 pm, Ganesh Pal wrote: > Hello team, > > I need suggestion to improve the below code , Iam on Linux and python 2.7 > > if not os.path.ismount("/tmp"): > sys.exit("/tmp not mounted.") This is good enough for quick and dirty scripts, but this is vulnerable to a race condition. It may be that /tmp is mounted *now*, but a millisecond later (before you can use it) another process unmounts it. This is called a "time of check to time of use" bug: https://cwe.mitre.org/data/definitions/367.html https://www.owasp.org/index.php/Time_of_check,_time_of_use_race_condition https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use and can be a serious software vulnerability. If this code is only being used under trusted conditions, then it is probably okay, otherwise you should reconsider your strategy. (Besides, how often do you unmount /tmp?) > else: > if create_dataset() and check_permission(): this with: elif create_dataset() and check_permission(): but again be mindful of the risk of race conditions. > try: > run_full_back_up() > run_partial_back_up() > except Exception, e: > logging.error(e) > sys.exit("Running backup failed") > if not validation_errors(): > sys.exit("Validation failed") I would swap the sense of validation_errors(). Currently, it looks like it returns True if there are *no* errors, and False if there are errors. That seems confusing and easy to get wrong. if validation_errors(): sys.exit("Validation failed") reads better and is easier to understand. Now validation_errors() returns true if there are errors, and false if there are no errors. > else: > try: > compare_results() > except Exception, e: > logging.error(e) > sys.exit("Comparing result failed") > > Question 1: > > 1. if create_dataset() and check_permission(): > Iam assuming that if statement will be executed only if both the > functions are true ? Correct. > 2. Can I have a if statement within if else ? , some how I feel its messy Yes you can, but elif is usually nicer, and saves a level of indentation. -- Steven From breamoreboy at yahoo.co.uk Wed Dec 2 08:30:38 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 2 Dec 2015 13:30:38 +0000 Subject: Installation Problem In-Reply-To: References: Message-ID: On 02/12/2015 13:12, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 11:08 PM, Packie Kelly wrote: >> Hi my name is Patrick, >> >> I have a problem regarding the installation of the latest version of >> python, everytime I install the program I keep getting the message modify, >> repair, uninstall. I've tried different versions but with no luck. Before >> you ask I have already completely removed the program. >> >> Looking forward to your reply > > My crystal ball says you're using Windows XP. Your options, if that is > the case, are: > > 1) Downgrade to Python 3.4 > 2) Upgrade to Windows 7/8/10 > 3) Install a better operating system, like Linux, *BSD, or Mac OS > > Otherwise, tell us some more about your system - what kind of computer > are you running, what OS are you using, etc, etc - and where you got > Python from, etc. We'll then be better able to advise. > > ChrisA > 0) before asking search for "python installation problem" just in case you're not the first person to have this issue. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From lac at openend.se Wed Dec 2 08:35:23 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 02 Dec 2015 14:35:23 +0100 Subject: Installation Problem In-Reply-To: References: Message-ID: <201512021335.tB2DZNTw026100@fido.openend.se> In a message of Wed, 02 Dec 2015 12:08:02 +0000, Packie Kelly writes: >Hi my name is Patrick, > >I have a problem regarding the installation of the latest version of >python, everytime I install the program I keep getting the message modify, >repair, uninstall. I've tried different versions but with no luck. Before >you ask I have already completely removed the program. > >Looking forward to your reply What Operating System? If it is Windows XP, that is your problem. Python 3.5 is not supported on Windows XP. Either stick with 3.4 or upgrade your OS to something more recent. Laura Creighton From antoon.pardon at rece.vub.ac.be Wed Dec 2 08:41:43 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 14:41:43 +0100 Subject: static variables In-Reply-To: <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <565EF517.3060508@rece.vub.ac.be> Op 02-12-15 om 14:11 schreef Steven D'Aprano: > On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: > >> If you want your arguments to be taken seriously, then you better should. >> If you use an argument when it suits you and ignore it when it doesn't >> you are showing you don't really have an argument. You are just showing >> your preference and making it sound like an argument. > "A foolish consistency is the hobgoblin of little minds." So? That doesn't show that we are talking about a foolish consistency here. This pseudo kind of arguing happens a lot on this list. A lot of the times one just throws out some proverb as if it is at all clear that the proverb applies. Somebody points out an inconsistency and out comes the above proverb, without much arguments that this inconsisty has advantages over a more consistent approach. > Thank you for your feedback. If you ever decide to post here to make > constructive comments or to help others, instead of just flaunting your > imagined superiority and whinging and moaning about the rest of us, then > I'll start to take your arguments seriously too. Oh come of your high horse. If people use arguments in a selective way, I can point that out. If you selectively apply an argument so you ignore the counter arguments when it suits you, that is not a constructive comment either and you can expect people to point out when that first argument can be used against you in the same way. Then going on to complain about non constructive comments seems a bit disingenous. -- Antoon. From breamoreboy at yahoo.co.uk Wed Dec 2 08:48:05 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 2 Dec 2015 13:48:05 +0000 Subject: static variables In-Reply-To: <565EF517.3060508@rece.vub.ac.be> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> Message-ID: On 02/12/2015 13:41, Antoon Pardon wrote: > Op 02-12-15 om 14:11 schreef Steven D'Aprano: >> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: >> >>> If you want your arguments to be taken seriously, then you better should. >>> If you use an argument when it suits you and ignore it when it doesn't >>> you are showing you don't really have an argument. You are just showing >>> your preference and making it sound like an argument. >> "A foolish consistency is the hobgoblin of little minds." > > So? That doesn't show that we are talking about a foolish consistency here. > > This pseudo kind of arguing happens a lot on this list. A lot of the times > one just throws out some proverb as if it is at all clear that the proverb > applies. > > Somebody points out an inconsistency and out comes the above proverb, without > much arguments that this inconsisty has advantages over a more consistent > approach. > >> Thank you for your feedback. If you ever decide to post here to make >> constructive comments or to help others, instead of just flaunting your >> imagined superiority and whinging and moaning about the rest of us, then >> I'll start to take your arguments seriously too. > > Oh come of your high horse. If people use arguments in a selective way, > I can point that out. If you selectively apply an argument so you ignore > the counter arguments when it suits you, that is not a constructive comment > either and you can expect people to point out when that first argument can > be used against you in the same way. > > Then going on to complain about non constructive comments seems a bit > disingenous. > Would the pair of you, Antoon and Steven, be kind enough to take your bickering offline, thanks. -- 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 Wed Dec 2 08:49:10 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Dec 2015 00:49:10 +1100 Subject: how to make the below code look better In-Reply-To: <565ef1eb$0$1604$c3e8da3$5496439d@news.astraweb.com> References: <565ef1eb$0$1604$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Dec 3, 2015 at 12:28 AM, Steven D'Aprano wrote: >> if not os.path.ismount("/tmp"): >> sys.exit("/tmp not mounted.") > > This is good enough for quick and dirty scripts, but this is vulnerable to a > race condition. It may be that /tmp is mounted *now*, but a millisecond > later (before you can use it) another process unmounts it. > > This is called a "time of check to time of use" bug: > > https://cwe.mitre.org/data/definitions/367.html > > https://www.owasp.org/index.php/Time_of_check,_time_of_use_race_condition > > https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use > > and can be a serious software vulnerability. > > If this code is only being used under trusted conditions, then it is > probably okay, otherwise you should reconsider your strategy. > > (Besides, how often do you unmount /tmp?) > Possibly it's not worried about *un*mounting of /tmp, but about being run prior to /tmp being mounted for the first time. If that's the case, the check/use difference won't matter - worst case, the program errors out even though the mount was almost completed. ChrisA From lac at openend.se Wed Dec 2 08:59:13 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 02 Dec 2015 14:59:13 +0100 Subject: Installation Problem In-Reply-To: References: Message-ID: <201512021359.tB2DxDh5026529@fido.openend.se> In a message of Wed, 02 Dec 2015 13:30:38 +0000, Mark Lawrence writes: >0) before asking search for "python installation problem" just in case >you're not the first person to have this issue. That is not a good idea, there are so many different hits for that. The first one I get is this: http://superuser.com/questions/613820/error-installing-python-on-windows-7-x64 which is unlikely to be the OP's problem. I'd like it if people would stop mentioning crystal balls and the like around here, which was funny once, but which has gotten extremely stale since. And if people whose first take on others is 'does this give me an opportunity to be sarcastic' took it someplace else. I get very tired of hanging around people who think that sarcastic is clever. Laura From antoon.pardon at rece.vub.ac.be Wed Dec 2 09:07:09 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 15:07:09 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> Message-ID: <565EFB0D.2020809@rece.vub.ac.be> Op 02-12-15 om 14:48 schreef Mark Lawrence: > > Would the pair of you, Antoon and Steven, be kind enough to take your > bickering offline, thanks. > Mark, you are in no position to make such a request of others. -- Antoon. From ian.g.kelly at gmail.com Wed Dec 2 09:15:59 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 08:15:59 -0600 Subject: static variables In-Reply-To: <565EF517.3060508@rece.vub.ac.be> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> Message-ID: On Wed, Dec 2, 2015 at 7:41 AM, Antoon Pardon wrote: > Op 02-12-15 om 14:11 schreef Steven D'Aprano: >> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: >> >>> If you want your arguments to be taken seriously, then you better should. >>> If you use an argument when it suits you and ignore it when it doesn't >>> you are showing you don't really have an argument. You are just showing >>> your preference and making it sound like an argument. >> "A foolish consistency is the hobgoblin of little minds." > > So? That doesn't show that we are talking about a foolish consistency here. It's actually the truest use of the quote that I've yet seen on this list. Emerson was complaining about those who adhere to opinions that they've expressed in the past solely for the sake of appearing consistent in their values, which is basically what you're accusing Steven of not doing. If you haven't previously read Self-Reliance, I would recommend it as a good (and short) read. From breamoreboy at yahoo.co.uk Wed Dec 2 09:31:01 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 2 Dec 2015 14:31:01 +0000 Subject: static variables In-Reply-To: <565EFB0D.2020809@rece.vub.ac.be> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> <565EFB0D.2020809@rece.vub.ac.be> Message-ID: On 02/12/2015 14:07, Antoon Pardon wrote: > Op 02-12-15 om 14:48 schreef Mark Lawrence: >> >> Would the pair of you, Antoon and Steven, be kind enough to take your >> bickering offline, thanks. >> > Mark, you are in no position to make such a request of others. > I am, I'm sat perfectly comfortably 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 breamoreboy at yahoo.co.uk Wed Dec 2 09:42:48 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 2 Dec 2015 14:42:48 +0000 Subject: Installation Problem In-Reply-To: <201512021359.tB2DxDh5026529@fido.openend.se> References: <201512021359.tB2DxDh5026529@fido.openend.se> Message-ID: On 02/12/2015 13:59, Laura Creighton wrote: > In a message of Wed, 02 Dec 2015 13:30:38 +0000, Mark Lawrence writes: >> 0) before asking search for "python installation problem" just in case >> you're not the first person to have this issue. > > That is not a good idea, there are so many different hits for that. > The first one I get is this: > http://superuser.com/questions/613820/error-installing-python-on-windows-7-x64 > > which is unlikely to be the OP's problem. So you are advocating that people keep on asking the same question, even if it has been asked twice a day for the last month? Wouldn't it be better to advise people to restrict their search to maybe the last month or even week, or do a site specific search, or even check the mailing list archives? > > I'd like it if people would stop mentioning crystal balls and the like > around here, which was funny once, but which has gotten extremely stale > since. And if people whose first take on others is 'does this give me > an opportunity to be sarcastic' took it someplace else. I get very > tired of hanging around people who think that sarcastic is clever. It's not funny, but it does show the number of times that the question asked is often less than useless. Personally I'm tired of the fit bib, spoon feed, change nappy brigade, who IMHO are doing far more harm than good. > > Laura > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From invalid at invalid.invalid Wed Dec 2 10:15:21 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 2 Dec 2015 15:15:21 +0000 (UTC) Subject: "Downloading" References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 2015-12-01, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 6:05 AM, Random832 wrote: >> On 2015-12-01, Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> I'm a little bit confused as to what kinds of file transfers >> you think don't have at least two endpoints. > >>From some other computer to the one you're controlling it from. A > download is initiated by the recipient; an upload is initiated by the > sender. Nope. It doesn't depend on who initiated the transfer, up/down is a direction. I upload things to the Host on the Internet, and I download things to the circuit board on my bench. In both cases I initiate the transaction [ Host on The Internet ] | [my computer] | [circuit board I'm working on] -- Grant Edwards grant.b.edwards Yow! I invented skydiving at in 1989! gmail.com From lac at openend.se Wed Dec 2 10:15:42 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 02 Dec 2015 16:15:42 +0100 Subject: Installation Problem In-Reply-To: References: <201512021359.tB2DxDh5026529@fido.openend.se> Message-ID: <201512021515.tB2FFgqT027841@fido.openend.se> In a message of Wed, 02 Dec 2015 14:42:48 +0000, Mark Lawrence writes: >On 02/12/2015 13:59, Laura Creighton wrote: >> In a message of Wed, 02 Dec 2015 13:30:38 +0000, Mark Lawrence writes: >>> 0) before asking search for "python installation problem" just in case >>> you're not the first person to have this issue. >> >> That is not a good idea, there are so many different hits for that. >> The first one I get is this: >> http://superuser.com/questions/613820/error-installing-python-on-windows-7-x64 >> >> which is unlikely to be the OP's problem. > >So you are advocating that people keep on asking the same question, even >if it has been asked twice a day for the last month? Yes. It is old for us, but nobody should be giving 2 hoots about our feelings. Since we can just ignore such things. The problem is always fresh and new for the poster. > Wouldn't it be >better to advise people to restrict their search to maybe the last month >or even week, or do a site specific search, or even check the mailing >list archives? They are already getting the advice to ask the question on python-list. This is the preferred way to get such problems solved. We even have automated mailer responses telling people to ask such questions here. We don't warn them that they are about to meet anti-social and egotistical people who think that they should take every opportunity to be sarcastic that presents itself. You also have a woefully inadequate understanding of ignorance. See Kruger Dunnign effect: https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect People in the bottom quartile of comprehension of anything -- i.e. the most ignorant -- lack the metacognative skills to recognise the solutions to their problems even when they are presented in a clear and logical fashion. Thus the most ignorant can not be expected to just google up an answer, because even if they got one, they wouldn't be able to recognise it. It's bad enough when they miss solutions out there. It's worse when they try to do things that work for one OS on another, or one version of an OS on another, and so on and so forth. Much, much better that these people come and ask quesitons. >It's not funny, but it does show the number of times that the question >asked is often less than useless. Personally I'm tired of the fit bib, >spoon feed, change nappy brigade, who IMHO are doing far more harm than >good. I think you should stay away from python-list, then, until your sense of humour returns and your ability to deal with the abysmally ignorant matures. Because this is where we actually want to get a hold of such people so we can teach them things, and the active and vocal presence of people who resent them for being ignorant makes the job a whole lot harder. Laura >Mark Lawrence From invalid at invalid.invalid Wed Dec 2 10:20:13 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 2 Dec 2015 15:20:13 +0000 (UTC) Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 2015-12-02, Richard Heathfield wrote: > On 02/12/15 08:57, Juha Nieminen wrote: >> In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> It's a matter of perspective. If a hacker breaks into your computer and >> starts a download from somewhere else into your computer, isn't the hacker >> "downloading" things to your computer? > > My understanding of the term has always been that you upload from a > smaller device to a larger, and download from a larger device to a > smaller. Thus, from your laptop you might *up*load data to a Web server > or a mainframe, but you would *down*load data to your phone or tablet. That's sort of the usage I'm used to, but it probably has more to do with network topology than CPU power. Servers on the internet are at the top of the diagram, and embedded devices that can't access the internet directly are at the bottom with my PC somewhere in the middle. -- Grant Edwards grant.b.edwards Yow! Are you still an at ALCOHOLIC? gmail.com From invalid at invalid.invalid Wed Dec 2 10:20:53 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 2 Dec 2015 15:20:53 +0000 (UTC) Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 2015-12-02, Les Cargill wrote: > Juha Nieminen wrote: >> In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> It's a matter of perspective. If a hacker breaks into your computer and >> starts a download from somewhere else into your computer, isn't the hacker >> "downloading" things to your computer? >> >> --- news://freenews.netfront.net/ - complaints: news at netfront.net --- >> > > Down is towards an end node; up is towards the backbone. Servers live > closer to the backbone. Usually. Or rather did when the nomenclature > was forged. Exactly! Thats the usage I've been used to for the past 30 years. -- Grant Edwards grant.b.edwards Yow! I'm pretending that at we're all watching PHIL gmail.com SILVERS instead of RICARDO MONTALBAN! From self at example.org Wed Dec 2 10:23:55 2015 From: self at example.org (me) Date: Wed, 2 Dec 2015 15:23:55 +0000 (UTC) Subject: how to make the below code look better References: Message-ID: On 2015-12-02, Ganesh Pal wrote: > if not os.path.ismount("/tmp"): > sys.exit("/tmp not mounted.") > else: > if create_dataset() and check_permission(): > try: > run_full_back_up() > run_partial_back_up() > except Exception, e: > logging.error(e) > sys.exit("Running backup failed") > if not validation_errors(): > sys.exit("Validation failed") > else: > try: > compare_results() > except Exception, e: > logging.error(e) > sys.exit("Comparing result failed") Apart from what already mentioned (indentation, assumptions on environment): > 1. if create_dataset() and check_permission(): > Iam assuming that if statement will be executed only if both the > functions are true ? Yes, this is the meaning of 'and'. Notice how functions are always true, but the result of the function call might not be. - create_dataset is a function. - create_dataset() is a function call. > 2. Can I have a if statement within if else ? , some how I feel its messy You are searching for `elif`. From self at example.org Wed Dec 2 10:25:14 2015 From: self at example.org (me) Date: Wed, 2 Dec 2015 15:25:14 +0000 (UTC) Subject: regarding download issues from sharepoint site References: Message-ID: On 2015-12-02, Arpit Arya wrote: > please help me out http://catb.org/~esr/faqs/smart-questions.html#beprecise From antoon.pardon at rece.vub.ac.be Wed Dec 2 10:30:21 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 02 Dec 2015 16:30:21 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> Message-ID: <565F0E8D.5080606@rece.vub.ac.be> Op 02-12-15 om 15:15 schreef Ian Kelly: > On Wed, Dec 2, 2015 at 7:41 AM, Antoon Pardon > wrote: >> Op 02-12-15 om 14:11 schreef Steven D'Aprano: >>> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: >>> >>>> If you want your arguments to be taken seriously, then you better should. >>>> If you use an argument when it suits you and ignore it when it doesn't >>>> you are showing you don't really have an argument. You are just showing >>>> your preference and making it sound like an argument. >>> "A foolish consistency is the hobgoblin of little minds." >> So? That doesn't show that we are talking about a foolish consistency here. > It's actually the truest use of the quote that I've yet seen on this > list. Emerson was complaining about those who adhere to opinions that > they've expressed in the past solely for the sake of appearing > consistent in their values, which is basically what you're accusing > Steven of not doing. That is not true. I expect that the next time someone will try to argue for private attributes or some such, Steven will be among those that will support the "consenting adults" line. This view of his, is not in the past, it is for all i know still in the present. That his latest expression was in the past, doesn't make his view something of the past. If there was a reason to think he had changed his mind, you would have been right. But I see no reason for that. There is a difference between changing your mind and thus change your arguments and using an argument selectively. From kst-u at mib.org Wed Dec 2 11:36:24 2015 From: kst-u at mib.org (Keith Thompson) Date: Wed, 02 Dec 2015 08:36:24 -0800 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: Juha Nieminen writes: > In comp.lang.c++ Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > > It's a matter of perspective. If a hacker breaks into your computer and > starts a download from somewhere else into your computer, isn't the hacker > "downloading" things to your computer? My understanding of the word "downloading" has always been STOP FEEDING THE TROLL! -- Keith Thompson (The_Other_Keith) kst-u at mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From marko at pacujo.net Wed Dec 2 11:37:58 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Dec 2015 18:37:58 +0200 Subject: "Downloading" References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <874mg0ztzt.fsf@elektro.pacujo.net> Grant Edwards : > On 2015-12-01, Chris Angelico wrote: >> download is initiated by the recipient; an upload is initiated by the >> sender. > > Nope. It doesn't depend on who initiated the transfer, up/down is a > direction. I upload things to the Host on the Internet, and I download > things to the circuit board on my bench. In both cases I initiate the > transaction Forget the ups and downs and just load the file. Marko From lac at openend.se Wed Dec 2 11:53:29 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 02 Dec 2015 17:53:29 +0100 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <201512021653.tB2GrTAi029320@fido.openend.se> In a message of Wed, 02 Dec 2015 08:36:24 -0800, Keith Thompson writes: >"We must do something. This is something. Therefore, we must do this." > -- Antony Jay and Jonathan Lynn, "Yes Minister" This is one of my favourite quotes of all time. Unfortunately, you have it slightly wrong. The quote is: Something must be done. This is something. Therefore we must do it. cheers! Laura https://www.google.se/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwjZvrXl0L3JAhVmJHIKHTBjCugQtwIIIjAB&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dtrw1PbQt_Yo&usg=AFQjCNHEKrgju4vVOH_hmwnbn0zAWU0aEg&sig2=VwmILBUKi-vz7YCA5k_0ew From rhills at medimorphosis.com.au Wed Dec 2 12:00:09 2015 From: rhills at medimorphosis.com.au (Rob Hills) Date: Thu, 3 Dec 2015 01:00:09 +0800 Subject: Is secretly downloading to your computer ?! In-Reply-To: <201512021653.tB2GrTAi029320@fido.openend.se> References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> <201512021653.tB2GrTAi029320@fido.openend.se> Message-ID: <565F2399.1040906@medimorphosis.com.au> On 03/12/15 00:53, Laura Creighton wrote: > This is one of my favourite quotes of all time. Unfortunately, you > have it slightly wrong. The quote is: > Something must be done. This is something. Therefore we must do it. I wish people would check their email subjects before replying to this thread. I suspect part of the OP's intent is to have his assertion generate lots of traffic, all repeating the assertion via their subject heading... Unless of course you actually agree with his assertion! Cheers, -- Rob Hills Waikiki, Western Australia From quantiacsllc at gmail.com Wed Dec 2 12:22:24 2015 From: quantiacsllc at gmail.com (quantiacsllc at gmail.com) Date: Wed, 2 Dec 2015 09:22:24 -0800 (PST) Subject: Q4 Quant Coding Competition in Python Message-ID: $2.25M for the best three trading algos. You pocket 10% of the profits with no downside risk. The winner of one of our last competitions made $4,000 in the past five weeks with an initial investment of $1M. We provide a free and open-source toolbox in Python. It comes with 25 years of financial data. Join the Q4: https://quantiacs.com/q4 From ian.g.kelly at gmail.com Wed Dec 2 12:32:25 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 11:32:25 -0600 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, Dec 2, 2015 at 10:36 AM, Keith Thompson wrote: > Juha Nieminen writes: >> In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> It's a matter of perspective. If a hacker breaks into your computer and >> starts a download from somewhere else into your computer, isn't the hacker >> "downloading" things to your computer? > > My understanding of the word "downloading" has always been STOP FEEDING > THE TROLL! In what way is discussion of a tangential topic feeding the troll? Said troll is not even participating in the discussion. From jorge.conrado at cptec.inpe.br Wed Dec 2 12:53:08 2015 From: jorge.conrado at cptec.inpe.br (jorge.conrado at cptec.inpe.br) Date: Wed, 02 Dec 2015 15:53:08 -0200 Subject: python message Message-ID: Hi, I'm a new user of Pyhton and I run my code lenetcdf1.py and I plot the figure but I had this message: /usr/lib64/python2.7/site-packages/matplotlib/collections.py:590: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison if self._edgecolors == str('face'): I do not understand this message. Atached it my code. What can I do to solve this message. Thanks in advance. Conrado From albert.visser at gmail.com Wed Dec 2 13:08:32 2015 From: albert.visser at gmail.com (Albert Visser) Date: Wed, 02 Dec 2015 19:08:32 +0100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <4327593e-9b6a-49f0-9b11-addda7906a29@googlegroups.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <4327593e-9b6a-49f0-9b11-addda7906a29@googlegroups.com> Message-ID: On Tue, 01 Dec 2015 22:15:08 +0100, Rick Johnson wrote: > On Tuesday, December 1, 2015 at 10:56:27 AM UTC-6, John Gordon wrote: >> Rick Johnson writes: >> > Your lament does remind me of a pet peeve i have concerning Python, >> and >> > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) >> > WAY TO DO IT!". In fact, in python there is almost always *MANY* ways >> to >> > achieve the same output.=20 >> >> The koan reads: >> >> There should be one-- and preferably only one --obvious way to do >> it. >> >> You left out the rather important word "obvious". > > Indeed you are correct about the wording, but your interpretation is > wrong. Mm, not so much. What you're describing is a statement like "There should be one way and it should be obvious". -- Vriendelijke groeten / Kind regards, Albert Visser Using Opera's mail client: http://www.opera.com/mail/ From lac at openend.se Wed Dec 2 13:52:24 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 02 Dec 2015 19:52:24 +0100 Subject: python message In-Reply-To: References: Message-ID: <201512021852.tB2IqOoN031098@fido.openend.se> In a message of Wed, 02 Dec 2015 15:53:08 -0200, jorge.conrado at cptec.inpe.br wr ites: > > > >Hi, > > >I'm a new user of Pyhton and I run my code lenetcdf1.py and I plot the >figure but I had this message: > > >/usr/lib64/python2.7/site-packages/matplotlib/collections.py:590: >FutureWarning: elementwise comparison failed; returning scalar instead, >but in the future will perform elementwise comparison > if self._edgecolors == str('face'): > >I do not understand this message. Atached it my code. > > >What can I do to solve this message. > >Thanks in advance. > > >Conrado Your code did not get attached, but no matter. Just ignore this one. https://github.com/matplotlib/matplotlib/issues/5209 next release of matplotlib should fix it. Laura From dylan.riley at hotmail.com Wed Dec 2 13:58:18 2015 From: dylan.riley at hotmail.com (Dylan Riley) Date: Wed, 2 Dec 2015 10:58:18 -0800 (PST) Subject: HELP PLEASE printing single characters! Message-ID: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> hi all, I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. my code is: #Create a program that prints a list of words in random order. #The program should print all the words and not repeat any. import random LIST = ["blue ", "red ", "yellow ", "green ", "orange "] order = [] print("This game will print a random order of colours") print("The list is", LIST) input("press enter to start") while LIST != []: choice = random.choice(LIST) order += choice while choice in LIST: LIST.remove(choice) print(order) input("press enter to exit") thanks in advance guys From ian.g.kelly at gmail.com Wed Dec 2 14:08:21 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 13:08:21 -0600 Subject: HELP PLEASE printing single characters! In-Reply-To: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> References: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> Message-ID: On Wed, Dec 2, 2015 at 12:58 PM, Dylan Riley wrote: > hi all, > I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: > ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. Remember that strings are iterable, and that iterating over strings results in individual characters. That should give you a clue as to what's going on. > my code is: > #Create a program that prints a list of words in random order. > #The program should print all the words and not repeat any. > > import random > > LIST = ["blue ", "red ", "yellow ", "green ", "orange "] > order = [] > > print("This game will print a random order of colours") > print("The list is", LIST) > input("press enter to start") > > > > while LIST != []: > choice = random.choice(LIST) > order += choice Addition on a list does concatenation, not appending. So this takes each element from choice and adds them individually to order. From dylan.riley at hotmail.com Wed Dec 2 14:44:38 2015 From: dylan.riley at hotmail.com (Dylan Riley) Date: Wed, 2 Dec 2015 11:44:38 -0800 (PST) Subject: HELP PLEASE printing single characters! In-Reply-To: References: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> Message-ID: <39698cab-6f54-4a27-8626-9625dbaf6917@googlegroups.com> On Wednesday, December 2, 2015 at 7:09:23 PM UTC, Ian wrote: > On Wed, Dec 2, 2015 at 12:58 PM, Dylan Riley wrote: > > hi all, > > I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: > > ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. > > Remember that strings are iterable, and that iterating over strings > results in individual characters. That should give you a clue as to > what's going on. > > > my code is: > > #Create a program that prints a list of words in random order. > > #The program should print all the words and not repeat any. > > > > import random > > > > LIST = ["blue ", "red ", "yellow ", "green ", "orange "] > > order = [] > > > > print("This game will print a random order of colours") > > print("The list is", LIST) > > input("press enter to start") > > > > > > > > while LIST != []: > > choice = random.choice(LIST) > > order += choice > > Addition on a list does concatenation, not appending. So this takes > each element from choice and adds them individually to order. hi ian what would be the correct code to use in this situation then because as far as i am aware the elements of my list should be printed as whole elements and not just characters of the elements. From emile at fenx.com Wed Dec 2 15:10:33 2015 From: emile at fenx.com (Emile van Sebille) Date: Wed, 2 Dec 2015 12:10:33 -0800 Subject: "Downloading" In-Reply-To: <874mg0ztzt.fsf@elektro.pacujo.net> References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> <874mg0ztzt.fsf@elektro.pacujo.net> Message-ID: On 12/2/2015 8:37 AM, Marko Rauhamaa wrote: > Grant Edwards : > >> On 2015-12-01, Chris Angelico wrote: >>> download is initiated by the recipient; an upload is initiated by the >>> sender. >> >> Nope. It doesn't depend on who initiated the transfer, up/down is a >> direction. I upload things to the Host on the Internet, and I download >> things to the circuit board on my bench. In both cases I initiate the >> transaction > > Forget the ups and downs and just load the file. Nowadays I suspect push and pull are better terms. Emile From ian.g.kelly at gmail.com Wed Dec 2 15:15:35 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 14:15:35 -0600 Subject: HELP PLEASE printing single characters! In-Reply-To: <39698cab-6f54-4a27-8626-9625dbaf6917@googlegroups.com> References: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> <39698cab-6f54-4a27-8626-9625dbaf6917@googlegroups.com> Message-ID: On Wed, Dec 2, 2015 at 1:44 PM, Dylan Riley wrote: > hi ian what would be the correct code to use in this situation then because as far as i am aware the elements of my list should be printed as whole elements and not just characters of the elements. order.append(choice) From ian.g.kelly at gmail.com Wed Dec 2 15:30:29 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 14:30:29 -0600 Subject: static variables In-Reply-To: <565F0E8D.5080606@rece.vub.ac.be> References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> <565F0E8D.5080606@rece.vub.ac.be> Message-ID: On Wed, Dec 2, 2015 at 9:30 AM, Antoon Pardon wrote: > Op 02-12-15 om 15:15 schreef Ian Kelly: >> On Wed, Dec 2, 2015 at 7:41 AM, Antoon Pardon >> wrote: >>> Op 02-12-15 om 14:11 schreef Steven D'Aprano: >>>> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote: >>>> >>>>> If you want your arguments to be taken seriously, then you better should. >>>>> If you use an argument when it suits you and ignore it when it doesn't >>>>> you are showing you don't really have an argument. You are just showing >>>>> your preference and making it sound like an argument. >>>> "A foolish consistency is the hobgoblin of little minds." >>> So? That doesn't show that we are talking about a foolish consistency here. >> It's actually the truest use of the quote that I've yet seen on this >> list. Emerson was complaining about those who adhere to opinions that >> they've expressed in the past solely for the sake of appearing >> consistent in their values, which is basically what you're accusing >> Steven of not doing. > > That is not true. I expect that the next time someone will try to > argue for private attributes or some such, Steven will be among > those that will support the "consenting adults" line. This view > of his, is not in the past, it is for all i know still in the > present. That his latest expression was in the past, doesn't make > his view something of the past. > > If there was a reason to think he had changed his mind, you would > have been right. But I see no reason for that. > > There is a difference between changing your mind and thus change > your arguments and using an argument selectively. A person can hold one opinion in some contexts and an opposing opinion in others. "Speak what you think now in hard words, and to-morrow speak what to-morrow thinks in hard words again, though it contradict every thing you said to-day." "There will be an agreement in whatever variety of actions, so they be each honest and natural in their hour. For of one will, the actions will be harmonious, however unlike they seem. These varieties are lost sight of at a little distance, at a little height of thought. One tendency unites them all. The voyage of the best ship is a zigzag line of a hundred tacks. See the line from a sufficient distance, and it straightens itself to the average tendency. Your genuine action will explain itself, and will explain your other genuine actions. Your conformity explains nothing. Act singly, and what you have already done singly will justify you now." From rxjwg98 at gmail.com Wed Dec 2 15:37:02 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 2 Dec 2015 12:37:02 -0800 (PST) Subject: Question about split method Message-ID: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Hi, I learn split method online. When I try to run the line with ss1 beginning, I don't understand why its output of ss1 and ss2. I have check the help about split. It looks like that it is a numpy method. What is the split method parameter (within " ") for? Thanks, ............... ss0="1, 2, 4, 8, 16".split(", ") ss0 Out[2]: ['1', '2', '4', '8', '16'] ss1="1, 2, 4, 8, 16".split(" , ") ss1 Out[4]: ['1, 2, 4, 8, 16'] ss2="1, 2, 4, 8, 16".split(", ") ss2 Out[9]: ['1, 2, 4, 8, 16'] help(split) Help on function split in module numpy.lib.shape_base: From ian.g.kelly at gmail.com Wed Dec 2 15:44:30 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 14:44:30 -0600 Subject: Question about split method In-Reply-To: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: > Hi, > > I learn split method online. When I try to run the line with ss1 beginning, > I don't understand why its output of ss1 and ss2. I have check the help > about split. It looks like that it is a numpy method. > What is the split method parameter (within " ") for? > > > Thanks, > > > > ............... > ss0="1, 2, 4, 8, 16".split(", ") > > ss0 > Out[2]: ['1', '2', '4', '8', '16'] > > ss1="1, 2, 4, 8, 16".split(" , ") > > ss1 > Out[4]: ['1, 2, 4, 8, 16'] > > ss2="1, 2, 4, 8, 16".split(", ") > > ss2 > Out[9]: ['1, 2, 4, 8, 16'] > > help(split) > Help on function split in module numpy.lib.shape_base: That's just some random function that you've imported into globals by doing "from numpy import *" or some such. What you're calling in these examples is a string method, not a global function. Try help(str.split) From rxjwg98 at gmail.com Wed Dec 2 16:00:21 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 2 Dec 2015 13:00:21 -0800 (PST) Subject: Question about split method In-Reply-To: References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: On Wednesday, December 2, 2015 at 3:45:34 PM UTC-5, Ian wrote: > On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: > > Hi, > > > > I learn split method online. When I try to run the line with ss1 beginning, > > I don't understand why its output of ss1 and ss2. I have check the help > > about split. It looks like that it is a numpy method. > > What is the split method parameter (within " ") for? > > > > > > Thanks, > > > > > > > > ............... > > ss0="1, 2, 4, 8, 16".split(", ") > > > > ss0 > > Out[2]: ['1', '2', '4', '8', '16'] > > > > ss1="1, 2, 4, 8, 16".split(" , ") > > > > ss1 > > Out[4]: ['1, 2, 4, 8, 16'] > > > > ss2="1, 2, 4, 8, 16".split(", ") > > > > ss2 > > Out[9]: ['1, 2, 4, 8, 16'] > > > > help(split) > > Help on function split in module numpy.lib.shape_base: > > That's just some random function that you've imported into globals by > doing "from numpy import *" or some such. What you're calling in these > examples is a string method, not a global function. > > Try help(str.split) Thanks. I didn't know numpy has been automatically imported, not by me. And your demo line code is helpful. From denismfmcmahon at gmail.com Wed Dec 2 17:51:13 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 2 Dec 2015 22:51:13 -0000 (UTC) Subject: stuff and nonsense References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, 02 Dec 2015 11:32:25 -0600, Ian Kelly wrote: > In what way is discussion of a tangential topic feeding the troll? Said > troll is not even participating in the discussion. Reposting / responding / following up with the original subject boosts the visibility of the subject to internet search engines because of the way newsgroups get gated to websites. -- Denis McMahon, denismfmcmahon at gmail.com From blackwingcat2000 at gmail.com Wed Dec 2 18:09:43 2015 From: blackwingcat2000 at gmail.com (blackwingcat2000 at gmail.com) Date: Wed, 2 Dec 2015 15:09:43 -0800 (PST) Subject: Python 3.5.0: python.exe is not a valid Windows 32 application In-Reply-To: References: Message-ID: <28787b4f-8ebb-42f6-82e3-8ea64f2ed041@googlegroups.com> Hi. https://mail.python.org/pipermail/python-dev/2015-July/140823.html Python 3.5 was dropped the support Windows XP and 2003. It's just an aside, but Python 3.5.1 works on my customized Windows 2000 :P http://blog.livedoor.jp/blackwingcat/archives/1917281.html From jcasale at activenetwerx.com Wed Dec 2 18:32:31 2015 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Wed, 2 Dec 2015 23:32:31 +0000 Subject: Subclassing tuple and introspection Message-ID: <177ebe2b7c6b4011b74e3f2364223df8@activenetwerx.com> I need to return a collection of various types, since python doesn't have the terse facility of extension methods like C#, subclassing tuple and adding a method seems like a terse way to accommodate this. However, if the method returns one element of the collection, how can one enable introspection for users of IDE's that the resulting reference is of type A, and therefor has A's fields? For example: col = (Class(..), Class(...)) item = col[0] Introspection will now enumerate item as an instance of Class, providing its fields. The subclass of tuple breaks this. Is there a better way to do this? Thanks, jlc From ian.g.kelly at gmail.com Wed Dec 2 18:34:37 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 16:34:37 -0700 Subject: Python 3.5.0: python.exe is not a valid Windows 32 application In-Reply-To: <28787b4f-8ebb-42f6-82e3-8ea64f2ed041@googlegroups.com> References: <28787b4f-8ebb-42f6-82e3-8ea64f2ed041@googlegroups.com> Message-ID: On Wed, Dec 2, 2015 at 4:09 PM, wrote: > Hi. > > https://mail.python.org/pipermail/python-dev/2015-July/140823.html > Python 3.5 was dropped the support Windows XP and 2003. > > > > It's just an aside, but Python 3.5.1 works on my customized Windows 2000 :P > http://blog.livedoor.jp/blackwingcat/archives/1917281.html You may be able to get it to run, but as it is unsupported there may be features that are broken but not immediately obviously so and will not be fixed if they are. From ian.g.kelly at gmail.com Wed Dec 2 18:46:57 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Dec 2015 16:46:57 -0700 Subject: Subclassing tuple and introspection In-Reply-To: <177ebe2b7c6b4011b74e3f2364223df8@activenetwerx.com> References: <177ebe2b7c6b4011b74e3f2364223df8@activenetwerx.com> Message-ID: On Wed, Dec 2, 2015 at 4:32 PM, Joseph L. Casale wrote: > I need to return a collection of various types, since python doesn't > have the terse facility of extension methods like C#, subclassing tuple > and adding a method seems like a terse way to accommodate this. If you're not already familiar with collections.namedtuple, have a look at it, as it sounds like just naming the fields may be all that you need. You can also subclass it further to add methods if desired. > However, if the method returns one element of the collection, how can > one enable introspection for users of IDE's that the resulting reference > is of type A, and therefor has A's fields? > > For example: > col = (Class(..), Class(...)) > item = col[0] > > Introspection will now enumerate item as an instance of Class, providing > its fields. The subclass of tuple breaks this. > > Is there a better way to do this? I think that's going to depend heavily on the specific IDE being used, but for general usage you might consider using PEP 484 type annotations; I know that at least PyCharm supports their use for type hinting. From Seymore4Head at Hotmail.invalid Wed Dec 2 18:50:34 2015 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 02 Dec 2015 18:50:34 -0500 Subject: Does Python 2.7 do Open Office Message-ID: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> I have a text file I would like to search through but I have tried it before. I don't remember why they are not compatible together, but I wanted to ask to make sure. I know I can convert the file to plain text but it would be nice not to have to do that. From jcasale at activenetwerx.com Wed Dec 2 18:55:09 2015 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Wed, 2 Dec 2015 23:55:09 +0000 Subject: Subclassing tuple and introspection In-Reply-To: References: <177ebe2b7c6b4011b74e3f2364223df8@activenetwerx.com>, Message-ID: <0aef49d2dd474a23bc3bf92c54ae926a@activenetwerx.com> > If you're not already familiar with collections.namedtuple, have a > look at it, as it sounds like just naming the fields may be all that > you need. You can also subclass it further to add methods if desired. Yeah, all the types in these collections are named tuples... The collection itself isn't applicable, think of a simple list/tuple. > I think that's going to depend heavily on the specific IDE being used, > but for general usage you might consider using PEP 484 type > annotations; I know that at least PyCharm supports their use for type > hinting. The guys here use PyCharm, where it becomes less than describable is I have to make a distinct instance of the subclass for each use by each namedtuple instance and generate doc strings that return those types for the helper methods. This is auto XSLT auto generated code, so I am not worried about the overhead maintaining it, I just didn't want to have to do that if there was a way to prime the type hinting by "properly" subclassing tuple for example. Thanks for the feedback. jlc From jstrickler at gmail.com Wed Dec 2 19:08:24 2015 From: jstrickler at gmail.com (John Strick) Date: Wed, 2 Dec 2015 16:08:24 -0800 (PST) Subject: HELP PLEASE printing single characters! In-Reply-To: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> References: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> Message-ID: On Wednesday, December 2, 2015 at 12:58:30 PM UTC-6, Dylan Riley wrote: > hi all, > I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: > ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. > > my code is: > #Create a program that prints a list of words in random order. > #The program should print all the words and not repeat any. > > import random > > LIST = ["blue ", "red ", "yellow ", "green ", "orange "] > order = [] > > print("This game will print a random order of colours") > print("The list is", LIST) > input("press enter to start") > > > > while LIST != []: > choice = random.choice(LIST) > order += choice > while choice in LIST: > LIST.remove(choice) > print(order) > > > > input("press enter to exit") > > thanks in advance guys You could just shuffle the list first, then loop through it. This will guarantee that each color is only used once. import random LIST = ["blue ", "red ", "yellow ", "green ", "orange "] random.shuffle(LIST) for color in LIST: print(color) # or add to order or whatever you need to From lac at openend.se Wed Dec 2 19:46:44 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 01:46:44 +0100 Subject: stuff and nonsense In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <201512030046.tB30kiis003646@fido.openend.se> In a message of Wed, 02 Dec 2015 22:51:13 +0000, Denis McMahon writes: >On Wed, 02 Dec 2015 11:32:25 -0600, Ian Kelly wrote: > >> In what way is discussion of a tangential topic feeding the troll? Said >> troll is not even participating in the discussion. > >Reposting / responding / following up with the original subject boosts >the visibility of the subject to internet search engines because of the >way newsgroups get gated to websites. > >-- >Denis McMahon, denismfmcmahon at gmail.com That is not what I was told. I was told that these days it is all done by References: lines. Thus changing the Subject no longer has this effect. Wrong? Laura From python at mrabarnett.plus.com Wed Dec 2 19:47:42 2015 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 3 Dec 2015 00:47:42 +0000 Subject: Does Python 2.7 do Open Office In-Reply-To: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> References: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> Message-ID: <565F912E.7080207@mrabarnett.plus.com> On 2015-12-02 23:50, Seymore4Head wrote: > I have a text file I would like to search through but I have tried it > before. I don't remember why they are not compatible together, but I > wanted to ask to make sure. > > I know I can convert the file to plain text but it would be nice not > to have to do that. > A quick search found this: https://wiki.openoffice.org/wiki/Python From lac at openend.se Wed Dec 2 19:54:16 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 01:54:16 +0100 Subject: Does Python 2.7 do Open Office In-Reply-To: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> References: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> Message-ID: <201512030054.tB30sGKW003923@fido.openend.se> In a message of Wed, 02 Dec 2015 18:50:34 -0500, Seymore4Head writes: >I have a text file I would like to search through but I have tried it >before. I don't remember why they are not compatible together, but I >wanted to ask to make sure. > >I know I can convert the file to plain text but it would be nice not >to have to do that. > >-- >https://mail.python.org/mailman/listinfo/python-list You are looking for PyUNO.Unfortuntately it is not well documented, but I have heard good things about this as documentation. https://documenthacker.wordpress.com/2013/03/05/first-draft-released/ Laura From c.buhtz at posteo.jp Wed Dec 2 20:15:38 2015 From: c.buhtz at posteo.jp (c.buhtz at posteo.jp) Date: Thu, 3 Dec 2015 02:15:38 +0100 Subject: filter a list of strings Message-ID: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> I would like to know how this could be done more elegant/pythonic. I have a big list (over 10.000 items) with strings (each 100 to 300 chars long) and want to filter them. list = ..... for item in list[:]: if 'Banana' in item: list.remove(item) if 'Car' in item: list.remove(item) There are a lot of more conditions of course. This is just example code. It doesn't look nice to me. To much redundance. btw: Is it correct to iterate over a copy (list[:]) of that string list and not the original one? -- GnuPGP-Key ID 0751A8EC From denismfmcmahon at gmail.com Wed Dec 2 20:28:36 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 3 Dec 2015 01:28:36 -0000 (UTC) Subject: stuff and nonsense References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Thu, 03 Dec 2015 01:46:44 +0100, Laura Creighton wrote: > In a message of Wed, 02 Dec 2015 22:51:13 +0000, Denis McMahon writes: >>On Wed, 02 Dec 2015 11:32:25 -0600, Ian Kelly wrote: >> >>> In what way is discussion of a tangential topic feeding the troll? >>> Said troll is not even participating in the discussion. >> >>Reposting / responding / following up with the original subject boosts >>the visibility of the subject to internet search engines because of the >>way newsgroups get gated to websites. > That is not what I was told. I was told that these days it is all done > by References: lines. Thus changing the Subject no longer has this > effect. Wrong? Hmm, not sure on that bone, I heard that more instances of a phrase being found (eg in forums where a web page includes the subject in each message) helped increase the visibility of the phrase in some way, but I don't profess to understand how search engines score stuff, and I'm fairly sure few people do to be honest. And what I heard might no longer be true if it ever was to be honest. -- Denis McMahon, denismfmcmahon at gmail.com From hayesstw at telkomsa.net Wed Dec 2 23:21:45 2015 From: hayesstw at telkomsa.net (Steve Hayes) Date: Thu, 03 Dec 2015 06:21:45 +0200 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, 2 Dec 2015 15:20:13 +0000 (UTC), Grant Edwards wrote: >On 2015-12-02, Richard Heathfield wrote: >> On 02/12/15 08:57, Juha Nieminen wrote: >>> In comp.lang.c++ Steve Hayes wrote: >>>> You download things FROM a computer, you upload them TO a computer. >>> >>> It's a matter of perspective. If a hacker breaks into your computer and >>> starts a download from somewhere else into your computer, isn't the hacker >>> "downloading" things to your computer? >> >> My understanding of the term has always been that you upload from a >> smaller device to a larger, and download from a larger device to a >> smaller. Thus, from your laptop you might *up*load data to a Web server >> or a mainframe, but you would *down*load data to your phone or tablet. > >That's sort of the usage I'm used to, but it probably has more to do >with network topology than CPU power. Servers on the internet are at >the top of the diagram, and embedded devices that can't access the >internet directly are at the bottom with my PC somewhere in the >middle. In my usage it all has to do with sending and receiving, like immigration and emigration. I UPload photos from my cell phone to Facebook. I DOWNload photos from my cell phone to my desktop computer. -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From hayesstw at telkomsa.net Thu Dec 3 00:43:24 2015 From: hayesstw at telkomsa.net (Steve Hayes) Date: Thu, 03 Dec 2015 07:43:24 +0200 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: <3glv5bp6visab6qjv140b7qp8puni3r762@4ax.com> On Thu, 03 Dec 2015 06:21:45 +0200, Steve Hayes wrote: >On Wed, 2 Dec 2015 15:20:13 +0000 (UTC), Grant Edwards > wrote: > >>On 2015-12-02, Richard Heathfield wrote: >>> On 02/12/15 08:57, Juha Nieminen wrote: >>>> In comp.lang.c++ Steve Hayes wrote: >>>>> You download things FROM a computer, you upload them TO a computer. >>>> >>>> It's a matter of perspective. If a hacker breaks into your computer and >>>> starts a download from somewhere else into your computer, isn't the hacker >>>> "downloading" things to your computer? >>> >>> My understanding of the term has always been that you upload from a >>> smaller device to a larger, and download from a larger device to a >>> smaller. Thus, from your laptop you might *up*load data to a Web server >>> or a mainframe, but you would *down*load data to your phone or tablet. >> >>That's sort of the usage I'm used to, but it probably has more to do >>with network topology than CPU power. Servers on the internet are at >>the top of the diagram, and embedded devices that can't access the >>internet directly are at the bottom with my PC somewhere in the >>middle. > >In my usage it all has to do with sending and receiving, like >immigration and emigration. > >I UPload photos from my cell phone to Facebook. > >I DOWNload photos from my cell phone to my desktop computer. To which I will add that uploading is sending, and downloading is fetching. So saying that Microsoft downloaded something to my computer is like saying that someone fetched me a ltter when they actually sent it. -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From ganesh1pal at gmail.com Thu Dec 3 01:20:18 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Thu, 3 Dec 2015 11:50:18 +0530 Subject: how to make the below code look better In-Reply-To: References: Message-ID: On Wed, Dec 2, 2015 at 6:00 PM, Chris Angelico wrote: > If both the functions return true values, yes. You have an indentation > error there, but I'm assuming you meant to have the try/except > indented further. > Correct I had meant to have try/except indented further. >> 2. Can I have a if statement within if else ? , some how I feel its messy > > Certainly you can! However, most (maybe all) of your 'if' statements > are checking for error conditions, so the easiest solution is to > simply exit right away (either with sys.exit or by raising an > exception). Yes agreed , have included the suggestion >> 3. Any other suggestion ? please > > The first suggestion I'd make is to avoid the comma syntax for > exception handling. Replace "except Exception, e:" with "except > Exception as e:". That's a trivial change of syntax that shouldn't > affect your code at all; consider it low-hanging fruit. > ,Are we avoiding comma syntax because it's a bad convention or will it have any side effects? In fact I have used this comma syntax in most of my code . I will clean the code latter as it seems working fine > The second thing to look at is the way you're 'handling' those errors. > All you do is log the error and exit. So you can skip the except > clauses altogether, and just do this: > > if not os.path.ismount("/tmp"): > sys.exit("/tmp not mounted.") > if create_dataset() and check_permission(): > run_full_back_up() > run_partial_back_up() > if not validation_errors(): # CHECK ME > sys.exit("Validation failed") > compare_results() > > Agreed. > Check the logic of validation_errors, though. If it returns something > True, does that mean there were errors or there weren't? If it means > there were errors, then the 'not' seems to me to be wrong; but if it > means there weren't, then I would rename it "validation_successful" > rather than "validation_errors". > > Also worth checking: If you can't create the data set or the > permission check fails, what should it do? Should it terminate with an > error? Currently, it carries on and does the validation, which is > probably not right. If it ought to terminate straight away, you can > write the whole program in "fail and bail" style: > > if not create_dataset(): > sys.exit("Data set creation failed") > if not check_permission(): > sys.exit("Permission check failed") > Thanks for other suggestions also From rosuav at gmail.com Thu Dec 3 01:23:50 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Dec 2015 17:23:50 +1100 Subject: how to make the below code look better In-Reply-To: References: Message-ID: On Thu, Dec 3, 2015 at 5:20 PM, Ganesh Pal wrote: >> The first suggestion I'd make is to avoid the comma syntax for >> exception handling. Replace "except Exception, e:" with "except >> Exception as e:". That's a trivial change of syntax that shouldn't >> affect your code at all; consider it low-hanging fruit. >> > ,Are we avoiding comma syntax because it's a bad convention or will > it have any side effects? In fact I have used this comma syntax in > most of my code . I will clean the code latter as it seems working > fine > The comma syntax isn't supported in Python 3, so it'll be a barrier to migration. It's also a bit less clear if you catch multiple exception types in a single handler, which also uses a comma (to make a tuple). Also, the 'as' syntax matches up with similar syntax for 'with' and 'import' statements. ChrisA From mail at nospam.com Thu Dec 3 01:24:52 2015 From: mail at nospam.com (Chris in Makati) Date: Thu, 03 Dec 2015 14:24:52 +0800 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Wed, 2 Dec 2015 08:57:44 +0000 (UTC), Juha Nieminen wrote: >In comp.lang.c++ Steve Hayes wrote: >> You download things FROM a computer, you upload them TO a computer. > >It's a matter of perspective. If a hacker breaks into your computer and >starts a download from somewhere else into your computer, isn't the hacker >"downloading" things to your computer? Does it matter? As far as the law is concerned, it is possession of child porn that's illegal. How it got there is irrelevant. From harvesting at is.invalid Thu Dec 3 01:32:49 2015 From: harvesting at is.invalid (Jussi Piitulainen) Date: Thu, 03 Dec 2015 08:32:49 +0200 Subject: filter a list of strings References: Message-ID: writes: > I would like to know how this could be done more elegant/pythonic. > > I have a big list (over 10.000 items) with strings (each 100 to 300 > chars long) and want to filter them. > > list = ..... > > for item in list[:]: > if 'Banana' in item: > list.remove(item) > if 'Car' in item: > list.remove(item) > > There are a lot of more conditions of course. This is just example > code. It doesn't look nice to me. To much redundance. Yes. The initial copy is redundant and the repeated .remove calls are not only expensive (quadratic time loop that could have been linear), they are also incorrect if there are duplicates in the list. You want to copy and filter in one go: list = ... list = [ item for item in list if ( 'Banana' not in item and 'Car' not in item ) ] It's better to use another name, since "list" is the name of a built-in function. It may be a good idea to define a complex condition as a separate function: def isbad(item): return ( 'Banana' in item or 'Car' in item ) def isgood(item) return not isbad(item) items = ... items = [ item for item in items if isgood(item) ] Then there's also filter, which is easy to use now that the condition is already a named function: items = list(filter(isgood, items)) > btw: Is it correct to iterate over a copy (list[:]) of that string > list and not the original one? I think it's a good idea to iterate over a copy if you are modifying the original during the iteration, but the above suggestions are better for other reasons. From ganesh1pal at gmail.com Thu Dec 3 01:50:39 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Thu, 3 Dec 2015 12:20:39 +0530 Subject: storing test logs under /var/log/ Message-ID: Hi Team , I would need few tips from your past experiences on how to store the test logs My requirement is to capture log under /var/log/ directory every time the test is run . The test will create one small log files which are around 1KB in size . Here is how I plan to approach this , create directory based on current timesamp and store the logs in it . Sample code : time_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "/" LOG_DIR = "" + time_now try: retcode = os.makedirs(LOG_DIR) if retcode: raise Exception( "Faild to create log directory. mkdir %s failed !!!" % LOG_DIR) except Exception, e: sys.exit("Failed to create log directory...Exiting !!!") 1. Do I need to add the cleanup code to remove the log directory say /var/log/test_log/2015-11-25_04-07-48/ , because we might have many more directories like this when test are run multiple times , Iam avoiding because the test will be run 2/3 times max and file sizes are also very small 2. Any better suggestion for my use case. Regards, Ganesh From rxjwg98 at gmail.com Thu Dec 3 01:55:37 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 2 Dec 2015 22:55:37 -0800 (PST) Subject: 'string.join' is wrong in my Python console Message-ID: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --------------- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") ----------------------- My Python console is 2.7. It should be no problem because I see the tutorial is 2.7 too. The console has these display: string.join(['1', '2', '4', '8', '16'], ", ") --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") NameError: name 'string' is not defined >From the context, I don't see string should be replaced by something else. Could you tell me why I have such an error? Thanks, From dieter at handshake.de Thu Dec 3 02:32:37 2015 From: dieter at handshake.de (dieter) Date: Thu, 03 Dec 2015 08:32:37 +0100 Subject: regarding download issues from sharepoint site References: Message-ID: <87two09ecq.fsf@handshake.de> Arpit Arya writes: > i am facing problem downloading files from sharepoint site and to display > it on my web portal. Your sentence above mentions to processes "downloading" and "displaying". Which of the two gives you problems? For the one with the problems, you must describe it in detail: how the problem manisfests itself; which components (if possible, which versions thereof) are involved; what you tried in detail; ... >i have used requests_ntlm module which gives > successful authorisation but i am stuck in next step i.e. to download data > from sharepoint site and dispaly on portal. please help me out Again the "and". Where is the problem: in the "downloading" or in the "displaying" (likely the "downloading"). How does it fail (for the "downloading": which response code do you get for the downloading)? How did you try it (for downloading: with a browser or from the portal backend)? From dieter at handshake.de Thu Dec 3 02:39:59 2015 From: dieter at handshake.de (dieter) Date: Thu, 03 Dec 2015 08:39:59 +0100 Subject: 'string.join' is wrong in my Python console References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: <87poyo9e0g.fsf@handshake.de> Robert writes: > I read the tutorial on "Why is join() a string method instead of a list > or tuple method?" > at link: > https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls > > I have a problem on running the last line: > --------------- > If none of these arguments persuade you, then for the moment you can > continue to use the join() function from the string module, which allows > you to write > > string.join(['1', '2', '4', '8', '16'], ", ") > ----------------------- > > My Python console is 2.7. It should be no problem because I see the tutorial > is 2.7 too. > > The console has these display: > > string.join(['1', '2', '4', '8', '16'], ", ") > --------------------------------------------------------------------------- > NameError Traceback (most recent call last) > in () > ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") > > NameError: name 'string' is not defined You need to import the "string" module before you can use it. From sijanonly at gmail.com Thu Dec 3 02:59:42 2015 From: sijanonly at gmail.com (Sijan Bhandari) Date: Wed, 2 Dec 2015 23:59:42 -0800 (PST) Subject: 'string.join' is wrong in my Python console In-Reply-To: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: <5be09585-395d-499c-9cd6-a1e5f5459aa6@googlegroups.com> On Thursday, December 3, 2015 at 12:40:52 PM UTC+5:45, Robert wrote: > Hi, > > I read the tutorial on "Why is join() a string method instead of a list > or tuple method?" > at link: > https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls > > I have a problem on running the last line: > --------------- > If none of these arguments persuade you, then for the moment you can > continue to use the join() function from the string module, which allows > you to write > > string.join(['1', '2', '4', '8', '16'], ", ") > ----------------------- > > My Python console is 2.7. It should be no problem because I see the tutorial > is 2.7 too. > > The console has these display: > > string.join(['1', '2', '4', '8', '16'], ", ") > --------------------------------------------------------------------------- > NameError Traceback (most recent call last) > in () > ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") > > NameError: name 'string' is not defined > > > From the context, I don't see string should be replaced by something else. > > Could you tell me why I have such an error? > > > Thanks, simply, import string at the beginning of your script. From cs at zip.com.au Thu Dec 3 03:17:23 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 3 Dec 2015 19:17:23 +1100 Subject: storing test logs under /var/log/ In-Reply-To: References: Message-ID: <20151203081723.GA48121@cskk.homeip.net> On 03Dec2015 12:20, Ganesh Pal wrote: >I would need few tips from your past experiences on how to store >the test logs >My requirement is to capture log under /var/log/ directory every time >the test is run . Normally /var/log itself is only writable by root. Unless you are running your tests as root (_not_ recommended unless you're testing something quite privileged) the convention is either to create a log directory in the home directory of the user running the tests (though not if running as root), *or* to create a subdirectory in /var/log named after your purpose, eg /var/log/test-results. >The test will create one small log files which are >around 1KB in size . Fine, unless you're running some poor filesystem (unlikely these days). >Here is how I plan to approach this , create directory based on >current timesamp and store the logs in it . Sounds reasonable to me, but definitiely inside a top level directory _below_ /var/log. >Sample code : > >time_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "/" >LOG_DIR = "" + time_now This is a little weird in a few ways. Firstly, UPPER_CASE names are normally reserved for what would be called "constants" in languages like C: top level global names for program wide defaults. You don't use them for working, changable, names like the computed name of your log directory. I'd be saying something like this: # near the top of your program TOP_LOG_DIR = '/var/log/test-results' # lower down when computing the subdirectory for this test run time_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') results_dir = os.path.join(TOP_LOG_DIR, time_now) Notice also that this example code does not mention the '/'; on UNIX of course that is the path separator, and /var/log is a UNIX thing, but generally you should not unnecessarily put in system depending stuff like '/' (vs '\' on say Windows) in the middle of your code. So use os.path.join to construct pathnames. > try: > retcode = os.makedirs(LOG_DIR) > if retcode: > raise Exception( > "Faild to create log directory. mkdir %s failed !!!" > % LOG_DIR) > except Exception, e: > sys.exit("Failed to create log directory...Exiting !!!") > >1. Do I need to add the cleanup code to remove the log directory >say /var/log/test_log/2015-11-25_04-07-48/ , because we might have >many more directories like this when test are run multiple times , Iam >avoiding because the test will be run > 2/3 times max and file sizes are also very small I would also avoid it. I would leave that as an entirely separate task for another program (quite possibly a shell script whose sole purpose it to tidy up things like that). That way a user can safel;y run your test program _without_ being in fear that it my, unasked, delete a whole bunch of earlier tests data. Having your test program "clean up" is effectively wiring in a policy decision into your program, where users cannot avoid or change it. All programs implement some policy (arbitrary decisions about things beyond their core purpose, such as tidyup of data they did not create), but that should be minimised; that way the users can decide on policy themselves. >2. Any better suggestion for my use case. I would change your try/except code above a little: os.makedirs does not return zero/nonzero on success/failure like a C library function, it raises an exception. So remove your if statement, changing this: retcode = os.makedirs(LOG_DIR) if retcode: raise Exception( "Faild to create log directory. mkdir %s failed !!!" % LOG_DIR) into: os.makedirs(results_dir) # see earlier code Also, you discard the value "e" of the exception. It is almost always best to report exceptions tso that the user can figure out what went wrong, not merely to know that something (unidentified) went wrong. And because os.makedirs raises an except, and the default behaviour of a python program (without a try/except) is the abort with a nonzero exit and _also_ helpfully report the whole exception and the code which caused it, you could completely discard your whole try/except! Finally. sys.exit accepts an integer, not a string. Cheers, Cameron Simpson From david.brown at hesbynett.no Thu Dec 3 04:00:12 2015 From: david.brown at hesbynett.no (David Brown) Date: Thu, 03 Dec 2015 10:00:12 +0100 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On 03/12/15 07:24, Chris in Makati wrote: > On Wed, 2 Dec 2015 08:57:44 +0000 (UTC), Juha Nieminen > wrote: > >> In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >> It's a matter of perspective. If a hacker breaks into your computer and >> starts a download from somewhere else into your computer, isn't the hacker >> "downloading" things to your computer? > > Does it matter? As far as the law is concerned, it is possession of > child porn that's illegal. How it got there is irrelevant. > You are posting to a wide range of international newsgroups (with this thread being way off-topic for all of them...). It makes no sense to talk about "the law", because this is not something covered by /international/ law. What counts as "child porn", what counts as "possession", how relevant intention, knowledge, etc., is, varies enormously from country to country. Even if the OP is telling the truth (and if Skybuck said that grass is green, I'd recommend going outside to check), and he gets caught with this stuff on his machine, punishments can vary from "it's fine as long as you don't distribute it" to "25 years for each picture, to be served consecutively". From gherron at digipen.edu Thu Dec 3 04:02:21 2015 From: gherron at digipen.edu (Gary Herron) Date: Thu, 3 Dec 2015 01:02:21 -0800 Subject: 'string.join' is wrong in my Python console In-Reply-To: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: <5660051D.9050009@digipen.edu> On 12/02/2015 10:55 PM, Robert wrote: > Hi, > > I read the tutorial on "Why is join() a string method instead of a list > or tuple method?" > at link: > https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls > > I have a problem on running the last line: > --------------- > If none of these arguments persuade you, then for the moment you can > continue to use the join() function from the string module, which allows > you to write > > string.join(['1', '2', '4', '8', '16'], ", ") > ----------------------- > > My Python console is 2.7. It should be no problem because I see the tutorial > is 2.7 too. > > The console has these display: > > string.join(['1', '2', '4', '8', '16'], ", ") > --------------------------------------------------------------------------- > NameError Traceback (most recent call last) > in () > ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") > > NameError: name 'string' is not defined > > > From the context, I don't see string should be replaced by something else. > > Could you tell me why I have such an error? You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Gary Herron > > > Thanks, -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From antoon.pardon at rece.vub.ac.be Thu Dec 3 04:06:29 2015 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 03 Dec 2015 10:06:29 +0100 Subject: static variables In-Reply-To: References: <565cf163$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4329$0$1612$c3e8da3$5496439d@news.astraweb.com> <565e4861$0$1587$c3e8da3$5496439d@news.astraweb.com> <565ec669$0$1586$c3e8da3$5496439d@news.astraweb.com> <565eee1f$0$1595$c3e8da3$5496439d@news.astraweb.com> <565EF517.3060508@rece.vub.ac.be> <565F0E8D.5080606@rece.vub.ac.be> Message-ID: <56600615.8090804@rece.vub.ac.be> Op 02-12-15 om 21:30 schreef Ian Kelly: > A person can hold one opinion in some contexts and an opposing opinion > in others. Yes people are capable of that. It doesn't mean we shouldn't challenge them on that. There are many possibilities for people to act like that. One context can be sufficiently different from the other to support a different opinion, people can be hypocritical, they can have different preference in different contexts, they can be biased, they can be in a different mood, there may be some misunderstanding. Aren't we allowed to probe for what is behind these opposing opinions? I know people who will defend a teacher leading a class in prayer in one context and several months later fight it in an other context. The difference being that in the first context the teacher's faith is compatible with there own and in the second context it isn't. When others challenge them on that and point this out, do you consider it an adequate response should they react with the quote: A foolish consistency is the hobgoblin of little minds. My opinion is that if one finds oneself in the situation that one comes to different opinions in different contexts, one should try to find out on what grounds one does so. And not let possible biases, misunderstandings, ... go unchallenged. I also see nothing wrong with challenging someone's view when you notice something like this is going on with them. But that seems to be something the regulars here have problems with because all too often they respond with the above quote and react as if that settles the question. -- Antoon. From rosuav at gmail.com Thu Dec 3 04:11:02 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Dec 2015 20:11:02 +1100 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! In-Reply-To: References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Thu, Dec 3, 2015 at 8:00 PM, David Brown wrote: > Even if the OP is telling the truth (and if Skybuck said that > grass is green, I'd recommend going outside to check) Here in Australia, we're coming up on summer, so grass is more likely to be yellowish-brown. Definitely don't believe people who claim it's green. ChrisA From nospam at thanks.invalid Thu Dec 3 04:16:32 2015 From: nospam at thanks.invalid (Juha Nieminen) Date: Thu, 3 Dec 2015 09:16:32 +0000 (UTC) Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: In comp.lang.c++ Chris in Makati wrote: > On Wed, 2 Dec 2015 08:57:44 +0000 (UTC), Juha Nieminen > wrote: > >>In comp.lang.c++ Steve Hayes wrote: >>> You download things FROM a computer, you upload them TO a computer. >> >>It's a matter of perspective. If a hacker breaks into your computer and >>starts a download from somewhere else into your computer, isn't the hacker >>"downloading" things to your computer? > > Does it matter? As far as the law is concerned, it is possession of > child porn that's illegal. How it got there is irrelevant. Most judiciary systems are not robots following a narrow set of instructions. If they determine that it wasn't your fault, they will not punish the innocent. Besides, how would they even know what's in your computer? --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From c.buhtz at posteo.jp Thu Dec 3 04:27:19 2015 From: c.buhtz at posteo.jp (c.buhtz at posteo.jp) Date: Thu, 3 Dec 2015 10:27:19 +0100 Subject: filter a list of strings In-Reply-To: References: Message-ID: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> Thank you for your suggestion. This will help a lot. On 2015-12-03 08:32 Jussi Piitulainen wrote: > list = [ item for item in list > if ( 'Banana' not in item and > 'Car' not in item ) ] I often saw constructions like this x for x in y if ... But I don't understand that combination of the Python keywords (for, in, if) I allready know. It is to complex to imagine what there really happen. I understand this for x in y: if ... But what is about the 'x' in front of all that? -- GnuPGP-Key ID 0751A8EC From rosuav at gmail.com Thu Dec 3 04:40:51 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Dec 2015 20:40:51 +1100 Subject: filter a list of strings In-Reply-To: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> References: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> Message-ID: On Thu, Dec 3, 2015 at 8:27 PM, wrote: > Thank you for your suggestion. This will help a lot. > > On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. > > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? It's called a *list comprehension*. The code Jussi posted is broadly equivalent to this: list = [] for item in list: if ( 'Banana' not in item and 'Car' not in item ): list.append(item) I recently came across this blog post, which visualizes comprehensions fairly well. http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ The bit at the beginning (before the first 'for') goes inside a list.append(...) call, and then everything else is basically the same. ChrisA From wolfgang.maier at biologie.uni-freiburg.de Thu Dec 3 04:46:54 2015 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 3 Dec 2015 10:46:54 +0100 Subject: filter a list of strings In-Reply-To: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> References: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> Message-ID: On 03.12.2015 10:27, c.buhtz at posteo.jp wrote: > > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. > > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? > The leading x states which value you want to put in the new list. This may seem obvious in the simple case, but quite often its not the original x-ses found in y that you want to store, but some transformation of it, e.g.: [x**2 for x in y] is equivalent to: squares = [] for x in y: squares.append(x**2) From lac at openend.se Thu Dec 3 04:53:16 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 10:53:16 +0100 Subject: filter a list of strings In-Reply-To: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> References: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> Message-ID: <201512030953.tB39rGLE011532@fido.openend.se> In a message of Thu, 03 Dec 2015 10:27:19 +0100, c.buhtz at posteo.jp writes: >Thank you for your suggestion. This will help a lot. > >On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > >I often saw constructions like this > x for x in y if ... >But I don't understand that combination of the Python keywords (for, >in, if) I allready know. It is to complex to imagine what there really >happen. > >I understand this > for x in y: > if ... > >But what is about the 'x' in front of all that? This is a list comprehension. see: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions But I would solve your problem like this: things_I_do_not_want = ['Car', 'Banana', ] things_I_want = [] for item in list_of_everything_I_started_with: if item not in things_I_do_not_want: things_I_want.append(item) Laura From self at example.org Thu Dec 3 05:01:41 2015 From: self at example.org (me) Date: Thu, 3 Dec 2015 10:01:41 +0000 (UTC) Subject: python message References: Message-ID: On 2015-12-02, jorge.conrado at cptec.inpe.br wrote: > I do not understand this message. Atached it my code. I'm new to Usenet, so maybe it's my fault. But I can't find any attachment in your message. Would you mind to post the code? From jeanmichel at sequans.com Thu Dec 3 05:03:48 2015 From: jeanmichel at sequans.com (jmp) Date: Thu, 03 Dec 2015 11:03:48 +0100 Subject: filter a list of strings In-Reply-To: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> References: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> Message-ID: On 12/03/2015 10:27 AM, c.buhtz at posteo.jp wrote: > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. > > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? > I'd advise you insist on understanding this construct as it is a very common (and useful) construct in python. It's a list comprehension, you can google it to get some clues about it. consider this example [2*i for i in [0,1,2,3,4] if i%2] == [2,6] you can split it in 3 parts: 1/ for i in [0,1,2,3,4] 2/ if i/2 3/ 2*i 1/ I'm assuming you understand this one 2/ this is the filter part 3/ this is the mapping part, it applies a function to each element To go back to your question "what is about the 'x' in front of all that". The x is the mapping part, but the function applied is the function identity which simply keeps the element as is. # map each element, no filter [2*i for i in [0,1,2,3,4]] == [0, 2, 4, 6, 8] # no mapping, keeping only odd elements [i for i in [0,1,2,3,4] if i%2] == [1,3] JM From __peter__ at web.de Thu Dec 3 05:13:57 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Dec 2015 11:13:57 +0100 Subject: filter a list of strings References: <3pBBdn3nVcz5vP8@dovecot03.posteo.de> <201512030953.tB39rGLE011532@fido.openend.se> Message-ID: Laura Creighton wrote: > In a message of Thu, 03 Dec 2015 10:27:19 +0100, c.buhtz at posteo.jp writes: >>Thank you for your suggestion. This will help a lot. >> >>On 2015-12-03 08:32 Jussi Piitulainen wrote: >>> list = [ item for item in list >>> if ( 'Banana' not in item and >>> 'Car' not in item ) ] >> >>I often saw constructions like this >> x for x in y if ... >>But I don't understand that combination of the Python keywords (for, >>in, if) I allready know. It is to complex to imagine what there really >>happen. >> >>I understand this >> for x in y: >> if ... >> >>But what is about the 'x' in front of all that? > > This is a list comprehension. > see: > https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions > > But I would solve your problem like this: > > things_I_do_not_want = ['Car', 'Banana', ] > things_I_want = [] > > for item in list_of_everything_I_started_with: > if item not in things_I_do_not_want: > things_I_want.append(item) Note that unlike the original code your variant will not reject "Blue Banana". If the OP wants to preserve the '"Banana" in item' test he can use for item in list_of_everything_I_started_with: for unwanted in things_I_do_not_want: if unwanted in item: break else: # executed unless the for loop exits with break things_I_want.append(item) or things_I_want = [ item for item in list_of_everything_I_started_with if not any(unwanted in item for unwanted in things_I_do_not_want) ] From harvesting at is.invalid Thu Dec 3 06:53:13 2015 From: harvesting at is.invalid (Jussi Piitulainen) Date: Thu, 03 Dec 2015 13:53:13 +0200 Subject: filter a list of strings References: Message-ID: writes: > Thank you for your suggestion. This will help a lot. > > On 2015-12-03 08:32 Jussi Piitulainen wrote: >> list = [ item for item in list >> if ( 'Banana' not in item and >> 'Car' not in item ) ] > > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. Others have given the crucial search word, "list comprehension". The brackets are part of the notation. Without brackets, or grouped in parentheses, it would be a generator expression, whose value would yield the items on demand. Curly braces would make it a set or dict comprehension; the latter also uses a colon. > I understand this > for x in y: > if ... > > But what is about the 'x' in front of all that? You can understand the notation as collecting the values from nested for-loops and conditions, just like you are attempting here, together with a fresh list that will be the result. The "x" in front can be any expression involving the loop variables; it corresponds to a result.append(x) inside the nested loops and conditions. Roughly: result = [] for x in xs: for y in ys: if x != y: result.append((x,y)) ==> result = [(x,y) for x in xs for y in ys if x != y] On python.org, this information seems to be in the tutorial but not in the language reference. From snailcoder at retrosite.invalid Thu Dec 3 07:17:30 2015 From: snailcoder at retrosite.invalid (Grobu) Date: Thu, 03 Dec 2015 13:17:30 +0100 Subject: filter a list of strings In-Reply-To: References: Message-ID: On 03/12/15 02:15, c.buhtz at posteo.jp wrote: > I would like to know how this could be done more elegant/pythonic. > > I have a big list (over 10.000 items) with strings (each 100 to 300 > chars long) and want to filter them. > > list = ..... > > for item in list[:]: > if 'Banana' in item: > list.remove(item) > if 'Car' in item: > list.remove(item) > > There are a lot of more conditions of course. This is just example code. > It doesn't look nice to me. To much redundance. > > btw: Is it correct to iterate over a copy (list[:]) of that string list > and not the original one? > No idea how 'Pythonic' this would be considered, but you could use a combination of filter() with a regular expression : # ------------------------------------------------------------------ import re list = ... pattern = re.compile( r'banana|car', re.I ) filtered_list = filter( lambda line: not pattern.search(line), list ) # ------------------------------------------------------------------ HTH From breamoreboy at yahoo.co.uk Thu Dec 3 07:28:07 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 3 Dec 2015 12:28:07 +0000 Subject: filter a list of strings In-Reply-To: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> References: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> Message-ID: On 03/12/2015 01:15, c.buhtz at posteo.jp wrote: > I would like to know how this could be done more elegant/pythonic. > > I have a big list (over 10.000 items) with strings (each 100 to 300 > chars long) and want to filter them. > > list = ..... > > for item in list[:]: > if 'Banana' in item: > list.remove(item) > if 'Car' in item: > list.remove(item) > > There are a lot of more conditions of course. This is just example code. > It doesn't look nice to me. To much redundance. targets = ['Banana', 'Car'...] for item in list[:]: for target in targets: if target in item: list.remove(item) > > btw: Is it correct to iterate over a copy (list[:]) of that string list > and not the original one? > Absolutely :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From eclectic959 at gmail.com Thu Dec 3 07:30:49 2015 From: eclectic959 at gmail.com (eclectic959 at gmail.com) Date: Thu, 3 Dec 2015 04:30:49 -0800 (PST) Subject: Are there any plans to support nCurses 6.0 with Python? Message-ID: <4c9dc771-59f4-4f1e-902e-fc2e7dfa2677@googlegroups.com> The GNU Project has announced the release of nCurses 6.0. With it, Python curses would be able to support 256 colors instead of the current 8 or 16. I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is not usable by Python programs, such as my character-mode emulation of pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates a 71 color palette but will not work (its has been disabled) with the existing 16-color curses because text attributes (such as underline) partially overlay the foreground-background color-pair attributes. From breamoreboy at yahoo.co.uk Thu Dec 3 08:43:36 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 3 Dec 2015 13:43:36 +0000 Subject: Are there any plans to support nCurses 6.0 with Python? In-Reply-To: <4c9dc771-59f4-4f1e-902e-fc2e7dfa2677@googlegroups.com> References: <4c9dc771-59f4-4f1e-902e-fc2e7dfa2677@googlegroups.com> Message-ID: On 03/12/2015 12:30, eclectic959 at gmail.com wrote: > The GNU Project has announced the release of nCurses 6.0. > > With it, Python curses would be able to support 256 colors instead of the current 8 or 16. > > I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is not usable by Python programs, such as my character-mode emulation of pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates a 71 color palette but will not work (its has been disabled) with the existing 16-color curses because text attributes (such as underline) partially overlay the foreground-background color-pair attributes. > Work is all ready being done to support building Python with ncurses6, see https://bugs.python.org/issue25720. Whether this alone meets your needs or an enhancement request on the bug tracker against 3.6 is required I'm really not qualified to say. -- 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 Dec 3 09:16:34 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 3 Dec 2015 14:16:34 -0000 (UTC) Subject: filter a list of strings References: Message-ID: On Thu, 03 Dec 2015 08:32:49 +0200, Jussi Piitulainen wrote: > def isbad(item): > return ( 'Banana' in item or > 'Car' in item ) > > def isgood(item) > return not isbad(item) badthings = [ 'Banana', 'Car', ........] def isgood(item) for thing in badthings: if thing in item: return False return True -- Denis McMahon, denismfmcmahon at gmail.com From harvesting at is.invalid Thu Dec 3 10:02:07 2015 From: harvesting at is.invalid (Jussi Piitulainen) Date: Thu, 03 Dec 2015 17:02:07 +0200 Subject: filter a list of strings References: Message-ID: Denis McMahon writes: > On Thu, 03 Dec 2015 08:32:49 +0200, Jussi Piitulainen wrote: > >> def isbad(item): >> return ( 'Banana' in item or >> 'Car' in item ) >> >> def isgood(item) >> return not isbad(item) > > badthings = [ 'Banana', 'Car', ........] > > def isgood(item) > for thing in badthings: > if thing in item: > return False > return True As long as all conditions are of that shape. From a24061 at ducksburg.com Thu Dec 3 10:12:15 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 03 Dec 2015 15:12:15 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? Message-ID: I'm having trouble with some input files that are almost all proper UTF-8 but with a couple of troublesome characters mixed in, which I'd like to ignore instead of throwing ValueError. I've found the openhook for the encoding for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): do_stuff(line) which the documentation describes as "a hook which opens each file with codecs.open(), using the given encoding to read the file", but I'd like codecs.open() to also have the errors='ignore' or errors='replace' effect. Is it possible to do this? Thanks. -- Why is it drug addicts and computer afficionados are both called users? --- Clifford Stoll From a24061 at ducksburg.com Thu Dec 3 10:18:32 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 03 Dec 2015 15:18:32 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? References: Message-ID: <8336jcxi2m.ln2@news.ducksburg.com> On 2015-12-03, Adam Funk wrote: > I'm having trouble with some input files that are almost all proper > UTF-8 but with a couple of troublesome characters mixed in, which I'd > like to ignore instead of throwing ValueError. I've found the > openhook for the encoding > > for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): > do_stuff(line) > > which the documentation describes as "a hook which opens each file > with codecs.open(), using the given encoding to read the file", but > I'd like codecs.open() to also have the errors='ignore' or > errors='replace' effect. Is it possible to do this? I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different machines). -- ...the reason why so many professional artists drink a lot is not necessarily very much to do with the artistic temperament, etc. It is simply that they can afford to, because they can normally take a large part of a day off to deal with the ravages. --- Amis _On Drink_ From Seymore4Head at Hotmail.invalid Thu Dec 3 11:00:22 2015 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 03 Dec 2015 11:00:22 -0500 Subject: Does Python 2.7 do Open Office References: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> Message-ID: On Thu, 3 Dec 2015 00:47:42 +0000, MRAB wrote: >On 2015-12-02 23:50, Seymore4Head wrote: >> I have a text file I would like to search through but I have tried it >> before. I don't remember why they are not compatible together, but I >> wanted to ask to make sure. >> >> I know I can convert the file to plain text but it would be nice not >> to have to do that. >> >A quick search found this: > >https://wiki.openoffice.org/wiki/Python Thanks From robin.koch at t-online.de Thu Dec 3 11:00:32 2015 From: robin.koch at t-online.de (Robin Koch) Date: Thu, 3 Dec 2015 17:00:32 +0100 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: Am 03.12.2015 um 10:02 schrieb Gary Herron: > On 12/02/2015 10:55 PM, Robert wrote: >> Hi, >> >> I read the tutorial on "Why is join() a string method instead of a list >> or tuple method?" >> at link: >> https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls >> >> >> I have a problem on running the last line: >> --------------- >> If none of these arguments persuade you, then for the moment you can >> continue to use the join() function from the string module, which >> allows >> you to write >> >> string.join(['1', '2', '4', '8', '16'], ", ") >> ----------------------- >> >> My Python console is 2.7. It should be no problem because I see the >> tutorial >> is 2.7 too. >> >> The console has these display: >> >> string.join(['1', '2', '4', '8', '16'], ", ") >> --------------------------------------------------------------------------- >> >> NameError Traceback (most recent call >> last) >> in () >> ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") >> >> NameError: name 'string' is not defined >> >> >> From the context, I don't see string should be replaced by something >> else. >> >> Could you tell me why I have such an error? > > You are trying to use the *string* module without importing it, I'd guess. > > Try: > import string > first then you should be able to access string.join without error. Now *I* am confused. Shouldn't it be ", ".join(['1', '2', '4', '8', '16']) instead? Without any importing? -- Robin Koch From Seymore4Head at Hotmail.invalid Thu Dec 3 11:00:44 2015 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 03 Dec 2015 11:00:44 -0500 Subject: Does Python 2.7 do Open Office References: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> Message-ID: <5pp06bhbi7cfu2c4n1espkb55em9cunq02@4ax.com> On Thu, 03 Dec 2015 01:54:16 +0100, Laura Creighton wrote: >In a message of Wed, 02 Dec 2015 18:50:34 -0500, Seymore4Head writes: >>I have a text file I would like to search through but I have tried it >>before. I don't remember why they are not compatible together, but I >>wanted to ask to make sure. >> >>I know I can convert the file to plain text but it would be nice not >>to have to do that. >> >>-- >>https://mail.python.org/mailman/listinfo/python-list > >You are looking for PyUNO.Unfortuntately it is not well >documented, but I have heard good things about this as documentation. >https://documenthacker.wordpress.com/2013/03/05/first-draft-released/ > >Laura Thanks From __peter__ at web.de Thu Dec 3 11:11:37 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Dec 2015 17:11:37 +0100 Subject: getting fileinput to do errors='ignore' or 'replace'? References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: Adam Funk wrote: > On 2015-12-03, Adam Funk wrote: > >> I'm having trouble with some input files that are almost all proper >> UTF-8 but with a couple of troublesome characters mixed in, which I'd >> like to ignore instead of throwing ValueError. I've found the >> openhook for the encoding >> >> for line in fileinput.input(options.files, >> openhook=fileinput.hook_encoded("utf-8")): >> do_stuff(line) >> >> which the documentation describes as "a hook which opens each file >> with codecs.open(), using the given encoding to read the file", but >> I'd like codecs.open() to also have the errors='ignore' or >> errors='replace' effect. Is it possible to do this? > > I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different > machines). Have a look at the source of fileinput.hook_encoded: def hook_encoded(encoding): import io def openhook(filename, mode): mode = mode.replace('U', '').replace('b', '') or 'r' return io.open(filename, mode, encoding=encoding, newline='') return openhook You can use it as a template to write your own factory function: def my_hook_encoded(encoding, errors=None): import io def openhook(filename, mode): mode = mode.replace('U', '').replace('b', '') or 'r' return io.open( filename, mode, encoding=encoding, newline='', errors=errors) return openhook for line in fileinput.input( options.files, openhook=my_hook_encoded("utf-8", errors="ignore")): do_stuff(line) Another option is to create the function on the fly: for line in fileinput.input( options.files, openhook=functools.partial( io.open, encoding="utf-8", errors="replace")): do_stuff(line) (codecs.open() instead of io.open() should also work) From python at mrabarnett.plus.com Thu Dec 3 11:12:55 2015 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 3 Dec 2015 16:12:55 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: Message-ID: <56606A07.5050102@mrabarnett.plus.com> On 2015-12-03 15:12, Adam Funk wrote: > I'm having trouble with some input files that are almost all proper > UTF-8 but with a couple of troublesome characters mixed in, which I'd > like to ignore instead of throwing ValueError. I've found the > openhook for the encoding > > for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): > do_stuff(line) > > which the documentation describes as "a hook which opens each file > with codecs.open(), using the given encoding to read the file", but > I'd like codecs.open() to also have the errors='ignore' or > errors='replace' effect. Is it possible to do this? > It looks like it's not possible with the standard "hook_encoded", but you could write your own alternative: import codecs def my_hook_encoded(encoding, errors): def opener(path, mode): return codecs.open(path, mode, encoding=encoding, errors=errors) return opener for line in fileinput.input(options.files, openhook=fileinput.my_hook_encoded("utf-8", "ignore")): do_stuff(line) From tjreedy at udel.edu Thu Dec 3 11:19:29 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Dec 2015 11:19:29 -0500 Subject: filter a list of strings In-Reply-To: References: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> Message-ID: On 12/3/2015 7:28 AM, Mark Lawrence wrote: > On 03/12/2015 01:15, c.buhtz at posteo.jp wrote: >> I would like to know how this could be done more elegant/pythonic. >> >> I have a big list (over 10.000 items) with strings (each 100 to 300 >> chars long) and want to filter them. >> >> list = ..... >> >> for item in list[:]: >> if 'Banana' in item: >> list.remove(item) >> if 'Car' in item: >> list.remove(item) >> >> There are a lot of more conditions of course. This is just example code. >> It doesn't look nice to me. To much redundance. > > targets = ['Banana', 'Car'...] > for item in list[:]: > for target in targets: > if target in item: > list.remove(item) > >> >> btw: Is it correct to iterate over a copy (list[:]) of that string list >> and not the original one? >> > > Absolutely :) Even better, instead of copying and deleting, which is O(k*n), where n is the len of list and k is number deletions, is to create a new list with the item you want. In other words, actually filter, as you said you want. targets = {'Banana', 'Car', ...} # set intentional newlist = [item for item in oldlist if item not in targets] Generically, replace 'not in targets' with any boolean expression or function. -- Terry Jan Reedy From python at mrabarnett.plus.com Thu Dec 3 11:24:07 2015 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 3 Dec 2015 16:24:07 +0000 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: <56606CA7.7040605@mrabarnett.plus.com> On 2015-12-03 16:00, Robin Koch wrote: > Am 03.12.2015 um 10:02 schrieb Gary Herron: >> On 12/02/2015 10:55 PM, Robert wrote: >>> Hi, >>> >>> I read the tutorial on "Why is join() a string method instead of a list >>> or tuple method?" >>> at link: >>> https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls >>> >>> >>> I have a problem on running the last line: >>> --------------- >>> If none of these arguments persuade you, then for the moment you can >>> continue to use the join() function from the string module, which >>> allows >>> you to write >>> >>> string.join(['1', '2', '4', '8', '16'], ", ") >>> ----------------------- >>> >>> My Python console is 2.7. It should be no problem because I see the >>> tutorial >>> is 2.7 too. >>> >>> The console has these display: >>> >>> string.join(['1', '2', '4', '8', '16'], ", ") >>> --------------------------------------------------------------------------- >>> >>> NameError Traceback (most recent call >>> last) >>> in () >>> ----> 1 string.join(['1', '2', '4', '8', '16'], ", ") >>> >>> NameError: name 'string' is not defined >>> >>> >>> From the context, I don't see string should be replaced by something >>> else. >>> >>> Could you tell me why I have such an error? >> >> You are trying to use the *string* module without importing it, I'd guess. >> >> Try: >> import string >> first then you should be able to access string.join without error. > > Now *I* am confused. > > Shouldn't it be > > ", ".join(['1', '2', '4', '8', '16']) > > instead? Without any importing? > The documentation says: """The string module contains a number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings.""" The "join" function is one of those old functions you don't need any more, and you're correct that the the "join" method should be used instead. From ian.g.kelly at gmail.com Thu Dec 3 11:25:46 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 3 Dec 2015 09:25:46 -0700 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: > Now *I* am confused. > > Shouldn't it be > > ", ".join(['1', '2', '4', '8', '16']) > > instead? Without any importing? That would be the normal way to write it. The FAQ entry is suggesting the string module function as an alternative for those who can't accept it as a string method. From framstag at rus.uni-stuttgart.de Thu Dec 3 11:32:09 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 3 Dec 2015 16:32:09 +0000 (UTC) Subject: urllib2.urlopen() crashes on Windows 2008 Server Message-ID: I have a Python2 program which runs fine on Windows 7, but crashes on Windows 2008 Server R2 64 bit: downloading http://fex.belwue.de/download/7za.exe Traceback (most recent call last): File "", line 1992, in File "", line 180, in main File "", line 329, in get_ID File "", line 1627, in check_7z File "C:\Software\Python\lib\urllib2.py", line 154, in urlopen File "C:\Software\Python\lib\urllib2.py", line 431, in open File "C:\Software\Python\lib\urllib2.py", line 449, in _open File "C:\Software\Python\lib\urllib2.py", line 409, in _call_chain File "C:\Software\Python\lib\urllib2.py", line 1227, in http_open File "C:\Software\Python\lib\urllib2.py", line 1200, in do_open File "C:\Software\Python\lib\httplib.py", line 1132, in getresponse File "C:\Software\Python\lib\httplib.py", line 485, in begin File "C:\Software\Python\lib\mimetools.py", line 25, in __init__ File "C:\Software\Python\lib\rfc822.py", line 108, in __init__ File "C:\Software\Python\lib\httplib.py", line 319, in readheaders File "C:\Software\Python\lib\socket.py", line 480, in readline error: [Errno 10054] Eine vorhandene Verbindung wurde vom Remotehost geschlossen This is the function where the error happens: if python2: import urllib2 as urllib if python3: import urllib.request as urllib def check_7z(): global sz sz = path.join(fexhome,'7za.exe') szurl = "http://fex.belwue.de/download/7za.exe" if not path.exists(sz) or path.getsize(sz) < 9999: try: szo = open(sz,'wb') except (IOError,OSError) as e: die('cannot write %s - %s' % (sz,e.strerror)) printf("\ndownloading %s\n",szurl) try: req = urllib.Request(szurl) req.add_header('User-Agent',useragent) u = urllib.urlopen(req) # line 1627 # except urllib.URLError as e: die('cannot get %s - %s' % (szurl,e.reason)) except urllib.HTTPError as e: die('cannot get %s - server reply: %d %s' % (szurl,e.code,e.reason)) if u.getcode() == 200: copy_file_obj(u,szo) szo.close() else: die('cannot get %s - server reply: %d' % (szurl,u.getcode())) The curious thing is: the download was successful, the file 7za.exe is there in the local directory! -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From lac at openend.se Thu Dec 3 11:46:39 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 17:46:39 +0100 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: Message-ID: <201512031646.tB3Gkd2Y017982@fido.openend.se> In a message of Thu, 03 Dec 2015 15:12:15 +0000, Adam Funk writes: >I'm having trouble with some input files that are almost all proper >UTF-8 but with a couple of troublesome characters mixed in, which I'd >like to ignore instead of throwing ValueError. I've found the >openhook for the encoding > >for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): > do_stuff(line) > >which the documentation describes as "a hook which opens each file >with codecs.open(), using the given encoding to read the file", but >I'd like codecs.open() to also have the errors='ignore' or >errors='replace' effect. Is it possible to do this? > >Thanks. This should be both easy to add, and useful, and I happen to know that fileinput is being hacked on by Serhiy Storchaka right now, who agrees that this would be easy. So, with his approval, I stuck this into the tracker. http://bugs.python.org/issue25788 Future Pythons may not have the problem. Laura From tjreedy at udel.edu Thu Dec 3 11:48:13 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Dec 2015 11:48:13 -0500 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: <8336jcxi2m.ln2@news.ducksburg.com> References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: On 12/3/2015 10:18 AM, Adam Funk wrote: > On 2015-12-03, Adam Funk wrote: > >> I'm having trouble with some input files that are almost all proper >> UTF-8 but with a couple of troublesome characters mixed in, which I'd >> like to ignore instead of throwing ValueError. I've found the >> openhook for the encoding >> >> for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): >> do_stuff(line) >> >> which the documentation describes as "a hook which opens each file >> with codecs.open(), using the given encoding to read the file", but >> I'd like codecs.open() to also have the errors='ignore' or >> errors='replace' effect. Is it possible to do this? > > I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different > machines). fileinput is an ancient module that predates iterators (and generators) and context managers. Since by 2.7 open files are both context managers and line iterators, you can easily write your own multi-file line iteration that does exactly what you want. At minimum: for file in files: with codecs.open(file, errors='ignore') as f # did not look up signature, for line in f: do_stuff(line) To make this reusable, wrap in 'def filelines(files):' and replace 'do_stuff(line)' with 'yield line'. -- Terry Jan Reedy From robin.koch at t-online.de Thu Dec 3 12:01:21 2015 From: robin.koch at t-online.de (Robin Koch) Date: Thu, 3 Dec 2015 18:01:21 +0100 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: Am 03.12.2015 um 17:25 schrieb Ian Kelly: > On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch wrote: >> Now *I* am confused. >> >> Shouldn't it be >> >> ", ".join(['1', '2', '4', '8', '16']) >> >> instead? Without any importing? > > That would be the normal way to write it. The FAQ entry is suggesting > the string module function as an alternative for those who can't > accept it as a string method. Whoops. Thanks and sorry. :-) -- Robin Koch From eclectic959 at gmail.com Thu Dec 3 12:11:46 2015 From: eclectic959 at gmail.com (eclectic959 at gmail.com) Date: Thu, 3 Dec 2015 09:11:46 -0800 (PST) Subject: Are there any plans to support nCurses 6.0 with Python? In-Reply-To: References: <4c9dc771-59f4-4f1e-902e-fc2e7dfa2677@googlegroups.com> Message-ID: <31242786-b25f-4990-b75c-8b9d685b45d0@googlegroups.com> On Thursday, December 3, 2015 at 8:44:30 AM UTC-5, Mark Lawrence wrote: > On 03/12/2015 12:30, eclectic959 at gmail.com wrote: > > The GNU Project has announced the release of nCurses 6.0. > > > > With it, Python curses would be able to support 256 colors instead of the current 8 or 16. > > > > I've discovered that a pre-release of Fedora 24 includes ncurses 6.0. It is not usable by Python programs, such as my character-mode emulation of pixel-mode WxPython (available as "tsWxGTUI_PyVx" on GitHub) which creates a 71 color palette but will not work (its has been disabled) with the existing 16-color curses because text attributes (such as underline) partially overlay the foreground-background color-pair attributes. > > > > Work is all ready being done to support building Python with ncurses6, > see https://bugs.python.org/issue25720. Whether this alone meets your > needs or an enhancement request on the bug tracker against 3.6 is > required I'm really not qualified to say. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence ncurses6 provides both an application binary interface for ncurses6.0 an one for ncurses5.0. Perhaps it will take an enhancement request to adopt the ABI 6.0 that su[prts 256 colors. From tjreedy at udel.edu Thu Dec 3 12:23:20 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Dec 2015 12:23:20 -0500 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: On 12/3/2015 11:00 AM, Robin Koch wrote: > Am 03.12.2015 um 10:02 schrieb Gary Herron: >> On 12/02/2015 10:55 PM, Robert wrote: >>> Hi, >>> >>> I read the tutorial on "Why is join() a string method instead of a list >>> or tuple method?" >>> at link: >>> https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls >>> >>> >>> >>> I have a problem on running the last line: >>> --------------- >>> If none of these arguments persuade you, then for the moment you can >>> continue to use the join() function from the string module, which >>> allows >>> you to write >>> >>> string.join(['1', '2', '4', '8', '16'], ", ") >>> ----------------------- ... >> You are trying to use the *string* module without importing it, I'd >> guess. >> >> Try: >> import string >> first then you should be able to access string.join without error. > > Now *I* am confused. > > Shouldn't it be > > ", ".join(['1', '2', '4', '8', '16']) > > instead? Without any importing? Yes, that is what one *should* do in late 2.x and indeed must do in 3.x, where the string module has been stripped of the functions that later became string methods. The FAQ entry was written when the join method was new as a method and some people were upset by the reversal of the order of the two arguments, an iterable of strings and the joining string. -- Terry Jan Reedy From tjreedy at udel.edu Thu Dec 3 12:26:44 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 Dec 2015 12:26:44 -0500 Subject: Does Python 2.7 do Open Office In-Reply-To: References: <3q0v5bpsgvjh2pd66uh7epv2jdbecmp019@4ax.com> Message-ID: On 12/3/2015 11:00 AM, Seymore4Head wrote: > On Thu, 3 Dec 2015 00:47:42 +0000, MRAB > wrote: > >> On 2015-12-02 23:50, Seymore4Head wrote: >>> I have a text file I would like to search through but I have tried it >>> before. I don't remember why they are not compatible together, but I >>> wanted to ask to make sure. >>> >>> I know I can convert the file to plain text but it would be nice not >>> to have to do that. >>> >> A quick search found this: >> >> https://wiki.openoffice.org/wiki/Python LibreOffice rather sensibly (given that it is a any-language unicode editor) jumped to 3.3 a couple of years ago. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Thu Dec 3 12:42:27 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 3 Dec 2015 17:42:27 +0000 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: On 03/12/2015 17:01, Robin Koch wrote: > Am 03.12.2015 um 17:25 schrieb Ian Kelly: >> On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch >> wrote: >>> Now *I* am confused. >>> >>> Shouldn't it be >>> >>> ", ".join(['1', '2', '4', '8', '16']) >>> >>> instead? Without any importing? >> >> That would be the normal way to write it. The FAQ entry is suggesting >> the string module function as an alternative for those who can't >> accept it as a string method. > > Whoops. > Thanks and sorry. :-) > You might like to note that here https://docs.python.org/3/faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method the reference to the string module function has been completely removed. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From robin.koch at t-online.de Thu Dec 3 13:15:01 2015 From: robin.koch at t-online.de (Robin Koch) Date: Thu, 3 Dec 2015 19:15:01 +0100 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: Am 03.12.2015 um 18:42 schrieb Mark Lawrence: > On 03/12/2015 17:01, Robin Koch wrote: >> Am 03.12.2015 um 17:25 schrieb Ian Kelly: >>> On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch >>> wrote: >>>> Now *I* am confused. >>>> >>>> Shouldn't it be >>>> >>>> ", ".join(['1', '2', '4', '8', '16']) >>>> >>>> instead? Without any importing? >>> >>> That would be the normal way to write it. The FAQ entry is suggesting >>> the string module function as an alternative for those who can't >>> accept it as a string method. >> >> Whoops. >> Thanks and sorry. :-) >> > > You might like to note that here > https://docs.python.org/3/faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method > the reference to the string module function has been completely removed. Actually I did. :-) I tried the line with my Python 3.4 and it didn't work. Then I sent my initial posting. After Ians answer I took a look in the 2.x and the 3.x FAQs and found exactly that phrase removed. :-) -- Robin Koch From robin.koch at t-online.de Thu Dec 3 13:16:21 2015 From: robin.koch at t-online.de (Robin Koch) Date: Thu, 3 Dec 2015 19:16:21 +0100 Subject: 'string.join' is wrong in my Python console In-Reply-To: References: <88afafc5-699f-46ea-aaca-7e78b75a4552@googlegroups.com> Message-ID: Am 03.12.2015 um 18:23 schrieb Terry Reedy: > On 12/3/2015 11:00 AM, Robin Koch wrote: >> Am 03.12.2015 um 10:02 schrieb Gary Herron: >>> On 12/02/2015 10:55 PM, Robert wrote: >>>> Hi, >>>> >>>> I read the tutorial on "Why is join() a string method instead of a list >>>> or tuple method?" >>>> at link: >>>> https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls >>>> >>>> >>>> >>>> >>>> I have a problem on running the last line: >>>> --------------- >>>> If none of these arguments persuade you, then for the moment you can >>>> continue to use the join() function from the string module, which >>>> allows >>>> you to write >>>> >>>> string.join(['1', '2', '4', '8', '16'], ", ") >>>> ----------------------- > ... >>> You are trying to use the *string* module without importing it, I'd >>> guess. >>> >>> Try: >>> import string >>> first then you should be able to access string.join without error. >> >> Now *I* am confused. >> >> Shouldn't it be >> >> ", ".join(['1', '2', '4', '8', '16']) >> >> instead? Without any importing? > > Yes, that is what one *should* do in late 2.x and indeed must do in 3.x, > where the string module has been stripped of the functions that later > became string methods. The FAQ entry was written when the join method > was new as a method and some people were upset by the reversal of the > order of the two arguments, an iterable of strings and the joining string. Thank you. I figured that out by now. :-) I just didn't followed the link of the OP. -- Robin Koch From a24061 at ducksburg.com Thu Dec 3 14:17:32 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 03 Dec 2015 19:17:32 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: On 2015-12-03, Peter Otten wrote: > def my_hook_encoded(encoding, errors=None): > import io > def openhook(filename, mode): > mode = mode.replace('U', '').replace('b', '') or 'r' > return io.open( > filename, mode, > encoding=encoding, newline='', > errors=errors) > return openhook > > for line in fileinput.input( > options.files, > openhook=my_hook_encoded("utf-8", errors="ignore")): > do_stuff(line) Perfect, thanks! > (codecs.open() instead of io.open() should also work) OK. -- The internet is quite simply a glorious place. Where else can you find bootlegged music and films, questionable women, deep seated xenophobia and amusing cats all together in the same place? --- Tom Belshaw From a24061 at ducksburg.com Thu Dec 3 14:17:51 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 03 Dec 2015 19:17:51 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? References: Message-ID: On 2015-12-03, Laura Creighton wrote: > In a message of Thu, 03 Dec 2015 15:12:15 +0000, Adam Funk writes: >>I'm having trouble with some input files that are almost all proper >>UTF-8 but with a couple of troublesome characters mixed in, which I'd >>like to ignore instead of throwing ValueError. I've found the >>openhook for the encoding >> >>for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): >> do_stuff(line) >> >>which the documentation describes as "a hook which opens each file >>with codecs.open(), using the given encoding to read the file", but >>I'd like codecs.open() to also have the errors='ignore' or >>errors='replace' effect. Is it possible to do this? >> >>Thanks. > > This should be both easy to add, and useful, and I happen to know that > fileinput is being hacked on by Serhiy Storchaka right now, who agrees > that this would be easy. So, with his approval, I stuck this into the > tracker. http://bugs.python.org/issue25788 > > Future Pythons may not have the problem. Good to know, thanks. -- You cannot really appreciate Dilbert unless you've read it in the original Klingon. --- Klingon Programmer's Guide From a24061 at ducksburg.com Thu Dec 3 14:21:41 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 03 Dec 2015 19:21:41 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: <5bh6jcxtas.ln2@news.ducksburg.com> On 2015-12-03, Terry Reedy wrote: > fileinput is an ancient module that predates iterators (and generators) > and context managers. Since by 2.7 open files are both context managers > and line iterators, you can easily write your own multi-file line > iteration that does exactly what you want. At minimum: > > for file in files: > with codecs.open(file, errors='ignore') as f > # did not look up signature, > for line in f: > do_stuff(line) > > To make this reusable, wrap in 'def filelines(files):' and replace > 'do_stuff(line)' with 'yield line'. I like fileinput because if the file list is empty, it reads from stdin instead (so I can pipe something else's output into it). Unfortunately, the fix I got elsewhere in this thread doesn't seem to work for that! -- Science is what we understand well enough to explain to a computer. Art is everything else we do. --- Donald Knuth From dgoodwin352 at gmail.com Thu Dec 3 14:25:53 2015 From: dgoodwin352 at gmail.com (Dylan Goodwin) Date: Thu, 3 Dec 2015 21:25:53 +0200 Subject: problem Message-ID: Every time I try and run python 3.5 it keeps coming up with modify, repair or uninstall From lac at openend.se Thu Dec 3 14:34:10 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 3 Dec 2015 20:34:10 +0100 Subject: Idle, tk and MacOS Message-ID: <201512031934.tB3JYAo2020793@fido.openend.se> This in to webmaster. Somebody got an error message about their Tcl/Tk when they started using IDLE. They went to https://www.python.org/download/mac/tcltk/ and, yes indeed, their tk is 8.5.9, their OS is 10.8.5 so they have a problem. They downloaded the patch from ActiveState, and did _something_ which reported 'installation successful'. But when they restart Idle it still has 8.5.9 What else do they need to do? Laura From lac at openend.se Thu Dec 3 15:40:16 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 21:40:16 +0100 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: Message-ID: <201512032040.tB3KeGwJ021803@fido.openend.se> In a message of Thu, 03 Dec 2015 19:17:51 +0000, Adam Funk writes: >On 2015-12-03, Laura Creighton wrote: > >> In a message of Thu, 03 Dec 2015 15:12:15 +0000, Adam Funk writes: >>>I'm having trouble with some input files that are almost all proper >>>UTF-8 but with a couple of troublesome characters mixed in, which I'd >>>like to ignore instead of throwing ValueError. I've found the >>>openhook for the encoding >>> >>>for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): >>> do_stuff(line) >>> >>>which the documentation describes as "a hook which opens each file >>>with codecs.open(), using the given encoding to read the file", but >>>I'd like codecs.open() to also have the errors='ignore' or >>>errors='replace' effect. Is it possible to do this? >>> >>>Thanks. >> >> This should be both easy to add, and useful, and I happen to know that >> fileinput is being hacked on by Serhiy Storchaka right now, who agrees >> that this would be easy. So, with his approval, I stuck this into the >> tracker. http://bugs.python.org/issue25788 >> >> Future Pythons may not have the problem. > >Good to know, thanks. Well, we have moved right along to 'You write the patch, Laura' so I can pretty much guarantee that future Pythons won't have the problem. :) Laura From lac at openend.se Thu Dec 3 15:50:30 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 03 Dec 2015 21:50:30 +0100 Subject: Idle, tk and MacOS In-Reply-To: <201512031934.tB3JYAo2020793@fido.openend.se> References: <201512031934.tB3JYAo2020793@fido.openend.se> Message-ID: <201512032050.tB3KoUh6022079@fido.openend.se> In a message of Thu, 03 Dec 2015 20:34:10 +0100, Laura Creighton writes: >This in to webmaster. Somebody got an error message about their >Tcl/Tk when they started using IDLE. > >They went to https://www.python.org/download/mac/tcltk/ >and, yes indeed, their tk is 8.5.9, their OS is 10.8.5 so they >have a problem. They downloaded the patch from ActiveState, >and did _something_ which reported 'installation successful'. > >But when they restart Idle it still has 8.5.9 > >What else do they need to do? > >Laura The OP reported that trying to do it again seems to have worked great, so I guess something went wrong the first time. Laura From oscar.j.benjamin at gmail.com Thu Dec 3 17:26:22 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 3 Dec 2015 22:26:22 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: On 3 Dec 2015 16:50, "Terry Reedy" wrote: > > On 12/3/2015 10:18 AM, Adam Funk wrote: >> >> On 2015-12-03, Adam Funk wrote: >> >>> I'm having trouble with some input files that are almost all proper >>> UTF-8 but with a couple of troublesome characters mixed in, which I'd >>> like to ignore instead of throwing ValueError. I've found the >>> openhook for the encoding >>> >>> for line in fileinput.input(options.files, openhook=fileinput.hook_encoded("utf-8")): >>> do_stuff(line) >>> >>> which the documentation describes as "a hook which opens each file >>> with codecs.open(), using the given encoding to read the file", but >>> I'd like codecs.open() to also have the errors='ignore' or >>> errors='replace' effect. Is it possible to do this? >> >> >> I forgot to mention: this is for Python 2.7.3 & 2.7.10 (on different >> machines). > > > fileinput is an ancient module that predates iterators (and generators) and context managers. Since by 2.7 open files are both context managers and line iterators, you can easily write your own multi-file line iteration that does exactly what you want. At minimum: > > for file in files: > with codecs.open(file, errors='ignore') as f > # did not look up signature, > for line in f: > do_stuff(line) The above is fine but... > To make this reusable, wrap in 'def filelines(files):' and replace 'do_stuff(line)' with 'yield line'. That doesn't work entirely correctly as you end up yielding from inside a with statement. If the user of your generator function doesn't fully consume the generator then whichever file is currently open is not guaranteed to be closed. -- Oscar From rxjwg98 at gmail.com Thu Dec 3 19:30:25 2015 From: rxjwg98 at gmail.com (Robert) Date: Thu, 3 Dec 2015 16:30:25 -0800 (PST) Subject: Is there a way to set several list elements a same value with one line code Message-ID: Hi, I remember that there is a way to set several list elements a same value with one line code. Excuse me, I don't remember the accurate syntax on the code snippet. But the basic format looks like this. 1. There is a four-element list, such as: bb=[[[]],[[]],[[]],[[]]] 2. An assignment line is here: bb[0]='a' 3. Then, all 4 element of bb is set with the above value. bb=[['a'],['a'],['a'],['a']] The above three line codes are what I guess (I forgot the original tutorial now). Do you remember there is such a list application? Thanks, From python at mrabarnett.plus.com Thu Dec 3 19:58:39 2015 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 4 Dec 2015 00:58:39 +0000 Subject: Is there a way to set several list elements a same value with one line code In-Reply-To: References: Message-ID: <5660E53F.7080201@mrabarnett.plus.com> On 2015-12-04 00:30, Robert wrote: > Hi, > > I remember that there is a way to set several list elements a same value with > one line code. Excuse me, I don't remember the accurate syntax on the code > snippet. But the basic format looks like this. > > 1. There is a four-element list, such as: > bb=[[[]],[[]],[[]],[[]]] > 2. An assignment line is here: > bb[0]='a' > 3. Then, all 4 element of bb is set with the above value. > bb=[['a'],['a'],['a'],['a']] > > The above three line codes are what I guess (I forgot the original tutorial > now). Do you remember there is such a list application? > Do you mean this behaviour: >>> bb=[[[]]] * 4 >>> print(bb) [[[]], [[]], [[]], [[]]] >>> bb[0][0]='a' >>> print(bb) [['a'], ['a'], ['a'], ['a']] ? That's because the bb contains 4 references to the same list. From rxjwg98 at gmail.com Thu Dec 3 21:11:24 2015 From: rxjwg98 at gmail.com (Robert) Date: Thu, 3 Dec 2015 18:11:24 -0800 (PST) Subject: Is there a way to set several list elements a same value with one line code In-Reply-To: References: Message-ID: <46a3ad9e-02f9-4bb0-9981-e7dd8fcb8f30@googlegroups.com> On Thursday, December 3, 2015 at 7:59:16 PM UTC-5, MRAB wrote: > On 2015-12-04 00:30, Robert wrote: > > Hi, > > > > I remember that there is a way to set several list elements a same value with > > one line code. Excuse me, I don't remember the accurate syntax on the code > > snippet. But the basic format looks like this. > > > > 1. There is a four-element list, such as: > > bb=[[[]],[[]],[[]],[[]]] > > 2. An assignment line is here: > > bb[0]='a' > > 3. Then, all 4 element of bb is set with the above value. > > bb=[['a'],['a'],['a'],['a']] > > > > The above three line codes are what I guess (I forgot the original tutorial > > now). Do you remember there is such a list application? > > > Do you mean this behaviour: > > >>> bb=[[[]]] * 4 > >>> print(bb) > [[[]], [[]], [[]], [[]]] > >>> bb[0][0]='a' > >>> print(bb) > [['a'], ['a'], ['a'], ['a']] > > ? > > That's because the bb contains 4 references to the same list. Yes! What you post is I want. Thanks. From mail at nospam.com Thu Dec 3 22:22:22 2015 From: mail at nospam.com (Chris in Makati) Date: Fri, 04 Dec 2015 11:22:22 +0800 Subject: Is Microsoft Windows secretly downloading childporn to your computer ?! References: <519af$565d03d9$d47876e2$19871@news.ziggo.nl> Message-ID: On Thu, 3 Dec 2015 09:16:32 +0000 (UTC), Juha Nieminen wrote: >In comp.lang.c++ Chris in Makati wrote: >> On Wed, 2 Dec 2015 08:57:44 +0000 (UTC), Juha Nieminen >> wrote: >> >>>In comp.lang.c++ Steve Hayes wrote: >>>> You download things FROM a computer, you upload them TO a computer. >>> >>>It's a matter of perspective. If a hacker breaks into your computer and >>>starts a download from somewhere else into your computer, isn't the hacker >>>"downloading" things to your computer? >> >> Does it matter? As far as the law is concerned, it is possession of >> child porn that's illegal. How it got there is irrelevant. > >Most judiciary systems are not robots following a narrow set of instructions. >If they determine that it wasn't your fault, they will not punish the >innocent. > >Besides, how would they even know what's in your computer? If you do a Google search for you will find literally thousands of cases where raids have taken place and people have been found with this material on their computers. In many of these cases the authorities have traced the IP addresses of people whose computers have made connections to known sites that host child porn. It's no use trying to claim that a bot you weren't aware of downloaded it without your knowledge. If you could get off the hook that easily everybody who was interested in the stuff would deliberately install such a bot and use that as an excuse. From orgnut at yahoo.com Thu Dec 3 23:08:22 2015 From: orgnut at yahoo.com (Larry Hudson) Date: Thu, 3 Dec 2015 20:08:22 -0800 Subject: HELP PLEASE printing single characters! In-Reply-To: References: <75854ef5-fdd5-49da-88e8-27687b8d31c6@googlegroups.com> Message-ID: <5sednRMaaYkrjPzLnZ2dnUU7-bWdnZ2d@giganews.com> On 12/02/2015 04:08 PM, John Strick wrote: > On Wednesday, December 2, 2015 at 12:58:30 PM UTC-6, Dylan Riley wrote: >> hi all, >> I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get: >> ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"]. >> >> my code is: >> #Create a program that prints a list of words in random order. >> #The program should print all the words and not repeat any. >> >> import random >> >> LIST = ["blue ", "red ", "yellow ", "green ", "orange "] >> order = [] >> >> print("This game will print a random order of colours") >> print("The list is", LIST) >> input("press enter to start") >> >> >> >> while LIST != []: >> choice = random.choice(LIST) >> order += choice >> while choice in LIST: >> LIST.remove(choice) >> print(order) >> >> >> >> input("press enter to exit") >> >> thanks in advance guys > > You could just shuffle the list first, then loop through it. This will guarantee that each color is only used once. > Not quite. Only if the original list has no repetitions. My personal approach would be to use a set to eliminate the duplicates, convert back to a list and shuffle that. no_reps = list(set(LIST)) random.shuffle(no_reps) print(no_reps) # Or use loop to print one-per-line -=- Larry -=- From phamtony33 at gmail.com Thu Dec 3 23:19:23 2015 From: phamtony33 at gmail.com (phamtony33 at gmail.com) Date: Thu, 3 Dec 2015 20:19:23 -0800 (PST) Subject: How to bounce the ball forever around the screen Message-ID: from Tkinter import * window = Tk() canvas = Canvas(window, width=500, height=500, background="green") canvas.pack() def move_ball(speed_x, speed_y): box = canvas.bbox("ball") x1 = box[0] y1 = box[1] x2 = box[2] y2 = box[3] if x1 <= 0: speed_x = 0 speed_y = 0 canvas.move("ball", speed_x, speed_y) canvas.after(30, move_ball, speed_x, speed_y) canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball") move_ball(-10, 7) mainloop() where in the code should i change to make the ball bounce around forever. is it the x and y? From denismfmcmahon at gmail.com Thu Dec 3 23:19:24 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 4 Dec 2015 04:19:24 -0000 (UTC) Subject: Is there a way to set several list elements a same value with one line code References: Message-ID: On Thu, 03 Dec 2015 16:30:25 -0800, Robert wrote: > Hi, > > I remember that there is a way to set several list elements a same value > with > one line code. Excuse me, I don't remember the accurate syntax on the > code snippet. But the basic format looks like this. > > 1. There is a four-element list, such as: > bb=[[[]],[[]],[[]],[[]]] > 2. An assignment line is here: > bb[0]='a' > 3. Then, all 4 element of bb is set with the above value. > bb=[['a'],['a'],['a'],['a']] > > The above three line codes are what I guess (I forgot the original > tutorial > now). Do you remember there is such a list application? bb = [ for i in range()] will create bb as a list of size whatever elements each of which is eg: >>> bb = [ ['a'] for i in range(4)] >>> bb [['a'], ['a'], ['a'], ['a']] >>> bb = [ 0 for i in range(5)] >>> bb [0, 0, 0, 0, 0] >>> -- Denis McMahon, denismfmcmahon at gmail.com From __peter__ at web.de Fri Dec 4 03:09:05 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Dec 2015 09:09:05 +0100 Subject: How to bounce the ball forever around the screen References: Message-ID: phamtony33 at gmail.com wrote: > from Tkinter import * > window = Tk() > canvas = Canvas(window, width=500, height=500, background="green") > canvas.pack() > > def move_ball(speed_x, speed_y): > box = canvas.bbox("ball") > x1 = box[0] > y1 = box[1] > x2 = box[2] > y2 = box[3] > > if x1 <= 0: > speed_x = 0 > speed_y = 0 > > canvas.move("ball", speed_x, speed_y) > canvas.after(30, move_ball, speed_x, speed_y) > > canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball") > > move_ball(-10, 7) > > mainloop() > > where in the code should i change to make the ball bounce around forever. is it the x and y? When the ball hits a wall you have to "reflect" it; for a vertical wall speed_x has to change: if x1 <= 0: # ball hits left wall speed_x = -speed_x elif ... # ball hits right wall speed_x = -speed_x Can you come up with the correct check for the right wall? To try if this part works correctly temporarily change > move_ball(-10, 7) to move_ball(-10, 0) so that the ball only moves in horizontal direction. Once this works handle the vertical walls and speed_y the same way. From storchaka at gmail.com Fri Dec 4 03:34:42 2015 From: storchaka at gmail.com (Serhiy Storchaka) Date: Fri, 4 Dec 2015 10:34:42 +0200 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: On 04.12.15 00:26, Oscar Benjamin wrote: > On 3 Dec 2015 16:50, "Terry Reedy" wrote: >> fileinput is an ancient module that predates iterators (and generators) > and context managers. Since by 2.7 open files are both context managers and > line iterators, you can easily write your own multi-file line iteration > that does exactly what you want. At minimum: >> >> for file in files: >> with codecs.open(file, errors='ignore') as f >> # did not look up signature, >> for line in f: >> do_stuff(line) > > The above is fine but... > >> To make this reusable, wrap in 'def filelines(files):' and replace > 'do_stuff(line)' with 'yield line'. > > That doesn't work entirely correctly as you end up yielding from inside a > with statement. If the user of your generator function doesn't fully > consume the generator then whichever file is currently open is not > guaranteed to be closed. You can convert the generator to context manager and use it in the with statement to guarantee closing. with contextlib.closing(filelines(files)) as f: for line in f: ... From storchaka at gmail.com Fri Dec 4 03:42:16 2015 From: storchaka at gmail.com (Serhiy Storchaka) Date: Fri, 4 Dec 2015 10:42:16 +0200 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 02.12.15 11:28, Chris Angelico wrote: > On Wed, Dec 2, 2015 at 7:22 PM, Serhiy Storchaka wrote: >> On 01.12.15 03:00, Steven D'Aprano wrote: >>> I'm trying to understand why vars() exists. Does anyone use it? >> I use vars() exclusively for introspection in interactive environment. As >> well as dir() and help(). Sad that it doesn't work with __slots__. > Maybe the upshot of all this is a post to python-ideas recommending > that vars() grow support for __slots__ types? If it's most often used > interactively, this would make it more useful there, and it wouldn't > break backward compatibility unless there's some way that people are > depending on it raising an exception. It already was discussed few times. And there is even open issue for this: http://bugs.python.org/issue13290. From oscar.j.benjamin at gmail.com Fri Dec 4 04:00:32 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 4 Dec 2015 09:00:32 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? In-Reply-To: References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: On 4 Dec 2015 08:36, "Serhiy Storchaka" wrote: > > On 04.12.15 00:26, Oscar Benjamin wrote: >> >> On 3 Dec 2015 16:50, "Terry Reedy" wrote: >>> >>> fileinput is an ancient module that predates iterators (and generators) >> >> and context managers. Since by 2.7 open files are both context managers and >> line iterators, you can easily write your own multi-file line iteration >> that does exactly what you want. At minimum: >>> >>> >>> for file in files: >>> with codecs.open(file, errors='ignore') as f >>> # did not look up signature, >>> for line in f: >>> do_stuff(line) >> >> >> The above is fine but... >> >>> To make this reusable, wrap in 'def filelines(files):' and replace >> >> 'do_stuff(line)' with 'yield line'. >> >> That doesn't work entirely correctly as you end up yielding from inside a >> with statement. If the user of your generator function doesn't fully >> consume the generator then whichever file is currently open is not >> guaranteed to be closed. > > > You can convert the generator to context manager and use it in the with statement to guarantee closing. > > with contextlib.closing(filelines(files)) as f: > for line in f: > ... Or you can use fileinput which is designed to be exactly this kind of context manager and to be used in this way. Although fileinput is slightly awkward in defaulting to reading stdin. -- Oscar From nmcelwaine at gmail.com Fri Dec 4 06:26:59 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Fri, 4 Dec 2015 11:26:59 +0000 Subject: python 3.5.0rc1 problem opening IDLE in windows Message-ID: Dear python team since windows applied some updates last night to my windows 10 and windows 7 systems, I can't open anything with IDLE as I usually do. On windows 10 (64bit with 64bit python), I performed the installation repair procedure. * Edit with IDLE does not appear as an installed windows program. * when I open my usual shortcut to IDLE ( C:\Python\Python35\Lib\idlelib\idle.py) something briefly flashes on the screen *and immediately disappears.* * if I directly open a python program in windows, I get these options (as usual):- edit with IDLE (-> python launcher for windows console) edit with IDLE (-> edit with IDLE (64bit)) - which I always use, *nothing happens* Any ideas gratefully received!!! sincerely Nick "Mac" McElwaine From framstag at rus.uni-stuttgart.de Fri Dec 4 08:00:32 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Fri, 4 Dec 2015 13:00:32 +0000 (UTC) Subject: urllib2.urlopen() crashes on Windows 2008 Server References: Message-ID: Dennis Lee Bieber wrote: > >I have a Python2 program which runs fine on Windows 7, but > >crashes on Windows 2008 Server R2 64 bit: > > > >downloading http://fex.belwue.de/download/7za.exe > >Traceback (most recent call last): > > File "", line 1992, in > > File "", line 180, in main > > File "", line 329, in get_ID > > File "", line 1627, in check_7z > > File "C:\Software\Python\lib\urllib2.py", line 154, in urlopen > > File "C:\Software\Python\lib\urllib2.py", line 431, in open > > File "C:\Software\Python\lib\urllib2.py", line 449, in _open > > File "C:\Software\Python\lib\urllib2.py", line 409, in _call_chain > > File "C:\Software\Python\lib\urllib2.py", line 1227, in http_open > > File "C:\Software\Python\lib\urllib2.py", line 1200, in do_open > > File "C:\Software\Python\lib\httplib.py", line 1132, in getresponse > > File "C:\Software\Python\lib\httplib.py", line 485, in begin > > File "C:\Software\Python\lib\mimetools.py", line 25, in __init__ > > File "C:\Software\Python\lib\rfc822.py", line 108, in __init__ > > File "C:\Software\Python\lib\httplib.py", line 319, in readheaders > > File "C:\Software\Python\lib\socket.py", line 480, in readline > >error: [Errno 10054] Eine vorhandene Verbindung wurde vom Remotehost geschlossen > > > > Per MSDN: > """ > WSAECONNRESET > 10054 > > > > Connection reset by peer. > > An existing connection was forcibly closed by the remote host. This is not true. The server is under my control. Die client has terminated the connection (or a router between). How can I trap this within the python program? I see no exception. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From lac at openend.se Fri Dec 4 09:47:47 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 04 Dec 2015 15:47:47 +0100 Subject: python 3.5.0rc1 problem opening IDLE in windows In-Reply-To: References: Message-ID: <201512041447.tB4ElldX015624@fido.openend.se> In a message of Fri, 04 Dec 2015 11:26:59 +0000, Nicky Mac writes: >Dear python team >since windows applied some updates last night to my windows 10 and windows >7 systems, >I can't open anything with IDLE as I usually do. >On windows 10 (64bit with 64bit python), I performed the installation >repair procedure. >* Edit with IDLE does not appear as an installed windows program. >* when I open my usual shortcut to IDLE ( >C:\Python\Python35\Lib\idlelib\idle.py) > something briefly flashes on the screen *and immediately disappears.* >* if I directly open a python program in windows, I get these options (as >usual):- > edit with IDLE (-> python launcher for windows console) > edit with IDLE (-> edit with IDLE (64bit)) - which I always >use, *nothing >happens* > >Any ideas gratefully received!!! >sincerely >Nick "Mac" McElwaine Go to a console window and type python -m idlelib See if you get a useful traceback, and post it here. (If idle just works, tell us that, instead.) Laura Creighton From lac at openend.se Fri Dec 4 09:52:14 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 04 Dec 2015 15:52:14 +0100 Subject: problem In-Reply-To: References: Message-ID: <201512041452.tB4EqFTZ015967@fido.openend.se> In a message of Thu, 03 Dec 2015 21:25:53 +0200, Dylan Goodwin writes: >Every time I try and run python 3.5 it keeps coming up with modify, repair >or uninstall >-- >https://mail.python.org/mailman/listinfo/python-list What OS are you running? If windows XP, your problem is that your OS is too old. Python 3.5 is not supported. Stick with 3.4 or upgrade your OS. If something else, you need to install the available service packs. For instance, if you are running Windows 7, https://www.microsoft.com/en-us/download/details.aspx?id=5842 is where you get service pack 1. Laura Creighton From ian.g.kelly at gmail.com Fri Dec 4 10:41:39 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 4 Dec 2015 09:41:39 -0600 Subject: [Python-ideas] Missing Core Feature: + - * / | & do not call __getattr__ In-Reply-To: References: Message-ID: On Fri, Dec 4, 2015 at 7:20 AM, Stephan Sahm wrote: > Dear all, > > I just stumbled upon a very weird behaviour of python 2 and python 3. At > least I was not able to find a solution. > > The point is to dynamically define __add__, __or__ and so on via __getattr__ > (for example by deriving them from __iadd__ or similar in a generic way). > However this very intuitive idea is currently NOT POSSIBLE because * - * / & > | and so on just bypass this standard procedure. > > I found two stackoverflow contributions stating this: > http://stackoverflow.com/questions/11629287/python-how-to-forward-an-instances-method-call-to-its-attribute > http://stackoverflow.com/questions/33393474/lazy-evaluation-forward-operations-to-deferred-value > > Neither the mentioned posts, nor I myself can see any reason why this is the > way it is, nor how the operators are actually implemented to maybe bypass > this unintuitive behaviour. The cited reason is "speed optimizations": https://docs.python.org/3/reference/datamodel.html#special-method-lookup But there may be other reasons as well. __getattr__ and __getattribute__ are meant to implement *attribute* lookup. Special methods are best not regarded as attributes (although they can be looked up as such), but as implementation of class behavior. You'll note that special methods also aren't resolved in the instance dict, but only in the class dict; this is viewed as a matter of correctness, so that special methods work correctly on class objects (invoking the metaclass) as well as on instances. In some cases there may also be a chicken-and-egg problem; should Python call __getattribute__ in order to resolve the __getattribute__ method? From dfh at forestfield.co.uk Fri Dec 4 11:21:17 2015 From: dfh at forestfield.co.uk (dfh at forestfield.co.uk) Date: Fri, 4 Dec 2015 08:21:17 -0800 (PST) Subject: Frozen apps (py2exe, cx_freeze) built with Python 3.5 Message-ID: <94a5d971-ebd0-4385-b276-b33468f5497e@googlegroups.com> Python 3.5 will not run under Windows XP, but what about applications created using py2exe or cx_freeze under Windows 7, 8 or 10, is there any knowledge of whether they will run under XP? Regards, David Hughes Forestfield Software From ian.g.kelly at gmail.com Fri Dec 4 11:37:21 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 4 Dec 2015 10:37:21 -0600 Subject: Frozen apps (py2exe, cx_freeze) built with Python 3.5 In-Reply-To: <94a5d971-ebd0-4385-b276-b33468f5497e@googlegroups.com> References: <94a5d971-ebd0-4385-b276-b33468f5497e@googlegroups.com> Message-ID: On Fri, Dec 4, 2015 at 10:21 AM, dfh at forestfield.co.uk wrote: > Python 3.5 will not run under Windows XP, but what about applications created using py2exe or cx_freeze under Windows 7, 8 or 10, is there any knowledge of whether they will run under XP? I wouldn't expect them to. Those bundlers are just packaging up the Python binary, so they should have all the same problems. From zachary.ware+pylist at gmail.com Fri Dec 4 12:26:58 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 4 Dec 2015 11:26:58 -0600 Subject: Frozen apps (py2exe, cx_freeze) built with Python 3.5 In-Reply-To: References: <94a5d971-ebd0-4385-b276-b33468f5497e@googlegroups.com> Message-ID: On Fri, Dec 4, 2015 at 10:37 AM, Ian Kelly wrote: > On Fri, Dec 4, 2015 at 10:21 AM, dfh at forestfield.co.uk > wrote: >> Python 3.5 will not run under Windows XP, but what about applications created using py2exe or cx_freeze under Windows 7, 8 or 10, is there any knowledge of whether they will run under XP? > > I wouldn't expect them to. Those bundlers are just packaging up the > Python binary, so they should have all the same problems. I'll confirm that expectation. -- Zach From jsf80238 at gmail.com Fri Dec 4 12:38:43 2015 From: jsf80238 at gmail.com (Jason Friedman) Date: Fri, 4 Dec 2015 10:38:43 -0700 Subject: Exclude text within quotation marks and words beginning with a capital letter In-Reply-To: References: Message-ID: > > I am working on a program that is written in Python 2.7 to be compatible > with the POS tagger that I import from Pattern. The tagger identifies all > the nouns in a text. I need to exclude from the tagger any text that is > within quotation marks, and also any word that begins with an upper case > letter (including words at the beginning of sentences). > > Any advice on coding that would be gratefully received. Thanks. > Perhaps overkill, but wanted to make sure you knew about the Natural Language Toolkit: http://www.nltk.org/. From zarkeshali81 at gmail.com Fri Dec 4 13:02:03 2015 From: zarkeshali81 at gmail.com (Ali Zarkesh) Date: Fri, 4 Dec 2015 18:02:03 +0000 Subject: Problem in pip Message-ID: My pip can't download or upgrade anything I use python 3.5 (win 32) and my pip version is 7.1.2. The error message is this: Exception: Traceback (most recent call last): File "c:\program files\python 3.5\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) File "c:\program files\python 3.5\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, File "c:\program files\python 3.5\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs File "c:\program files\python 3.5\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) File "c:\program files\python 3.5\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files insolated=self.isolated, File "c:\program files\python 3.5\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python 3.5\lib\site-packages\pip\wheel.py", line 317, in clobber shutil.copyfile(srcfile, destfile) File "c:\program files\python 3.5\lib\shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: 'c:\program files\python 3.5\Lib\site-packages\PyWin32.chm' What do I do? From darcy at VybeNetworks.com Fri Dec 4 13:07:38 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Fri, 4 Dec 2015 13:07:38 -0500 Subject: Unicode failure Message-ID: <20151204130738.76313c43@imp> I thought that going to Python 3.4 would solve my Unicode issues but it seems I still don't understand this stuff. Here is my script. #! /usr/bin/python3 # -*- coding: UTF-8 -*- import sys print(sys.getdefaultencoding()) print(u"\N{TRADE MARK SIGN}") And here is my output. utf-8 Traceback (most recent call last): File "./g", line 5, in print(u"\N{TRADE MARK SIGN}") UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in position 0: ordinal not in range(128) What am I missing? TIA. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From zarkeshali81 at gmail.com Fri Dec 4 13:57:27 2015 From: zarkeshali81 at gmail.com (Ali Zarkesh) Date: Fri, 4 Dec 2015 18:57:27 +0000 Subject: problem fixed Message-ID: My problem fixed That was only about User Account Control From duncan at invalid.invalid Fri Dec 4 14:43:35 2015 From: duncan at invalid.invalid (duncan smith) Date: Fri, 4 Dec 2015 19:43:35 +0000 Subject: counting unique numpy subarrays Message-ID: Hello, I'm trying to find a computationally efficient way of identifying unique subarrays, counting them and returning an array containing only the unique subarrays and a corresponding 1D array of counts. The following code works, but is a bit slow. ############### from collections import Counter import numpy def bag_data(data): # data (a numpy array) is bagged along axis 0 # returns concatenated array and corresponding array of counts vec_shape = data.shape[1:] counts = Counter(tuple(arr.flatten()) for arr in data) data_out = numpy.zeros((len(counts),) + vec_shape) cnts = numpy.zeros((len(counts,))) for i, (tup, cnt) in enumerate(counts.iteritems()): data_out[i] = numpy.array(tup).reshape(vec_shape) cnts[i] = cnt return data_out, cnts ############### I've been looking through the numpy docs, but don't seem to be able to come up with a clean solution that avoids Python loops. TIA for any useful pointers. Cheers. Duncan From ian.g.kelly at gmail.com Fri Dec 4 17:07:26 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 4 Dec 2015 15:07:26 -0700 Subject: [Python-ideas] Using functools.lru_cache only on some arguments of a function In-Reply-To: References: Message-ID: On Fri, Dec 4, 2015 at 2:44 PM, Bill Winslow wrote: > This is a question I posed to reddit, with no real resolution: > https://www.reddit.com/r/learnpython/comments/3v75g4/using_functoolslru_cache_only_on_some_arguments/ > > The summary for people here is the following: > > Here's a pattern I'm using for my code: > > def deterministic_recursive_calculation(input, partial_state=None): > condition = do_some_calculations(input) > if condition: > return deterministic_recursive_calculation(reduced_input, > some_state) > > Basically, in calculating the results of the subproblem, the subproblem can > be calculated quicker by including/sharing some partial results from the > superproblem. (Calling the subproblem without the partial state still gives > the same result, but takes substantially longer.) > > I want to memoize this function for obvious reasons, but I need the > lru_cache to ignore the partial_state argument, for its value does not > affect the output, only the computation expense. > > Is there any reasonable way to do this? What form does the partial_state take? Would it be reasonable to design it with __eq__ and __hash__ methods so that each partial state (or a wrapper of it) is considered equal? From sjeik_appie at hotmail.com Fri Dec 4 17:36:52 2015 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 4 Dec 2015 22:36:52 +0000 Subject: counting unique numpy subarrays In-Reply-To: References: Message-ID: Hi (Sorry for topposting) numpy.ravel is faster than numpy.flatten (no copy) numpy.empty is faster than numpy.zeros numpy.fromiter might be useful to avoid the loop (just a hunch) Albert-Jan > From: duncan at invalid.invalid > Subject: counting unique numpy subarrays > Date: Fri, 4 Dec 2015 19:43:35 +0000 > To: python-list at python.org > > Hello, > I'm trying to find a computationally efficient way of identifying > unique subarrays, counting them and returning an array containing only > the unique subarrays and a corresponding 1D array of counts. The > following code works, but is a bit slow. > > ############### > > from collections import Counter > import numpy > > def bag_data(data): > # data (a numpy array) is bagged along axis 0 > # returns concatenated array and corresponding array of counts > vec_shape = data.shape[1:] > counts = Counter(tuple(arr.flatten()) for arr in data) > data_out = numpy.zeros((len(counts),) + vec_shape) > cnts = numpy.zeros((len(counts,))) > for i, (tup, cnt) in enumerate(counts.iteritems()): > data_out[i] = numpy.array(tup).reshape(vec_shape) > cnts[i] = cnt > return data_out, cnts > > ############### > > I've been looking through the numpy docs, but don't seem to be able to > come up with a clean solution that avoids Python loops. TIA for any > useful pointers. Cheers. > > Duncan > -- > https://mail.python.org/mailman/listinfo/python-list From zachary.ware+pylist at gmail.com Fri Dec 4 17:41:17 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 4 Dec 2015 16:41:17 -0600 Subject: Problem in pip In-Reply-To: References: Message-ID: On Fri, Dec 4, 2015 at 12:02 PM, Ali Zarkesh wrote: > My pip can't download or upgrade anything > I use python 3.5 (win 32) and my pip version is 7.1.2. > The error message is this: > > Exception: > Traceback (most recent call last): > ... > PermissionError: [Errno 13] Permission denied: 'c:\program files\python > 3.5\Lib\site-packages\PyWin32.chm' > > What do I do? It looks like you're trying to install in the global environment, which requires administrative privileges. You'll either need to do the above from an Administrative Command Prompt or create a virtual environment (py -3.5 -m venv ) and try it using the pip from the venv. Hope this helps, -- Zach From szaharcsuk at googlemail.com Fri Dec 4 17:44:53 2015 From: szaharcsuk at googlemail.com (Anna Szaharcsuk) Date: Fri, 4 Dec 2015 22:44:53 +0000 Subject: issues Message-ID: Hello there, I was trying to install PyCharm, but didn't worked and needed interpreter. the computer advised to install the python for windows. Can you help me, please, PyCharm stillnot working...allways gives a message for repair, after- the repair successful and again message for repair... Kind regards, Anna From sjeik_appie at hotmail.com Fri Dec 4 17:49:49 2015 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 4 Dec 2015 22:49:49 +0000 Subject: Unicode failure In-Reply-To: <20151204130738.76313c43@imp> References: <20151204130738.76313c43@imp> Message-ID: I think you need to use a raw unicode string, ur >>> unicodedata.name(ur'\u2122') 'TRADE MARK SIGN' > Date: Fri, 4 Dec 2015 13:07:38 -0500 > From: darcy at VybeNetworks.com > To: python-list at python.org > Subject: Unicode failure > > I thought that going to Python 3.4 would solve my Unicode issues but it > seems I still don't understand this stuff. Here is my script. > > #! /usr/bin/python3 > # -*- coding: UTF-8 -*- > import sys > print(sys.getdefaultencoding()) > print(u"\N{TRADE MARK SIGN}") > > And here is my output. > > utf-8 > Traceback (most recent call last): > File "./g", line 5, in > print(u"\N{TRADE MARK SIGN}") > UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in > position 0: ordinal not in range(128) > > What am I missing? > > TIA. > > -- > D'Arcy J.M. Cain > Vybe Networks Inc. > http://www.VybeNetworks.com/ > IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com > -- > https://mail.python.org/mailman/listinfo/python-list From oscar.j.benjamin at gmail.com Fri Dec 4 17:54:49 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 4 Dec 2015 22:54:49 +0000 Subject: Unicode failure In-Reply-To: <20151204130738.76313c43@imp> References: <20151204130738.76313c43@imp> Message-ID: On 4 Dec 2015 22:34, "D'Arcy J.M. Cain" wrote: > > I thought that going to Python 3.4 would solve my Unicode issues but it > seems I still don't understand this stuff. Here is my script. > > #! /usr/bin/python3 > # -*- coding: UTF-8 -*- > import sys > print(sys.getdefaultencoding()) > print(u"\N{TRADE MARK SIGN}") > > And here is my output. > > utf-8 > Traceback (most recent call last): > File "./g", line 5, in > print(u"\N{TRADE MARK SIGN}") > UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in > position 0: ordinal not in range(128) > > What am I missing? The important thing is not the default encoding but the encoding associated with stdout. Try printing sys.stdout.encoding to see what that is. It may depend what terminal you're trying to print out in. Are you using cmd.exe? If on Unix what's the value of LANG environment variable? -- Oscar From __peter__ at web.de Fri Dec 4 18:03:35 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Dec 2015 00:03:35 +0100 Subject: Unicode failure References: <20151204130738.76313c43@imp> Message-ID: D'Arcy J.M. Cain wrote: > I thought that going to Python 3.4 would solve my Unicode issues but it > seems I still don't understand this stuff. Here is my script. > > #! /usr/bin/python3 > # -*- coding: UTF-8 -*- > import sys > print(sys.getdefaultencoding()) > print(u"\N{TRADE MARK SIGN}") > > And here is my output. > > utf-8 > Traceback (most recent call last): > File "./g", line 5, in > print(u"\N{TRADE MARK SIGN}") > UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in > position 0: ordinal not in range(128) > > What am I missing? """The character encoding is platform-dependent. Under Windows, if the stream is interactive (that is, if its isatty() method returns True), the console codepage is used, otherwise the ANSI code page. Under other platforms, the locale encoding is used (see locale.getpreferredencoding()). """ https://docs.python.org/dev/library/sys.html#sys.stdout From __peter__ at web.de Fri Dec 4 18:06:38 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Dec 2015 00:06:38 +0100 Subject: counting unique numpy subarrays References: Message-ID: duncan smith wrote: > Hello, > I'm trying to find a computationally efficient way of identifying > unique subarrays, counting them and returning an array containing only > the unique subarrays and a corresponding 1D array of counts. The > following code works, but is a bit slow. > > ############### > > from collections import Counter > import numpy > > def bag_data(data): > # data (a numpy array) is bagged along axis 0 > # returns concatenated array and corresponding array of counts > vec_shape = data.shape[1:] > counts = Counter(tuple(arr.flatten()) for arr in data) > data_out = numpy.zeros((len(counts),) + vec_shape) > cnts = numpy.zeros((len(counts,))) > for i, (tup, cnt) in enumerate(counts.iteritems()): > data_out[i] = numpy.array(tup).reshape(vec_shape) > cnts[i] = cnt > return data_out, cnts > > ############### > > I've been looking through the numpy docs, but don't seem to be able to > come up with a clean solution that avoids Python loops. Me neither :( > TIA for any > useful pointers. Cheers. Here's what I have so far: def bag_data(data): counts = numpy.zeros(data.shape[0]) seen = {} for i, arr in enumerate(data): sarr = arr.tostring() if sarr in seen: counts[seen[sarr]] += 1 else: seen[sarr] = i counts[i] = 1 nz = counts != 0 return numpy.compress(nz, data, axis=0), numpy.compress(nz, counts) From v+python at g.nevcal.com Fri Dec 4 18:26:52 2015 From: v+python at g.nevcal.com (Glenn Linderman) Date: Fri, 4 Dec 2015 15:26:52 -0800 Subject: msvcr100.dll missing ... error started after Windows 10 update to 10586.17 Message-ID: <5662213C.60307@g.nevcal.com> My wife's 64-bit Win8 home machine has 32-bit Python 3.3 installed. Then it upgraded to Win 8.1. Then I upgraded it to Win 10. Then I upgraded it to Threshold 2. It gets regular automatic updates also, like the one last night to build 10586.17. That's the history. When she tried a python script today, it failed, with an error saying that MSVCR100.dll was missing. After a few false starts, like being surprised that the error happened when it worked yesterday, and that there was an MSVCR100.dll in %windir%\system32, doing a search for all MSVCR100.dll on her machine discovered quite a few in various application directories, but then also one in \windows.old\WINDOWS\SysWOW64, the light-bulb blinked on, I copied that one to the \python33 directory, and everything works. Why M$ chose to delete MSVCR100.dll from %windir%\SysWOW64 in the recent update is a mystery, however. So this is just a data point and warning and solution, not really an expectation that anyone will be able to explain M$. Glenn From tjreedy at udel.edu Fri Dec 4 18:28:22 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 4 Dec 2015 18:28:22 -0500 Subject: Unicode failure In-Reply-To: <20151204130738.76313c43@imp> References: <20151204130738.76313c43@imp> Message-ID: On 12/4/2015 1:07 PM, D'Arcy J.M. Cain wrote: > I thought that going to Python 3.4 would solve my Unicode issues Within Python itself, that should be mostly true. As soon as you send text to a display, the rules of the display device take over. > > #! /usr/bin/python3 > # -*- coding: UTF-8 -*- Redundant, as this is the default for 3.x > import sys > print(sys.getdefaultencoding()) > print(u"\N{TRADE MARK SIGN}") > > And here is my output. > > utf-8 > Traceback (most recent call last): > File "./g", line 5, in > print(u"\N{TRADE MARK SIGN}") > UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in > position 0: ordinal not in range(128) Tk widgets, and hence IDLE windows, will print any character from \u0000 to \uffff without raising, even if the result is blank or ?. Higher codepoints fail, but allowing the entire BMP is better than any Windows codepage. -- Terry Jan Reedy From duncan at invalid.invalid Fri Dec 4 19:13:53 2015 From: duncan at invalid.invalid (duncan smith) Date: Sat, 5 Dec 2015 00:13:53 +0000 Subject: counting unique numpy subarrays In-Reply-To: References: Message-ID: On 04/12/15 22:36, Albert-Jan Roskam wrote: > Hi > > (Sorry for topposting) > > numpy.ravel is faster than numpy.flatten (no copy) > numpy.empty is faster than numpy.zeros > numpy.fromiter might be useful to avoid the loop (just a hunch) > > Albert-Jan > Thanks, I'd forgotten the difference between numpy. flatten and numpy.ravel. I wasn't even aware of numpy.empty. Duncan From duncan at invalid.invalid Fri Dec 4 19:18:04 2015 From: duncan at invalid.invalid (duncan smith) Date: Sat, 5 Dec 2015 00:18:04 +0000 Subject: counting unique numpy subarrays In-Reply-To: References: Message-ID: <93q8y.177413$ij2.5605@fx08.iad> On 04/12/15 23:06, Peter Otten wrote: > duncan smith wrote: > >> Hello, >> I'm trying to find a computationally efficient way of identifying >> unique subarrays, counting them and returning an array containing only >> the unique subarrays and a corresponding 1D array of counts. The >> following code works, but is a bit slow. >> >> ############### >> >> from collections import Counter >> import numpy >> >> def bag_data(data): >> # data (a numpy array) is bagged along axis 0 >> # returns concatenated array and corresponding array of counts >> vec_shape = data.shape[1:] >> counts = Counter(tuple(arr.flatten()) for arr in data) >> data_out = numpy.zeros((len(counts),) + vec_shape) >> cnts = numpy.zeros((len(counts,))) >> for i, (tup, cnt) in enumerate(counts.iteritems()): >> data_out[i] = numpy.array(tup).reshape(vec_shape) >> cnts[i] = cnt >> return data_out, cnts >> >> ############### >> >> I've been looking through the numpy docs, but don't seem to be able to >> come up with a clean solution that avoids Python loops. > > Me neither :( > >> TIA for any >> useful pointers. Cheers. > > Here's what I have so far: > > def bag_data(data): > counts = numpy.zeros(data.shape[0]) > seen = {} > for i, arr in enumerate(data): > sarr = arr.tostring() > if sarr in seen: > counts[seen[sarr]] += 1 > else: > seen[sarr] = i > counts[i] = 1 > nz = counts != 0 > return numpy.compress(nz, data, axis=0), numpy.compress(nz, counts) > Three times as fast as what I had, and a bit cleaner. Excellent. Cheers. Duncan From random832 at fastmail.com Fri Dec 4 22:22:43 2015 From: random832 at fastmail.com (Random832) Date: Sat, 5 Dec 2015 03:22:43 +0000 (UTC) Subject: Unicode failure References: <20151204130738.76313c43@imp> Message-ID: On 2015-12-04, Terry Reedy wrote: > Tk widgets, and hence IDLE windows, will print any character from \u0000 > to \uffff without raising, even if the result is blank or ?. Higher > codepoints fail, but allowing the entire BMP is better than any Windows > codepage. Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. From darcy at VybeNetworks.com Fri Dec 4 23:15:47 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Fri, 4 Dec 2015 23:15:47 -0500 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: <20151204231547.2d7b24a1@imp> On Fri, 4 Dec 2015 22:49:49 +0000 Albert-Jan Roskam wrote: > I think you need to use a raw unicode string, ur > > >>> unicodedata.name(ur'\u2122') > 'TRADE MARK SIGN' That seems to work in 2.x but not 3.x. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From tjreedy at udel.edu Sat Dec 5 01:06:04 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Dec 2015 01:06:04 -0500 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: On 12/4/2015 10:22 PM, Random832 wrote: > On 2015-12-04, Terry Reedy wrote: >> Tk widgets, and hence IDLE windows, will print any character from \u0000 >> to \uffff without raising, even if the result is blank or ?. Higher >> codepoints fail, but allowing the entire BMP is better than any Windows >> codepage. > > Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. Test before you post. >>> for cp in 1200, 1201, 12000, 12001, 65000, 65001, 54936: print(chr(cp)) ? ? ? ? ? ? ? -- Terry Jan Reedy From darcy at VybeNetworks.com Sat Dec 5 01:08:27 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sat, 5 Dec 2015 01:08:27 -0500 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: <20151205010827.2a82c6bc@imp> On Fri, 4 Dec 2015 18:28:22 -0500 Terry Reedy wrote: > On 12/4/2015 1:07 PM, D'Arcy J.M. Cain wrote: > > I thought that going to Python 3.4 would solve my Unicode issues > > Within Python itself, that should be mostly true. As soon as you > send text to a display, the rules of the display device take over. OK but my display (xterm) can display those characters. I see it when I dump unicode text from my database. > > #! /usr/bin/python3 > > # -*- coding: UTF-8 -*- > > Redundant, as this is the default for 3.x I assumed so but belt and suspenders, right? > Tk widgets, and hence IDLE windows, will print any character from > \u0000 to \uffff without raising, even if the result is blank or ?. > Higher codepoints fail, but allowing the entire BMP is better than > any Windows codepage. Not sure I follow all this but to be clear, I am not using Tk, Idle or Windows. I guess I should have mentioned that I am on Unix but I thought that the hash-bang would have given that away. To be complete, I am running xterms on Xubuntu connected to NetBSD 7.0. The data is coming from a PostgreSQL 9.3.5 database. I am using a beta of PyGreSQL 5.0 (I am the lead developer for it) and I checked and the type returned is str, not bytes. The database encoding is UTF8. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From rosuav at gmail.com Sat Dec 5 01:10:40 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 5 Dec 2015 17:10:40 +1100 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: On Sat, Dec 5, 2015 at 5:06 PM, Terry Reedy wrote: > On 12/4/2015 10:22 PM, Random832 wrote: >> >> On 2015-12-04, Terry Reedy wrote: >>> >>> Tk widgets, and hence IDLE windows, will print any character from \u0000 >>> to \uffff without raising, even if the result is blank or ?. Higher >>> codepoints fail, but allowing the entire BMP is better than any Windows >>> codepage. >> >> >> Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. > > > Test before you post. > >>>> for cp in 1200, 1201, 12000, 12001, 65000, 65001, 54936: > print(chr(cp)) > > > ? > ? > ? > ? > ? > ? > ? Those numbers aren't codepoints, they're code pages. Specifically, they're UTF-16, UTF-32, UTF-8, and I'm not sure what 54936 is. ChrisA From tjreedy at udel.edu Sat Dec 5 01:12:30 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Dec 2015 01:12:30 -0500 Subject: Unicode failure In-Reply-To: <20151204231547.2d7b24a1@imp> References: <20151204130738.76313c43@imp> <20151204231547.2d7b24a1@imp> Message-ID: On 12/4/2015 11:15 PM, D'Arcy J.M. Cain wrote: > On Fri, 4 Dec 2015 22:49:49 +0000 > Albert-Jan Roskam wrote: >> I think you need to use a raw unicode string, ur Nope. The 'r' prefix does not disable unicode escapes. >>>>> unicodedata.name(ur'\u2122') >> 'TRADE MARK SIGN' If if did, the string above would have 6 chars instead of 1 and the above would not work. > That seems to work in 2.x but not 3.x. 'u' was restored in 3.3 as a do-nothing prefix, but the combination 'ur' was not. -- Terry Jan Reedy From auriocus at gmx.de Sat Dec 5 04:07:20 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 5 Dec 2015 10:07:20 +0100 Subject: msvcr100.dll missing ... error started after Windows 10 update to 10586.17 In-Reply-To: References: Message-ID: Am 05.12.15 um 00:26 schrieb Glenn Linderman: > My wife's 64-bit Win8 home machine has 32-bit Python 3.3 installed. > > Then it upgraded to Win 8.1. Then I upgraded it to Win 10. Then I > upgraded it to Threshold 2. It gets regular automatic updates also, like > the one last night to build 10586.17. > > That's the history. > > When she tried a python script today, it failed, with an error saying > that MSVCR100.dll was missing. > > After a few false starts, like being surprised that the error happened > when it worked yesterday, and that there was an MSVCR100.dll in > %windir%\system32, doing a search for all MSVCR100.dll on her machine > discovered quite a few in various application directories, but then also > one in \windows.old\WINDOWS\SysWOW64, the light-bulb blinked on, I > copied that one to the \python33 directory, and everything works. These MSVCR*DLL are a bit different from other DLLs. They constitute the runtime for programs compiled using Visual Studio 2010. Instead of mucking around with these files manually, you should install the "Redustributable Package" found here https://www.microsoft.com/en-us/download/details.aspx?id=14632 for 32bit or here https://www.microsoft.com/en-us/download/details.aspx?id=5555 for 64 bit. Both can be installed simultaneously to support 32bit and 64bit programs. There is also a "Visual Studio 2010 SP1" version - I'm not sure which one is correct. It depends on the version of the compiler that Python was built with. > Why M$ chose to delete MSVCR100.dll from %windir%\SysWOW64 in the recent > update is a mystery, however. Maybe the upgrade process didn't recognize it as part of the rediistributable, maybe it was not installed correctly. The MS recommended way for an installer is to package that "redistributable" and to launch it during the installation of the main program. > So this is just a data point and warning and solution, not really an > expectation that anyone will be able to explain M$. > > Glenn From oscar.j.benjamin at gmail.com Sat Dec 5 05:46:20 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 5 Dec 2015 10:46:20 +0000 Subject: Unicode failure In-Reply-To: <20151205010827.2a82c6bc@imp> References: <20151204130738.76313c43@imp> <20151205010827.2a82c6bc@imp> Message-ID: On 5 Dec 2015 06:10, "D'Arcy J.M. Cain" wrote: > > On Fri, 4 Dec 2015 18:28:22 -0500 > Terry Reedy wrote: > > On 12/4/2015 1:07 PM, D'Arcy J.M. Cain wrote: > > > I thought that going to Python 3.4 would solve my Unicode issues > > > > Within Python itself, that should be mostly true. As soon as you > > send text to a display, the rules of the display device take over. > > OK but my display (xterm) can display those characters. I see it when > I dump unicode text from my database. > > > > #! /usr/bin/python3 > > > # -*- coding: UTF-8 -*- > > > > Redundant, as this is the default for 3.x > > I assumed so but belt and suspenders, right? > > > Tk widgets, and hence IDLE windows, will print any character from > > \u0000 to \uffff without raising, even if the result is blank or ?. > > Higher codepoints fail, but allowing the entire BMP is better than > > any Windows codepage. > > Not sure I follow all this but to be clear, I am not using Tk, Idle or > Windows. I guess I should have mentioned that I am on Unix but I > thought that the hash-bang would have given that away. To be complete, > I am running xterms on Xubuntu connected to NetBSD 7.0. The data is > coming from a PostgreSQL 9.3.5 database. I am using a beta of PyGreSQL > 5.0 (I am the lead developer for it) and I checked and the type > returned is str, not bytes. The database encoding is UTF8. Yeah but the error you showed was from print trying to encode the string as ASCII. For some reason Python thinks that stdout is ASCII I think. So I repeat: what is SYS.stdout.encoding? If you're using xterm I think it will be derived from LANG. So what's LANG? -- Oscar From jfong at ms4.hinet.net Sat Dec 5 06:26:02 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sat, 5 Dec 2015 03:26:02 -0800 (PST) Subject: Python 3.4 + pyUSB 1.0 + libusb-win32 1.2.6.0, what happens? Message-ID: I am new to python. I had a USB HID device which behavior is that the host send a 64 bytes commands to it, after complete the execution of this commands it send back a 64 bytes status to the host, so the host can check the status and decide the next step. When I run it under Win7 with SwiftForth 3.5.9 (a Forth system) and libusb-win32 1.2.6.0, it performs well. But when I test it under the same PC with python 3.4, pyUSB 1.0 and libusb-win32 1.2.6.0, it performs a little strange. The status read back always fail at the first time (return zero length) and success at the second time. >>> dev.write(0x02, cmdBuf) 64 >>> dev.read(0x81, 64, 5000) array('B') # no data returned >>> dev.read(0x81, 64, 5000) array('B', [165, 0, ....]) # this one is correct, totally 64 bytes another "strange" thing is that I had a 5000 timeout in the read but I see no delay at the first read. It returns immediately. I suppose it should wait for 5 seconds long before it returns. Right? Any hint? Best Regards, Jach Fong From tony at vanderhoff.org Sat Dec 5 07:40:57 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 5 Dec 2015 12:40:57 +0000 Subject: increment/decrement operators Message-ID: Hi, I'm a relative newbie to python, and this NG, but it's certainly growing on me. One thing I'm missing is the increment/decrement operator from C, ie x++, and its ilk. Likewise x += y. is there any way of doing this in Python? TIA, Tony From robin.koch at t-online.de Sat Dec 5 07:56:47 2015 From: robin.koch at t-online.de (Robin Koch) Date: Sat, 5 Dec 2015 13:56:47 +0100 Subject: increment/decrement operators In-Reply-To: References: Message-ID: Am 05.12.2015 um 13:40 schrieb Tony van der Hoff: > Hi, > > I'm a relative newbie to python, and this NG, but it's certainly growing > on me. > > One thing I'm missing is the increment/decrement operator from C, ie > x++, and its ilk. Likewise x += y. > > is there any way of doing this in Python? Quick answer: x += y works. (Well, it should.) x++ doesn't. Long answer: I'm sure someone more experienced will come up with one shortly. :-) Until then I found this: http://stackoverflow.com/a/1485854 -- Robin Koch From eryksun at gmail.com Sat Dec 5 08:21:58 2015 From: eryksun at gmail.com (eryk sun) Date: Sat, 5 Dec 2015 07:21:58 -0600 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: On Sat, Dec 5, 2015 at 12:10 AM, Chris Angelico wrote: > On Sat, Dec 5, 2015 at 5:06 PM, Terry Reedy wrote: >> On 12/4/2015 10:22 PM, Random832 wrote: >>> >>> On 2015-12-04, Terry Reedy wrote: >>>> >>>> Tk widgets, and hence IDLE windows, will print any character from \u0000 >>>> to \uffff without raising, even if the result is blank or ?. Higher >>>> codepoints fail, but allowing the entire BMP is better than any Windows >>>> codepage. >>> >>> >>> Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. >> >> >> Test before you post. >> >>>>> for cp in 1200, 1201, 12000, 12001, 65000, 65001, 54936: >> print(chr(cp)) >> >> >> ? >> ? >> ? >> ? >> ? >> ? >> ? > > Those numbers aren't codepoints, they're code pages. Specifically, > they're UTF-16, UTF-32, UTF-8, and I'm not sure what 54936 is. Codepage 65000 is UTF-7. Codepage 54936 [1] is GB18030, the official character set of China. It's a UTF superset of GBK. For comparison, codepage 936 is a subset of GBK (it's missing 95 characters) plus the Euro symbol. [1]: https://msdn.microsoft.com/en-us/library/dd317756 From tony at vanderhoff.org Sat Dec 5 09:14:43 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 5 Dec 2015 14:14:43 +0000 Subject: increment/decrement operators In-Reply-To: References: Message-ID: On 05/12/15 12:56, Robin Koch wrote: > Am 05.12.2015 um 13:40 schrieb Tony van der Hoff: >> Hi, >> >> I'm a relative newbie to python, and this NG, but it's certainly growing >> on me. >> >> One thing I'm missing is the increment/decrement operator from C, ie >> x++, and its ilk. Likewise x += y. >> >> is there any way of doing this in Python? > > Quick answer: > > x += y works. (Well, it should.) > > x++ doesn't. > > Long answer: > > I'm sure someone more experienced will come up with one shortly. :-) > > Until then I found this: > http://stackoverflow.com/a/1485854 > Thanks for the link From darcy at VybeNetworks.com Sat Dec 5 09:41:15 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sat, 5 Dec 2015 09:41:15 -0500 Subject: increment/decrement operators In-Reply-To: References: Message-ID: <20151205094115.01751274@imp> On Sat, 5 Dec 2015 13:56:47 +0100 Robin Koch wrote: > x += y works. (Well, it should.) It does, even on objects other than numbers. >>> x = "abc" >>> y = "def" >>> x += y >>> x 'abcdef' > x++ doesn't. No but it's just a special case of the above. >>> x = 1 >>> x += 1 >>> x 2 -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From tjreedy at udel.edu Sat Dec 5 10:43:17 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Dec 2015 10:43:17 -0500 Subject: increment/decrement operators In-Reply-To: <20151205094115.01751274@imp> References: <20151205094115.01751274@imp> Message-ID: On 12/5/2015 9:41 AM, D'Arcy J.M. Cain wrote: > On Sat, 5 Dec 2015 13:56:47 +0100 > Robin Koch wrote: >> x += y works. (Well, it should.) > > It does, even on objects other than numbers. > >>>> x = "abc" >>>> y = "def" >>>> x += y >>>> x > 'abcdef' > >> x++ doesn't. > > No but it's just a special case of the above. > >>>> x = 1 >>>> x += 1 >>>> x > 2 Apple is removing the ++ and -- pre- and post- increment and decrement operators from Swift 3.0 as redundant with += 1. https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md The following section is a good summary of why they were never added to Python, and should not be. ''' Disadvantages of These Operators 1. These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language. 2. Their expressive advantage is minimal - x++ is not much shorter than x += 1. 3. Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model. 4. Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc. 5. Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand. 6. While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined. 7. These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc. 8. Having to support these could add complexity to the potential revised numerics model. Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?" ''' -- Terry Jan Reedy From amksh at mail.ru Sat Dec 5 11:22:41 2015 From: amksh at mail.ru (amksh at mail.ru) Date: Sat, 05 Dec 2015 22:22:41 +0600 Subject: Python 3.5 not work in Windows XP Message-ID: Installer: only 'Cancel' button visible on dialog. 'Install now...' and 'Customize...' work but invisible (also when deinstalling). After installing interpreter and launcher not runs (with message 'Access denied)' From bc at freeuk.com Sat Dec 5 12:18:35 2015 From: bc at freeuk.com (BartC) Date: Sat, 5 Dec 2015 17:18:35 +0000 Subject: increment/decrement operators In-Reply-To: References: <20151205094115.01751274@imp> Message-ID: On 05/12/2015 15:43, Terry Reedy wrote: > On 12/5/2015 9:41 AM, D'Arcy J.M. Cain wrote: >> On Sat, 5 Dec 2015 13:56:47 +0100 >> Robin Koch wrote: >>> x += y works. (Well, it should.) >> >> It does, even on objects other than numbers. >> >>>>> x = "abc" >>>>> y = "def" >>>>> x += y >>>>> x >> 'abcdef' >> >>> x++ doesn't. >> >> No but it's just a special case of the above. >> >>>>> x = 1 >>>>> x += 1 >>>>> x >> 2 > > Apple is removing the ++ and -- pre- and post- increment and decrement > operators from Swift 3.0 as redundant with += 1. > https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md > > > The following section is a good summary of why they were never added to > Python, and should not be. > > ''' > Disadvantages of These Operators > > 1. These operators increase the burden to learn Swift as a first > programming language - or any other case where you don't already know > these operators from a different language. > > 2. Their expressive advantage is minimal - x++ is not much shorter than > x += 1. The latter is not the same. Some of the differences are: * ++ and -- are often inside inside expressions and return values (unlike x+=1 in Python) * x++ and x-- return the /current/ value of x, unlike x+=1 even if it were to return a value; it would be the new value * x+=1 requires you to hard-code the value 1, but ++ is not necessarily stepping by 1. You can imagine ++ stepping something to its next value. However, if ++ and -- are only used as statements, then why not simply map them to x+=1? In Python, that would need to be x++ and x-- as ++x or --x have existing meanings. -- Bartc From darcy at VybeNetworks.com Sat Dec 5 13:14:43 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sat, 5 Dec 2015 13:14:43 -0500 Subject: Unicode failure (Solved) In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: <20151205131443.6fe0b00b@imp> On Fri, 4 Dec 2015 18:28:22 -0500 Terry Reedy wrote: > Tk widgets, and hence IDLE windows, will print any character from > \u0000 to \uffff without raising, even if the result is blank or ?. > Higher codepoints fail, but allowing the entire BMP is better than > any Windows codepage. Thanks to all. Following up on the various posts brought me to information that solved my problem. Basicall I added "export PYTHONIOENCODING=utf8" to my environment and "SetEnv PYTHONIOENCODING utf8" in my Apache config and now things are working as they should. Thanks all. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From pkpearson at nowhere.invalid Sat Dec 5 14:29:05 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 5 Dec 2015 19:29:05 GMT Subject: Question about split method References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: On Wed, 2 Dec 2015 14:44:30 -0600, Ian Kelly wrote: > On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: [snip] >> ss0="1, 2, 4, 8, 16".split(", ") [snip] > Try help(str.split) Or if, like me, you can't remember the magic word "str", ask: help("".split) and you know you're asking about the right "split". -- To email me, substitute nowhere->runbox, invalid->com. From Jason.Smith at qualityaddict.org Sat Dec 5 14:35:04 2015 From: Jason.Smith at qualityaddict.org (Jason Alan Smith) Date: Sat, 5 Dec 2015 13:35:04 -0600 Subject: Brief Code Review Please - Learning Python Message-ID: <12f0701d12f94$0ac62c80$20528580$@qualityaddict.org> Hello List Members, I am beginning to learn Python, and I've adapted some code from Google into the function below. I'm also looking at the PEP 8 style guide. I'd appreciate a brief code review so I can start this journey off on a solid foundation. :) * I've already changed my editor from tabs to 4 spaces. * I've also set my editor to alert me at 72 characters and don't exceed 79 characters. * I've named the function and variables with lower case, underscore separated, and meaningful words. * I've surrounded this function with two blank lines before and after. * I just recognized I need to pick a quote style and stick to it so I'll fix that (" " or ' '). * I'm not sure about the WidthAndHeight on lines 16 and 17 regarding capitalization. If I understand correctly a namedtuple is a class so the CapWords convention is correct. * Is how I've aligned the function arguments on lines 1-4 and 22-25 good style or \ is spreading these out onto fewer lines preferred? * Same question as right above but with the if tests on lines 5-8. * I've also used ( ) around the if tests, but I'm not sure if this is good Python style or not. 1 def measure_string(desired_text, 2 desired_font_family, 3 desired_font_size, 4 is_multi_lines): 5 if (desired_text != '') and \ 6 (desired_font_family != '') and \ 7 (desired_font_size != '') and \ 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): 9 with Image(filename='wizard:') as temp_image: 10 with Drawing() as measure: 11 measure.font_family = desired_font_family 12 measure.font_size = desired_font_size 13 measures = measure.get_font_metrics(temp_image, 14 desired_text, 15 multiline=is_multi_lines) 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") 17 width_and_height = WidthAndHeight(measures.text_width, \ 18 measures.text_height) 19 return width_and_height 20 21 22 print(measure_string("some text\na new line", 23 "Segoe UI", 24 40, 25 "True")) Any and all feedback is much appreciated. As I said, I'm just beginning to learn Python and want to start off with a solid foundation. Thank you to everyone in advance for your time and thoughts. Jason From pkpearson at nowhere.invalid Sat Dec 5 14:42:04 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 5 Dec 2015 19:42:04 GMT Subject: filter a list of strings References: Message-ID: On Thu, 3 Dec 2015 10:27:19 +0100, wrote: [snip] > I often saw constructions like this > x for x in y if ... > But I don't understand that combination of the Python keywords (for, > in, if) I allready know. It is to complex to imagine what there really > happen. Don't give up! List comprehensions are one of the coolest things in Python. Maybe this simple example will make it click for you: >>> [x**2 for x in [1,2,3,4] if x != 2] [1, 9, 16] -- To email me, substitute nowhere->runbox, invalid->com. From random832 at fastmail.com Sat Dec 5 14:44:34 2015 From: random832 at fastmail.com (Random832) Date: Sat, 5 Dec 2015 19:44:34 +0000 (UTC) Subject: Unicode failure References: <20151204130738.76313c43@imp> Message-ID: On 2015-12-05, Terry Reedy wrote: > On 12/4/2015 10:22 PM, Random832 wrote: >> Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. > > Test before you post. As someone else pointed out, I meant that as a list of codepages which support all Unicode codepoints, not a list of codepoints not supported by Tk's UCS-2. Sorry, I assumed everyone knew offhand that 65001 was UTF-8 and would infer that the rest were for other UTF encodings. From rxjwg98 at gmail.com Sat Dec 5 14:51:50 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 5 Dec 2015 11:51:50 -0800 (PST) Subject: Question about split method In-Reply-To: References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: On Saturday, December 5, 2015 at 2:29:28 PM UTC-5, Peter Pearson wrote: > On Wed, 2 Dec 2015 14:44:30 -0600, Ian Kelly wrote: > > On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: > [snip] > >> ss0="1, 2, 4, 8, 16".split(", ") > [snip] > > Try help(str.split) > > Or if, like me, you can't remember the magic word "str", ask: > > help("".split) > > and you know you're asking about the right "split". > > -- > To email me, substitute nowhere->runbox, invalid->com. Thanks for your smart method. From breamoreboy at yahoo.co.uk Sat Dec 5 15:27:00 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 5 Dec 2015 20:27:00 +0000 Subject: Question about split method In-Reply-To: References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: On 05/12/2015 19:51, Robert wrote: > On Saturday, December 5, 2015 at 2:29:28 PM UTC-5, Peter Pearson wrote: >> On Wed, 2 Dec 2015 14:44:30 -0600, Ian Kelly wrote: >>> On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: >> [snip] >>>> ss0="1, 2, 4, 8, 16".split(", ") >> [snip] >>> Try help(str.split) >> >> Or if, like me, you can't remember the magic word "str", ask: >> >> help("".split) >> >> and you know you're asking about the right "split". >> >> -- >> To email me, substitute nowhere->runbox, invalid->com. > > Thanks for your smart method. > The even smarter method is: help(''.split) as this saves you reaching for the shift key :) -- 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 Sat Dec 5 17:03:30 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Dec 2015 17:03:30 -0500 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: On 12/5/2015 2:44 PM, Random832 wrote: > On 2015-12-05, Terry Reedy wrote: >> On 12/4/2015 10:22 PM, Random832 wrote: >>> Well, any bar 1200, 1201, 12000, 12001, 65000, 65001, and 54936. >> >> Test before you post. > > As someone else pointed out, I meant that as a list of codepages > which support all Unicode codepoints, not a list of codepoints > not supported by Tk's UCS-2. Sorry, I assumed everyone knew > offhand that 65001 was UTF-8 So Microsoft claims, but it is not terribly useful. Currently, on my Win 10 system, 'chcp 65001' results in sys.stdout.encoding = 'cp65001', and for cp in 1200, 1201, 12000, 12001, 65000, 65001, 54936: print(chr(cp)) running without the usual exception. But of the above numbers mis-interpreted as codepoints, only 1200 and 1201 print anything other than a box with ?, whereas IDLE printed 3 other chars for 3 other assigned codepoints. If I change the console font to Lucida Console, which I use in IDLE, even chr(1200) gives a box. > and would infer that the rest were for other UTF encodings. After re-reading, I see how I might have inferred that. Anyway, the OP found the solution for his system. -- Terry Jan Reedy From python at lucidity.plus.com Sat Dec 5 17:20:03 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 5 Dec 2015 22:20:03 +0000 Subject: Question about split method In-Reply-To: References: <169982db-7285-484a-9a48-0d4a2ea7dea1@googlegroups.com> Message-ID: <56636313.9020802@lucidity.plus.com> On 05/12/15 20:27, Mark Lawrence wrote: > On 05/12/2015 19:51, Robert wrote: >> On Saturday, December 5, 2015 at 2:29:28 PM UTC-5, Peter Pearson wrote: >>> On Wed, 2 Dec 2015 14:44:30 -0600, Ian Kelly >>> wrote: >>>> On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote: >>> [snip] >>>>> ss0="1, 2, 4, 8, 16".split(", ") >>> [snip] >>>> Try help(str.split) >>> >>> Or if, like me, you can't remember the magic word "str", ask: >>> >>> help("".split) >>> >>> and you know you're asking about the right "split". >>> >>> -- >>> To email me, substitute nowhere->runbox, invalid->com. >> >> Thanks for your smart method. >> > > The even smarter method is: > > help(''.split) > > as this saves you reaching for the shift key :) ... except you're already pressing it for the open parenthesis ... ;) E. From benjamin at python.org Sat Dec 5 17:20:30 2015 From: benjamin at python.org (Benjamin Peterson) Date: Sat, 05 Dec 2015 14:20:30 -0800 Subject: [RELEASED] Python 2.7.11 Message-ID: <1449354030.2091510.459129289.32191B7B@webmail.messagingengine.com> Python 2.7.11, the latest bugfix release of the Python 2.7 series, is now available for download at https://www.python.org/downloads/release/python-2711/ Thank you as always to Steve Dower and Ned Deily, who build our binaries. Enjoy the rest of the year, Benjamin From eryksun at gmail.com Sat Dec 5 19:19:19 2015 From: eryksun at gmail.com (eryk sun) Date: Sat, 5 Dec 2015 18:19:19 -0600 Subject: Unicode failure In-Reply-To: References: <20151204130738.76313c43@imp> Message-ID: On Sat, Dec 5, 2015 at 4:03 PM, Terry Reedy wrote: > On 12/5/2015 2:44 PM, Random832 wrote: >> As someone else pointed out, I meant that as a list of codepages >> which support all Unicode codepoints, not a list of codepoints >> not supported by Tk's UCS-2. Sorry, I assumed everyone knew >> offhand that 65001 was UTF-8 > > So Microsoft claims, but it is not terribly useful. Using codepage 65001 is how one encodes/decodes UTF-8 using the Windows API, i.e. WideCharToMultiByte and MultiByteToWideChar. If you're just referring to the console, then I agree for the most part. The console, even in Windows 10, still has two major flaws when using UTF-8. The biggest problem is that non-ASCII input gets read as EOF (i.e. 0 bytes read) because of a bug in how conhost.exe (the process that hosts the console) converts its internal input buffer. Instead of dynamically determining how many characters to encode based on the current codepage, it assumes an N byte user buffer is a request for N characters, which obviously fails with non-ASCII UTF-8. What's worse is that it doesn't fail the call. It returns to the client that it successfully read 0 bytes.This causes Python's REPL to quit and input() to raise EOFError. The 2nd problem that still exists in Windows 10 is that the console doesn't save state across writes, so a 2-4 byte UTF-8 code sequence that gets split into 2 writes due to buffering gets displayed in the console as 2-4 replacement characters (i.e. U+FFFD). Most POSIX terminals don't suffer from this problem because they natively use 8-bit strings, whereas Windows transcodes to UTF-16. Prior to Windows 8, there's another annoying bug. WriteFile and WriteConsoleA return the number of wchar_t elements written instead of the number of bytes written. So a buffered writer will write successively smaller slices of the output buffer until the two numbers agree. You end up with a (potentially long) trail of garbage at the end of every write that contains non-ASCII characters. Since Windows doesn't allow UTF-8 as the system codepage (i.e. the [A]NSI API), it's probably only by accident that UTF-8 works in the console at all. Unicode works best (though not perfectly) via the console's wide-character API. The win-unicode-console package provides this functionality for Python 2 and 3. > Currently, on my Win 10 system, 'chcp 65001' results in > sys.stdout.encoding = 'cp65001', and > > for cp in 1200, 1201, 12000, 12001, 65000, 65001, 54936: > print(chr(cp)) > running without the usual exception. But of the above numbers > mis-interpreted as codepoints, only 1200 and 1201 print anything other than > a box with ?, whereas IDLE printed 3 other chars for 3 other assigned > codepoints. If I change the console font to Lucida Console, which I use in > IDLE, even chr(1200) gives a box. 65000 and 65001 aren't characters. Code points 12000, 12001 and 54936 are East-Asian characters: >>> from unicodedata import name, east_asian_width >>> for n in (12000, 12001, 54936): ... c = chr(n) ... print(n, east_asian_width(c), name(c)) ... 12000 W CJK RADICAL C-SIMPLIFIED EAT 12001 W CJK RADICAL HEAD 54936 W HANGUL SYLLABLE HOELS The console window can't mix narrow glyphs with wide glyphs. Its font rendering still has mostly the same limitations that it had when it debuted in Windows NT 3.1 (1993). To display wide CJK glyphs in the console, set the system locale to an East-Asian region and restart Windows (what a piece of... cake). The console also stores only one 16-bit wchar_t code per character cell, so a UTF-16 surrogate pair representing a non-BMP character (e.g. one of the popular emoji characters) displays as two rectangle glyphs. However, at least the code values are preserved when copied from the console to a window that displays UTF-16 text properly. Alternatively, use ConEmu [1] to hide the original console and display its contents in a window that handles text more flexibly. It also hacks the console API via DLL injection to work around bugs and provide Xterm emulation. [1]: http://conemu.github.io From df at see.replyto.invalid Sun Dec 6 04:06:38 2015 From: df at see.replyto.invalid (Dave Farrance) Date: Sun, 06 Dec 2015 09:06:38 +0000 Subject: Unicode failure References: Message-ID: <69u76b9spvoql5eeh4h2686pmhigfvmivv@4ax.com> "D'Arcy J.M. Cain" wrote: >... >utf-8 >Traceback (most recent call last): > File "./g", line 5, in > print(u"\N{TRADE MARK SIGN}") >UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in >position 0: ordinal not in range(128) I *presume* that you're using Linux since you've got a hashbang, so... You can *check* that it's the local environment that's the issue with the *test* of setting the PYTHONIOENCODING environment variable. But if that works, then it tells you must then fix the underlying environment's character encoding to give a permanent fix. $ PYTHONIOENCODING=UTF-8 python3 -c 'print(u"\u00A9")' ? $ PYTHONIOENCODING=ascii python3 -c 'print(u"\u00A9")' Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character '\xa9' in position 0: ordinal not in range(128) From df at see.replyto.invalid Sun Dec 6 04:16:54 2015 From: df at see.replyto.invalid (Dave Farrance) Date: Sun, 06 Dec 2015 09:16:54 +0000 Subject: Unicode failure References: <69u76b9spvoql5eeh4h2686pmhigfvmivv@4ax.com> Message-ID: I was taking it for granted that you knew how to set environment variables, but just in case you don't: In the shell, (are you using BASH?), put this: export PYTHONIOENCODING=UTF-8 ...then run your script. Remember that this is *not* a permanent fix. From breamoreboy at yahoo.co.uk Sun Dec 6 04:34:23 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 6 Dec 2015 09:34:23 +0000 Subject: Unicode failure In-Reply-To: <69u76b9spvoql5eeh4h2686pmhigfvmivv@4ax.com> References: <69u76b9spvoql5eeh4h2686pmhigfvmivv@4ax.com> Message-ID: On 06/12/2015 09:06, Dave Farrance wrote: > "D'Arcy J.M. Cain" wrote: > >> ... >> utf-8 >> Traceback (most recent call last): >> File "./g", line 5, in >> print(u"\N{TRADE MARK SIGN}") >> UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in >> position 0: ordinal not in range(128) > > I *presume* that you're using Linux since you've got a hashbang, so... > Not really a good presumption as the hashbang has been used in Python scripts on Windows ever since "PEP 397 -- Python launcher for Windows", see https://www.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 framstag at rus.uni-stuttgart.de Sun Dec 6 04:38:04 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Sun, 6 Dec 2015 09:38:04 +0000 (UTC) Subject: urllib2.urlopen() crashes on Windows 2008 Server References: Message-ID: Dennis Lee Bieber wrote: > >> Connection reset by peer. > >> > >> An existing connection was forcibly closed by the remote host. > > > >This is not true. > >The server is under my control. Die client has terminated the connection > >(or a router between). > The odds are still good that something on the server is configured to > not make a clean shutdown of TCP connections (a router should not be > involved as the TCP connection is from client IP to server IP, regardless > of intervening MAC Ethernet routing). The RST is coming from the server. No. The server does not reset the connection. It is the router/firewall. > >How can I trap this within the python program? > >I see no exception. > > It's a socket error > > https://docs.python.org/2/library/socket.html > """ > > exception socket.error Ok, I have now: try: req = urllib.Request(szurl) req.add_header('User-Agent',useragent) u = urllib.urlopen(req) except urllib.URLError as e: die('cannot get %s - %s' % (szurl,e.reason)) except urllib.HTTPError as e: die('cannot get %s - server reply: %d %s' % (szurl,e.code,e.reason)) except (IOError,httplib.BadStatusLine,httplib.HTTPException): die('cannot get %s - connection reset by router or firewall' % szurl) except socket.error as msg: die('cannot get %s - %s' % (szurl,msg)) -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From df at see.replyto.invalid Sun Dec 6 04:46:30 2015 From: df at see.replyto.invalid (Dave Farrance) Date: Sun, 06 Dec 2015 09:46:30 +0000 Subject: Unicode failure (Solved) References: <20151204130738.76313c43@imp> Message-ID: <3b086b5dqv2do8gnhi09dthei54i6jir2n@4ax.com> "D'Arcy J.M. Cain" wrote: >On Fri, 4 Dec 2015 18:28:22 -0500 >Terry Reedy wrote: >> Tk widgets, and hence IDLE windows, will print any character from >> \u0000 to \uffff without raising, even if the result is blank or ?. >> Higher codepoints fail, but allowing the entire BMP is better than >> any Windows codepage. > >Thanks to all. Following up on the various posts brought me to >information that solved my problem. Basicall I added "export >PYTHONIOENCODING=utf8" to my environment and "SetEnv PYTHONIOENCODING >utf8" in my Apache config and now things are working as they should. > >Thanks all. Hmmm. I hadn't seen this post before replying to the original because my newsreader put this post in a later thread because: (a) The subject header was changed (b) The reference header is for a post that's not present in Usenet That raises another question. I'm seeing a number of broken threads because people reply to posts that are not present in Usenet. It's not just my main news-server because my newreader can gather posts from several Usenet servers and those posts are nowhere on Usenet. Case in point: The post by Terry Reedy quoted above, reference . I presume that it's on the list server even though it's not on Usenet. Anybody know what's going on? From jamesg2001 at hotmail.co.uk Sun Dec 6 10:48:18 2015 From: jamesg2001 at hotmail.co.uk (James Gilliver) Date: Sun, 6 Dec 2015 15:48:18 +0000 Subject: Issue Message-ID: Hi! I have recently installed Python 3.5.0 but cannot open the application! Could you help me resolve this issue? Thanks,James From Jason.Smith at qualityaddict.org Sun Dec 6 12:01:33 2015 From: Jason.Smith at qualityaddict.org (Jason Alan Smith) Date: Sun, 6 Dec 2015 11:01:33 -0600 Subject: Brief Code Review Please - Learning Python Message-ID: <12f5d01d13047$c2c97950$485c6bf0$@qualityaddict.org> Hello List Members, I am beginning to learn Python, and I've adapted some code from Google into the function below. I'm also looking at the PEP 8 style guide. I'd appreciate a brief code review so I can start this journey off on a solid foundation. :) * I've already changed my editor from tabs to 4 spaces. * I've also set my editor to alert me at 72 characters and don't exceed 79 characters. * I've named the function and variables with lower case, underscore separated, and meaningful words. * I've surrounded this function with two blank lines before and after. * I just recognized I need to pick a quote style and stick to it so I'll fix that (" " or ' '). * I'm not sure about the WidthAndHeight on lines 16 and 17 regarding capitalization. If I understand correctly a namedtuple is a class so the CapWords convention is correct. * Is how I've aligned the function arguments on lines 1-4 and 22-25 good style or \ is spreading these out onto fewer lines preferred? * Same question as right above but with the if tests on lines 5-8. * I've also used ( ) around the if tests, but I'm not sure if this is good Python style or not. 1 def measure_string(desired_text, 2 desired_font_family, 3 desired_font_size, 4 is_multi_lines): 5 if (desired_text != '') and \ 6 (desired_font_family != '') and \ 7 (desired_font_size != '') and \ 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): 9 with Image(filename='wizard:') as temp_image: 10 with Drawing() as measure: 11 measure.font_family = desired_font_family 12 measure.font_size = desired_font_size 13 measures = measure.get_font_metrics(temp_image, 14 desired_text, 15 multiline=is_multi_lines) 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") 17 width_and_height = WidthAndHeight(measures.text_width, \ 18 measures.text_height) 19 return width_and_height 20 21 22 print(measure_string("some text\na new line", 23 "Segoe UI", 24 40, 25 "True")) Any and all feedback is much appreciated. As I said, I'm just beginning to learn Python and want to start off with a solid foundation. Thank you to everyone in advance for your time and thoughts. Jason From qualityaddictorg at gmail.com Sun Dec 6 12:21:07 2015 From: qualityaddictorg at gmail.com (qualityaddictorg at gmail.com) Date: Sun, 6 Dec 2015 09:21:07 -0800 (PST) Subject: Brief Code Review Please - Learning Python Message-ID: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> [Note: Tried sending this twice to the Python-List mail list but I never saw it come through to the list.] Hello everyone, I am beginning to learn Python, and I've adapted some code from Google into the function below. I'm also looking at the PEP 8 style guide. I'd appreciate a brief code review so I can start this journey off on a solid foundation. :) * I've already changed my editor from tabs to 4 spaces. * I've also set my editor to alert me at 72 characters and don't exceed 79 characters. * I've named the function and variables with lower case, underscore separated, and meaningful words. * I've surrounded this function with two blank lines before and after. * I just recognized I need to pick a quote style and stick to it so I'll fix that (" " or ' '). * I'm not sure about the WidthAndHeight on lines 16 and 17 regarding capitalization. If I understand correctly a namedtuple is a class so the CapWords convention is correct. * Is how I've aligned the function arguments on lines 1-4 and 22-25 good style or \ is spreading these out onto fewer lines preferred? * Same question as right above but with the if tests on lines 5-8. * I've also used ( ) around the if tests, but I'm not sure if this is good Python style or not. 1 def measure_string(desired_text, 2 desired_font_family, 3 desired_font_size, 4 is_multi_lines): 5 if (desired_text != '') and \ 6 (desired_font_family != '') and \ 7 (desired_font_size != '') and \ 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): 9 with Image(filename='wizard:') as temp_image: 10 with Drawing() as measure: 11 measure.font_family = desired_font_family 12 measure.font_size = desired_font_size 13 measures = measure.get_font_metrics(temp_image, 14 desired_text, 15 multiline=is_multi_lines) 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") 17 width_and_height = WidthAndHeight(measures.text_width, \ 18 measures.text_height) 19 return width_and_height 20 21 22 print(measure_string("some text\na new line", 23 "Segoe UI", 24 40, 25 "True")) Any and all feedback is much appreciated. As I said, I'm just beginning to learn Python and want to start off with a solid foundation. Thank you to everyone in advance for your time and thoughts. Jason From joel.goldstick at gmail.com Sun Dec 6 12:34:31 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 6 Dec 2015 12:34:31 -0500 Subject: Brief Code Review Please - Learning Python In-Reply-To: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> References: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> Message-ID: On Sun, Dec 6, 2015 at 12:21 PM, wrote: > [Note: Tried sending this twice to the Python-List mail list but I never > saw it come through to the list.] > > Hello everyone, > > I am beginning to learn Python, and I've adapted some code from Google > into the function below. I'm also looking at the PEP 8 style guide. I'd > appreciate a brief code review so I can start this journey off on a solid > foundation. :) > > * I've already changed my editor from tabs to 4 spaces. > * I've also set my editor to alert me at 72 characters and don't > exceed 79 characters. > * I've named the function and variables with lower case, underscore > separated, and meaningful words. > * I've surrounded this function with two blank lines before and after. > * I just recognized I need to pick a quote style and stick to it so > I'll fix that (" " or ' '). > * I'm not sure about the WidthAndHeight on lines 16 and 17 regarding > capitalization. > You don't need the parens. If you feel it is easier to understand with them, they won't hurt > If I understand correctly a namedtuple is a class so the CapWords > convention is correct. > * Is how I've aligned the function arguments on lines 1-4 and 22-25 > good style or \ > is spreading these out onto fewer lines preferred? > If the parameters fit on one line, I think that is more common > * Same question as right above but with the if tests on lines 5-8. > * I've also used ( ) around the if tests, but I'm not sure if this is > good Python style or not. > > 1 def measure_string(desired_text, > 2 desired_font_family, > 3 desired_font_size, > 4 is_multi_lines): > 5 if (desired_text != '') and \ > 6 (desired_font_family != '') and \ > 7 (desired_font_size != '') and \ > 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): > The above test will always be True. Look up what is considered True in Python, and what is False. I imagine you don't want quotes around True and False. Any string will == True > 9 with Image(filename='wizard:') as temp_image: > 10 with Drawing() as measure: > 11 measure.font_family = desired_font_family > 12 measure.font_size = desired_font_size > 13 measures = measure.get_font_metrics(temp_image, > 14 desired_text, > 15 > multiline=is_multi_lines) > No need to set multiline = ... when is_multiline is already defined > 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") > 17 width_and_height = WidthAndHeight(measures.text_width, \ > 18 measures.text_height) > 19 return width_and_height > 20 > 21 > 22 print(measure_string("some text\na new line", > 23 "Segoe UI", > 24 40, > 25 "True")) > > Any and all feedback is much appreciated. As I said, I'm just beginning > to learn Python and want to start off with a solid foundation. Thank you > to everyone in advance for your time and thoughts. > > Jason > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From rosuav at gmail.com Sun Dec 6 12:49:15 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 7 Dec 2015 04:49:15 +1100 Subject: Brief Code Review Please - Learning Python In-Reply-To: References: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> Message-ID: On Mon, Dec 7, 2015 at 4:34 AM, Joel Goldstick wrote: >> 5 if (desired_text != '') and \ >> 6 (desired_font_family != '') and \ >> 7 (desired_font_size != '') and \ >> 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): >> > > The above test will always be True. Look up what is considered True in > Python, and what is False. I imagine you don't want quotes around True and > False. Any string will == True Not sure what you mean by this. If you're talking about boolification, then an empty string counts as false, but that's not what's happening here. It's checking that the string be equal to one of two other strings - and Python behaves exactly the way any sane person would expect, and this condition is true only if the string is exactly equal to either "True" or "False". But I think this line of code should be unnecessary. It's guarding the entire body of the function in a way that implies that failing this condition is an error - but if there is such an error, the function quietly returns None. Instead, I would go for a "fail-and-bail" model: def measure_string(text, font_family, font_size, multiline): if not text: raise ValueError("Cannot measure empty string") if not font_family: raise ValueError("No font family specified") if multiline not in ("True", "False"): raise ValueError("Must specify 'True' or 'False' for multiline flag") ... body of function here ... (Incidentally, it's quite un-Pythonic to use "True" and "False" as parameters; if the function you're calling requires this, it might be worth papering over that by having *your* function take the bools True and False, and converting to the strings on the inside.) > 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") You're creating a brand new namedtuple type every time you enter this function. That's expensive and messy. I would recommend either (a) constructing one "Dimension" type, outside the function, and using that every time; or (b) returning a regular tuple of width,height without the names. The convention of width preceding height (or x preceding y, more generally) is sufficiently widespread that it's unlikely to confuse people. ChrisA From __peter__ at web.de Sun Dec 6 13:14:11 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 Dec 2015 19:14:11 +0100 Subject: Brief Code Review Please - Learning Python References: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> Message-ID: qualityaddictorg at gmail.com wrote: > [Note: Tried sending this twice to the Python-List mail list but I never > [saw it come through to the list.] > > Hello everyone, > > I am beginning to learn Python, and I've adapted some code from Google > into the function below. I'm also looking at the PEP 8 style guide. > I'd appreciate a brief code review so I can start this journey off on > a solid foundation. :) > > * I've already changed my editor from tabs to 4 spaces. > * I've also set my editor to alert me at 72 characters and don't > exceed 79 characters. * I've named the function and variables with > lower case, underscore separated, and meaningful words. * I've > surrounded this function with two blank lines before and after. * I > just recognized I need to pick a quote style and stick to it so I'll > fix that (" " or ' '). * I'm not sure about the WidthAndHeight on > lines 16 and 17 regarding capitalization. > If I understand correctly a namedtuple is a class so the CapWords > convention is correct. > * Is how I've aligned the function arguments on lines 1-4 and 22-25 > good style or \ > is spreading these out onto fewer lines preferred? > * Same question as right above but with the if tests on lines 5-8. > * I've also used ( ) around the if tests, but I'm not sure if this is > good Python style or not. > > 1 def measure_string(desired_text, > 2 desired_font_family, > 3 desired_font_size, > 4 is_multi_lines): > 5 if (desired_text != '') and \ > 6 (desired_font_family != '') and \ > 7 (desired_font_size != '') and \ > 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): > 9 with Image(filename='wizard:') as temp_image: > 10 with Drawing() as measure: > 11 measure.font_family = desired_font_family > 12 measure.font_size = desired_font_size > 13 measures = measure.get_font_metrics(temp_image, > 14 desired_text, > 15 > multiline=is_multi_lines) > 16 WidthAndHeight = namedtuple("WidthAndHeight", "Width Height") > 17 width_and_height = WidthAndHeight(measures.text_width, \ > 18 measures.text_height) > 19 return width_and_height > 20 > 21 > 22 print(measure_string("some text\na new line", > 23 "Segoe UI", > 24 40, > 25 "True")) > > Any and all feedback is much appreciated. As I said, I'm just beginning > to learn Python and want to start off with a solid foundation. Thank you > to everyone in advance for your time and thoughts. > > Jason Use short variable names - the "desired_" prefix does not carry much information. Avoid unrelated but similar names: measure or measures -- what's what? Use consistent names. This is a bit tricky, but I would prefer multiline over is_multi_lines because the underlying library uses the former. Use the right datatype: multiline should be boolean, i. e. True or False, not "True" or "False". Provide defaults if possible: if the multiline argument is missing you can scan the text for "\n" and set the flag accordingly Prefer parens for line continuations (a and b) over backslashes a and \ b Move code that only should be executed once from the function to the global namespace: the namedtuple definition should be on the module level. Use qualified names if you are referring library code: wand.drawing.Drawing instead of just Drawing. Avoid spurious checks, but if you do argument validation fail noisyly, i. e. "wrong": def f(fontname): if is_valid(fontname): return meaningful_result() # implicitly return None "correct": class InvalidFontname(Exception): pass def f(fontname): if not is_valid(fontname): raise InvalidFontname(fontname) return meaningful_result() With changes along these lines your code might become from collections import namedtuple import wand.drawing import wand.image Extent = namedtuple("Extent", "width height") def get_text_extent( text, font_family, font_size, multiline=None): """Determine width and heights for `text`. """ if multiline is None: multiline = "\n" in text with wand.image.Image(filename='wizard:') as image: with wand.drawing.Drawing() as measure: measure.font_family = font_family measure.font_size = font_size metrics = measure.get_font_metrics( image, text, multiline=multiline) return Extent( width=metrics.text_width, height=metrics.text_height) if __name__ == "__main__": print( get_text_extent( "some text\na new line", "Segoe UI", 40)) From lac at openend.se Sun Dec 6 15:32:14 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 06 Dec 2015 21:32:14 +0100 Subject: Python 3.5 not work in Windows XP In-Reply-To: References: Message-ID: <201512062032.tB6KWErG019818@fido.openend.se> In a message of Sat, 05 Dec 2015 22:22:41 +0600, amksh at mail.ru writes: >Installer: only 'Cancel' button visible on dialog. 'Install now...' and >'Customize...' work but invisible (also when deinstalling). > >After installing interpreter and launcher not runs (with message 'Access >denied)' Yes, when 3.5.1 we will make that a lot clearer. Windows XP is not supported for 3.5 (and later). Either stick with 3.4 or upgrade your OS to something more recent. Laura Creighton From lac at openend.se Sun Dec 6 15:32:58 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 06 Dec 2015 21:32:58 +0100 Subject: issues In-Reply-To: References: Message-ID: <201512062032.tB6KWwRU019907@fido.openend.se> In a message of Fri, 04 Dec 2015 22:44:53 +0000, Anna Szaharcsuk via Python-lis t writes: >Hello there, > >I was trying to install PyCharm, but didn't worked and needed interpreter. >the computer advised to install the python for windows. > >Can you help me, please, PyCharm stillnot working...allways gives a message >for repair, after- the repair successful and again message for repair... > > >Kind regards, >Anna What OS version do you have? Laura From lac at openend.se Sun Dec 6 15:33:47 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 06 Dec 2015 21:33:47 +0100 Subject: Issue In-Reply-To: References: Message-ID: <201512062033.tB6KXlQf020020@fido.openend.se> In a message of Sun, 06 Dec 2015 15:48:18 +0000, James Gilliver writes: >Hi! >I have recently installed Python 3.5.0 but cannot open the application! Could you help me resolve this issue? >Thanks,James > >-- >https://mail.python.org/mailman/listinfo/python-list What OS version are you running. What happens when you try to open the application? Laura From python at mrabarnett.plus.com Sun Dec 6 15:33:48 2015 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 6 Dec 2015 20:33:48 +0000 Subject: issues In-Reply-To: References: Message-ID: <56649BAC.1000600@mrabarnett.plus.com> On 2015-12-04 22:44, Anna Szaharcsuk via Python-list wrote: > Hello there, > > I was trying to install PyCharm, but didn't worked and needed interpreter. > the computer advised to install the python for windows. > > Can you help me, please, PyCharm stillnot working...allways gives a message > for repair, after- the repair successful and again message for repair... > > > Kind regards, > Anna > Are you trying to use Python 3.5 on Windows XP? That won't work. XP is a very old version that Python 3.5 doesn't support. Either use Python 3.4 or update Windows to a more recent version. From random832 at fastmail.com Sun Dec 6 15:36:50 2015 From: random832 at fastmail.com (Random832) Date: Sun, 06 Dec 2015 15:36:50 -0500 Subject: Unicode failure References: <69u76b9spvoql5eeh4h2686pmhigfvmivv@4ax.com> Message-ID: Mark Lawrence writes: > On 06/12/2015 09:06, Dave Farrance wrote: >> "D'Arcy J.M. Cain" wrote: >>> utf-8 >>> Traceback (most recent call last): >>> File "./g", line 5, in >>> print(u"\N{TRADE MARK SIGN}") >>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in >>> position 0: ordinal not in range(128) >> >> I *presume* that you're using Linux since you've got a hashbang, so... > > Not really a good presumption as the hashbang has been used in Python > scripts on Windows ever since "PEP 397 -- Python launcher for > Windows", see https://www.python.org/dev/peps/pep-0397/ However, on windows it would typically be codepage 437, 850, or the like, and the error message would call it a 'charmap' codec. The 'ascii' codec error is associated with being in a UNIX environment with an unset (or "C" or "POSIX") locale. From jr at pyxus.co.uk Sun Dec 6 15:44:03 2015 From: jr at pyxus.co.uk (John Robinson) Date: Sun, 6 Dec 2015 20:44:03 -0000 Subject: install issue Message-ID: <001e01d13066$da2cc6a0$8e8653e0$@pyxus.co.uk> When I run the installer (python-3.5.0.exe [win32]) I see this: There seems to be "hidden" buttons as clicking in the middle of this dialog box does continue the process. However, when complete, and I start python, I get an error saying its not a valid win32 application. So, I uninstalled, and there is the same issue with the un-installer - I have to click random places in the dialog box to "find" the uninstall button, that is not shown. (plus AVG shows this as the Heri virus - and, yes, I did disable AVG while attempting the installation.) Win xp, SP3, AMD Phenom, 1100, 8gb (dual boot with win7) Rgds From random832 at fastmail.com Sun Dec 6 15:51:54 2015 From: random832 at fastmail.com (Random832) Date: Sun, 06 Dec 2015 15:51:54 -0500 Subject: Message-IDs on Usenet gateway References: <20151204130738.76313c43@imp> <3b086b5dqv2do8gnhi09dthei54i6jir2n@4ax.com> Message-ID: Dave Farrance writes: > That raises another question. I'm seeing a number of broken threads > because people reply to posts that are not present in Usenet. It's not > just my main news-server because my newreader can gather posts from > several Usenet servers and those posts are nowhere on Usenet. > > Case in point: The post by Terry Reedy quoted above, reference > . I presume that it's on the list server > even though it's not on Usenet. Anybody know what's going on? Something weird is going on. On google groups, this message has a different Message-ID: At first glance, it might look like Gmane is rewriting the Message-IDs, but the "gmane" ID seems authentic: It appears in the reply link in the online mailing list archive, and on the message in my own mailbox (I use Gmane now, but didn't bother with unsubscribing, particularly since my Email provider's search functionality is better.) This means the Usenet gateway (i.e. the "real" one, that goes to comp.lang.python) is rewriting the Message-Id. I've had the same problem in the other direction (Reference headers for the "mailman" Message-IDs breaking threading for me), and I'm glad that this prompted me to investigate properly, since before today I'd always assumed it was a Gmane problem. Who is in charge of the usenet gateway? From lac at openend.se Sun Dec 6 17:52:32 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 06 Dec 2015 23:52:32 +0100 Subject: Message-IDs on Usenet gateway In-Reply-To: References: <20151204130738.76313c43@imp> <3b086b5dqv2do8gnhi09dthei54i6jir2n@4ax.com> Message-ID: <201512062252.tB6MqWdp029656@fido.openend.se> In a message of Sun, 06 Dec 2015 15:51:54 -0500, Random832 writes: >Something weird is going on. On google groups, this message has >a different Message-ID: > I think it is this problem. Start here. https://mail.python.org/pipermail/mailman-developers/2015-November/025225.html Laura From steve at pearwood.info Sun Dec 6 19:16:07 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 07 Dec 2015 11:16:07 +1100 Subject: Issue References: Message-ID: <5664cfc9$0$1583$c3e8da3$5496439d@news.astraweb.com> On Mon, 7 Dec 2015 02:48 am, James Gilliver wrote: > Hi! > I have recently installed Python 3.5.0 but cannot open the application! > Could you help me resolve this issue? Thanks,James Yes, we can help you resolve the issue! You'll have to give us a bit more information, as we're not really mind-readers. Start with what operating system you are running, and what happens when you try to run the application. Is there an error message? What does it say? If there's no error message, describe what you did, and what happened. Be *precise* and *detailed*. The more vague you are, the less we can help. Oh, I can make one guess... if you're using Windows XP, I'm afraid that Python 3.5 is not supported. You'll have to either downgrade to Python 3.4, or upgrade to Windows 7 or higher, or another operating system. -- Steven From lalith at kohoku.lk Sun Dec 6 19:32:37 2015 From: lalith at kohoku.lk (lalith) Date: Mon, 07 Dec 2015 00:32:37 +0000 Subject: Packages installing problem Message-ID: Dear sir. I was using Python2.7 and i move to Python3.5. I face big trouble with installing software packages, i need in my development. Lalith From nonami.ayo at gmail.com Sun Dec 6 20:37:15 2015 From: nonami.ayo at gmail.com (nonami) Date: Mon, 7 Dec 2015 02:37:15 +0100 Subject: Problems using celery and pyelasticsearch Message-ID: <5664E2CB.9010104@gmail.com> Hi, I create a task that uses this function def get_jobs(specialization, yoe): try: key = "SpecAlert-" if len(specialization): key += '-'.join(map(str, specialization)) if yoe is not None: key += '-yoe'.join(yoe) jobs = memcache_client.get(key) if not jobs: spec_param = {'terms': {'jobs.specialization.id': specialization}} if yoe is not None: if len(yoe) == 2: yoe_param = {'range': {'jobs.experience': {'gte': yoe[0], 'lte': yoe[1]}}} elif int(yoe[0]): yoe_param = {'range': {'jobs.experience': {'gte': yoe[0]}}} else: yoe_param = {'term': {'jobs.experience': yoe[0]}} query_bool = {'must': [{'range': {'jobs.deadline': {'gt': str(date.today() + timedelta(days=1))}}}]} query_bool['must_not'] = [{'term': {'jobs.job_level': JOB_LEVEL_VOC}}] if specialization: query_bool['must'].append(spec_param) if yoe: query_bool['must'].append(yoe_param) es = config.get_es_connection() es_config = config.config['elasticsearch'] # print({'query': {'bool': query_bool}}) try: # Tasks sometimes hang here result = es.search(index=es_config['job_index'], doc_type=es_config['job_type'], body={'query': {'bool': query_bool}}) jobs = [] for j in result['hits']['hits']: jobs.append(j['_source']) except ElasticsearchException as esc: print(esc) jobs = [] if jobs: memcache_client.set(key, jobs, 3600) except Exception as e: jobs = [] print(e) return jobs I find that the celery worker often stops executing tasks. After tests and debugging I in that this NEVER happens when I take out this line(s): result = es.search(index=es_config['job_index'], doc_type=es_config['job_type'], body={'query': {'bool': query_bool}}) This line also does not raise any Exceptions Does anyone have any idea what could be going on or how I can further inspect running tasks. N.B celery worker is started with loglevel=debug flag but does not output any useful info as regards the problem. Thanks From lac at openend.se Sun Dec 6 20:50:25 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 07 Dec 2015 02:50:25 +0100 Subject: Problems using celery and pyelasticsearch In-Reply-To: <5664E2CB.9010104@gmail.com> References: <5664E2CB.9010104@gmail.com> Message-ID: <201512070150.tB71oP7W010189@fido.openend.se> In a message of Mon, 07 Dec 2015 02:37:15 +0100, nonami writes: >Does anyone have any idea what could be going on or how I can further >inspect running tasks. Not sure this will help, but it might ... https://www.caktusgroup.com/blog/2013/10/30/using-strace-debug-stuck-celery-tasks/ Laura From larry at hastings.org Mon Dec 7 00:06:46 2015 From: larry at hastings.org (Larry Hastings) Date: Sun, 6 Dec 2015 21:06:46 -0800 Subject: [RELEASED] Python 3.5.1 and 3.4.4rc1 are now available Message-ID: <566513E6.9050108@hastings.org> On behalf of the Python development community and the Python 3.4 and 3.5 release teams, I'm pleased to announce the simultaneous availability of Python 3.5.1 and Python 3.4.4rc1. As point releases, both have many incremental improvements over their predecessor releases. You can find Python 3.5.1 here: https://www.python.org/downloads/release/python-351/ And you can find Python 3.4.4rc1 here: https://www.python.org/downloads/release/python-344rc1/ Python 2.7.11 shipped today too, so it's a Python release-day hat trick! Happy computing, //arry/ From iverson.zhou at gmail.com Mon Dec 7 03:03:34 2015 From: iverson.zhou at gmail.com (iverson.zhou at gmail.com) Date: Mon, 7 Dec 2015 00:03:34 -0800 (PST) Subject: Help with stale exception Python Message-ID: <99840119-b7c2-4171-b2f8-7c600c85bd87@googlegroups.com> I'm new to Python and programming. Been learning it for 3 weeks now but have had lot of obstacles along the way. I found some of your insights very useful as a starter but I have come across many more complicated challenges that aren't very intuitive. For example,I'm trying to scrap this web(via university library (fully access) so it is a proxy) using selenium (because it is very heavily java script driven). There is a button which allows user to navigate to the next page of company and my script go and find the elements of interest from each page write to a csv and then click to the next page and do it recursively. I have a couple of problems need some help with. Firstly the element that I'm really interested is only company website(which isn't always there) but when it is there the location of the element can change all the time(see http://pasteboard.co/2GOHkbAD.png and http://pasteboard.co/2GOK2NBT.png) depending on the number of elements in the parent level. I'm using driver.find_elements_by_xpath("//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]") hoping to capture all information(e.g. phone,email,website) and then do some cleansing later on However, it appears not all the web elements are captured using this method and write to csv from each page. Some pages were written to the file but some were missing. I couldn't figure it out why. A second problem which is a more complicate and have been driving me nuts was the the DOM changes as a result of web content changes and elements are destroyed and/maybe being recreated after driver.find_element_by_id('detail-pagination-next-btn').click() I have tried uncountable number of methods (e.g. explicit, implicit wait) but the stale error still persists as it seems to stays stale as long as it is staled. Have anyone come up with a solution to this and what is the best way to deal with DOM tree changes. Much appreciated for your help. My code is attached: with open('C:/Python34/email.csv','w') as f: z=csv.writer(f, delimiter='\t',lineterminator = '\n',) while True: row = [] for link in driver.find_elements_by_xpath("//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"): try: row.append(str(link.text)) z.writerow(link.text) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]/span'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.presence_of_all_elements_located((By.XPATH,"//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"))) time.sleep(10) c=driver.find_element_by_id('detail-pagination-next-btn') WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]/span'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.presence_of_all_elements_located((By.XPATH,"//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"))) c.click() time.sleep(10) continue except StaleElementReferenceException as e: c=driver.find_element_by_id('detail-pagination-next-btn') for link in driver.find_elements_by_xpath("//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"): row.append(str(link.text)) z.writerow(link.text) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]/span'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.presence_of_all_elements_located((By.XPATH,"//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"))) time.sleep(10) c=driver.find_element_by_id('detail-pagination-next-btn') WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]/span'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="detail-pagination-next-btn"]'))) WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.ID,'detail-pagination-next-btn'))) WebDriverWait(driver, 50).until(EC.presence_of_all_elements_located((By.XPATH,"//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"))) c.click() time.sleep(10) much appreciated Iverson From oscar.j.benjamin at gmail.com Mon Dec 7 05:48:35 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 07 Dec 2015 10:48:35 +0000 Subject: Unicode failure In-Reply-To: References: Message-ID: On Sun, 6 Dec 2015 at 23:11 Quivis wrote: > On Fri, 04 Dec 2015 13:07:38 -0500, D'Arcy J.M. Cain wrote: > > > I thought that going to Python 3.4 would solve my Unicode issues but it > > seems I still don't understand this stuff. Here is my script. > > > > #! /usr/bin/python3 # -*- coding: UTF-8 -*- > > import sys print(sys.getdefaultencoding()) > > print(u"\N{TRADE MARK SIGN}") > > > > And here is my output. > > > > utf-8 Traceback (most recent call last): > > File "./g", line 5, in > > print(u"\N{TRADE MARK SIGN}") > > UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in > > position 0: ordinal not in range(128) > > Hmmmm, interesting: > > Python 2.7.3 (default, Jun 22 2015, 19:43:34) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> print sys.getdefaultencoding() > ascii > >>> print u'\N{TRADE MARK SIGN}' > ? > > sys.getdefaultencoding() returns the default encoding used when opening a file if an encoding is not explicitly given in the open call. What matters here is the encoding associated with stdout which is sys.stdout.encoding. $ python2.7 -c 'import sys; print(sys.stdout.encoding); print(u"\u2122")' UTF-8 ? $ LANG=C python2.7 -c 'import sys; print(sys.stdout.encoding); print(u"\u2122")' ANSI_X3.4-1968 Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 0: ordinal not in range(128) -- Oscar From jorge.conrado at cptec.inpe.br Mon Dec 7 07:51:10 2015 From: jorge.conrado at cptec.inpe.br (jorge.conrado at cptec.inpe.br) Date: Mon, 07 Dec 2015 10:51:10 -0200 Subject: define the area plot Message-ID: Hi, I'm changing from the IDL to PYTHON. I would like know how can I define the size of the window plot in Python. On IDL I define the size of area plot by: window,1,xsize=1000,ysize=1000 It is possible define the size of the window before my data is plotted. Conrado From hawkowl at atleastfornow.net Mon Dec 7 08:06:41 2015 From: hawkowl at atleastfornow.net (Amber "Hawkie" Brown) Date: Mon, 7 Dec 2015 21:06:41 +0800 Subject: Twisted 15.4 was the last release to support Python 2.6; or: a HawkOwl Can't Words Situation Message-ID: Hi everyone! It's been brought to my attention that I misworded something in the release notes and it slipped through the cracks. In the NEWS I said: > This is the last Twisted release where Python 2.6 is supported, on any platform. However, I meant that this is the first Twisted release to drop 2.6 support wholesale, preventing import on this platform. Twisted 15.4 will still operate, so if you have Python 2.6 deployment requirements, bracket the maximum to 15.4 on that platform by using an if statement in your setup.py, and `Twisted >=*minreq*,<=15.4; python_version < '2.7'` under requires_dist in your setup.cfg, where minreq is the minimum required Twisted. Sorry for the inconvenience! - Amber "HawkOwl" Brown Twisted Release Manager -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 455 bytes Desc: Message signed with OpenPGP using GPGMail URL: From a24061 at ducksburg.com Mon Dec 7 09:46:58 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Mon, 07 Dec 2015 14:46:58 +0000 Subject: getting fileinput to do errors='ignore' or 'replace'? References: <8336jcxi2m.ln2@news.ducksburg.com> Message-ID: <2oigjcx5nh.ln2@news.ducksburg.com> On 2015-12-04, Oscar Benjamin wrote: > Or you can use fileinput which is designed to be exactly this kind of > context manager and to be used in this way. Although fileinput is slightly > awkward in defaulting to reading stdin. That default is what I specifically like about fileinput --- it's a normal way for command-line tools to work: $ sort file0 file1 file2 >sorted.txt $ generate_junk | sort >sorted_junk.txt -- $2.95! PLATE O' SHRIMP Luncheon Special From a24061 at ducksburg.com Mon Dec 7 09:57:27 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Mon, 07 Dec 2015 14:57:27 +0000 Subject: writing an email.message.Message in UTF-8 Message-ID: I'm trying to write an instance of email.message.Message, whose body contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 again.) reply = email.message.Message() reply.set_charset('utf-8') ... # set various headers reply.set_payload('\n'.join(body_lines) + '\n') ... outfile = codecs.open(outfilename, 'w', encoding='utf-8', errors='ignore') outfile.write(reply.as_string()) outfile.close() Then reply.as_string() barfs a UnicodeDecodeError. I look in the documentation, which says the generator is better. So I replace the outfile.write(...) line with the following: g = email.generator.Generator(outfile, mangle_from_=False) g.flatten(reply) which still barfs a UnicodeDecodeError. Looking closer at the first error, I see that the exception was in g.flatten(...) already & thrown up to reply.as_string(). How can I force the thing to do UTF-8 output? Thanks. -- $2.95! PLATE O' SHRIMP Luncheon Special From a24061 at ducksburg.com Mon Dec 7 10:21:40 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Mon, 07 Dec 2015 15:21:40 +0000 Subject: writing an email.message.Message in UTF-8 References: Message-ID: <4pkgjcxr0j.ln2@news.ducksburg.com> On 2015-12-07, Adam Funk wrote: > I'm trying to write an instance of email.message.Message, whose body > contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 > again.) > > reply = email.message.Message() > reply.set_charset('utf-8') > ... # set various headers > reply.set_payload('\n'.join(body_lines) + '\n') I've also tried changing that to reply.set_payload('\n'.join(body_lines) + '\n', 'utf-8') but I get the same error on output. > ... > outfile = codecs.open(outfilename, 'w', encoding='utf-8', errors='ignore') > outfile.write(reply.as_string()) > outfile.close() > > Then reply.as_string() barfs a UnicodeDecodeError. I look in the > documentation, which says the generator is better. So I replace the > outfile.write(...) line with the following: > > g = email.generator.Generator(outfile, mangle_from_=False) > g.flatten(reply) > > which still barfs a UnicodeDecodeError. Looking closer at the first > error, I see that the exception was in g.flatten(...) already & thrown > up to reply.as_string(). How can I force the thing to do UTF-8 > output? > > Thanks. > > -- Cats don't have friends. They have co-conspirators. http://www.gocomics.com/getfuzzy/2015/05/31 From lac at openend.se Mon Dec 7 10:29:13 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 07 Dec 2015 16:29:13 +0100 Subject: define the area plot In-Reply-To: References: Message-ID: <201512071529.tB7FTDZP001429@fido.openend.se> In a message of Mon, 07 Dec 2015 10:51:10 -0200, jorge.conrado at cptec.inpe.br wr ites: > > >Hi, > >I'm changing from the IDL to PYTHON. I would like know how can I define >the size of the window plot in Python. On IDL I define the size of area >plot by: > > >window,1,xsize=1000,ysize=1000 > > >It is possible define the size of the window before my data is plotted. > > >Conrado What package are you using to plot with? Laura From lac at openend.se Mon Dec 7 10:42:41 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 07 Dec 2015 16:42:41 +0100 Subject: install issue In-Reply-To: <001e01d13066$da2cc6a0$8e8653e0$@pyxus.co.uk> References: <001e01d13066$da2cc6a0$8e8653e0$@pyxus.co.uk> Message-ID: <201512071542.tB7FgfHf002540@fido.openend.se> In a message of Sun, 06 Dec 2015 20:44:03 +0000, "John Robinson" writes: >When I run the installer (python-3.5.0.exe [win32]) I see this: > > > > > > > >There seems to be "hidden" buttons as clicking in the middle of this dialog >box does continue the process. > >However, when complete, and I start python, I get an error saying its not a >valid win32 application. > >So, I uninstalled, and there is the same issue with the un-installer - I >have to click random places in the dialog box to "find" the uninstall >button, that is not shown. > > > >(plus AVG shows this as the Heri virus - and, yes, I did disable AVG while >attempting the installation.) > >Win xp, SP3, AMD Phenom, 1100, 8gb (dual boot with win7) > > > >Rgds AVG, like most antivirus software, gets tons and tons of false positives. Regardless of weirdnesses in the installer, your real problem is that 3.5 and later does not run on XP, period. The new Python 3.5.1 released yesterday was supposed to be able to detect your XP, and tell you that you needed to upgrade your OS in order to run 3.5.1 Looks like things are still not working perfectly on that front, but that's the problem. You need to either stick with 3.4 or upgrade your OS. Laura Creighton From lac at openend.se Mon Dec 7 10:51:19 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 07 Dec 2015 16:51:19 +0100 Subject: Packages installing problem In-Reply-To: References: Message-ID: <201512071551.tB7FpJMn003110@fido.openend.se> In a message of Mon, 07 Dec 2015 00:32:37 +0000, lalith writes: >Dear sir. > >I was using Python2.7 and i move to Python3.5. >I face big trouble with installing software packages, i need in my >development. > >Lalith >-- >https://mail.python.org/mailman/listinfo/python-list Do you want to install your packages system-wide? Try py -3.5 -m install Do you want to install your python packages in a virtual environment? Start reading here: https://docs.python.org/3/library/venv.html If you sometimes want a python 2.7 virtual env you cannot get it with venv. You will have to use the older virtualenv. https://virtualenv.readthedocs.org/en/latest/ Laura From mediratta at gmail.com Mon Dec 7 12:15:44 2015 From: mediratta at gmail.com (Anupam Mediratta) Date: Mon, 7 Dec 2015 22:45:44 +0530 Subject: python 3.5: upgrading smart_open package Message-ID: Hello, I have to use python 3.5 in my use case and one of the packages I use (gensim), in turn uses smart_open (https://github.com/piskvorky/smart_open/) smart_open depends on boto and boto fails on my machine running ubuntu 15.10. So in order for me to be able to run gensim, I need to be able to migrate smart_open from boto to boto3 (boto3 works fine with python 3 and ubuntu 15.10). There is an open github issue: https://github.com/piskvorky/smart_open/issues/43 I am not sure how to go about doing this migration. If someone has any directions or guidelines I will appreciate. Thanks From tjreedy at udel.edu Mon Dec 7 12:40:56 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Dec 2015 12:40:56 -0500 Subject: writing an email.message.Message in UTF-8 In-Reply-To: References: Message-ID: On 12/7/2015 9:57 AM, Adam Funk wrote: > I'm trying to write an instance of email.message.Message, whose body > contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 > again.) The email package was rewritten for, I believe, 3.3. I believe it should handle unicode email encoded as utf-8 more easily. -- Terry Jan Reedy From lac at openend.se Mon Dec 7 12:47:52 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 07 Dec 2015 18:47:52 +0100 Subject: python 3.5: upgrading smart_open package In-Reply-To: References: Message-ID: <201512071747.tB7HlqeH011414@fido.openend.se> In a message of Mon, 07 Dec 2015 22:45:44 +0530, Anupam Mediratta writes: >Hello, > >I have to use python 3.5 in my use case and one of the packages I use >(gensim), in turn uses smart_open (https://github.com/piskvorky/smart_open/) > >smart_open depends on boto and boto fails on my machine running ubuntu >15.10. > >So in order for me to be able to run gensim, I need to be able to migrate >smart_open from boto to boto3 (boto3 works fine with python 3 and ubuntu >15.10). > >There is an open github issue: >https://github.com/piskvorky/smart_open/issues/43 > >I am not sure how to go about doing this migration. If someone has any >directions or guidelines I will appreciate. > >Thanks You have a bad problem. https://github.com/piskvorky/smart_open/labels/help%20wanted is the other name of https://github.com/piskvorky/smart_open/issues/43 This issue is because the author of smart_open wishes very badly to move to boto3, but hasn't, because he wants help with something. Thus you cannot migrate until he does. You should send mail to the author, which I looked up for you and you can find here. http://radimrehurek.com/contact/ Tell him that you want smart_open to work with boto3, and that you want to help making that happen. Then see what he says is needed and see if that is something you can do. Laura From tjreedy at udel.edu Mon Dec 7 12:50:39 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Dec 2015 12:50:39 -0500 Subject: python 3.5: upgrading smart_open package In-Reply-To: References: Message-ID: On 12/7/2015 12:15 PM, Anupam Mediratta wrote: > Hello, > > I have to use python 3.5 in my use case and one of the packages I use > (gensim), in turn uses smart_open (https://github.com/piskvorky/smart_open/) > > smart_open depends on boto and boto fails on my machine running ubuntu > 15.10. > > So in order for me to be able to run gensim, I need to be able to migrate > smart_open from boto to boto3 (boto3 works fine with python 3 and ubuntu > 15.10). > > There is an open github issue: > https://github.com/piskvorky/smart_open/issues/43 > > I am not sure how to go about doing this migration. If someone has any > directions or guidelines I will appreciate. Is boto3 installed and imported as 'boto' or 'boto3'? If the former, just install boto3 (into site-packages/boto) and 'import boto' in smart_open will just work. This would be the same in installing pillow as a drop in replacement for PIL, since pillow is installed in a directory named 'PIL'. If the latter, change the import statement. Any other changes would depend on boto3 having a different api from boto. -- Terry Jan Reedy From tony at vanderhoff.org Mon Dec 7 13:10:10 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Mon, 7 Dec 2015 18:10:10 +0000 Subject: Accessing container's methods Message-ID: Hi, I have a class A, containing embedded embedded classes, which need to access methods from A. . A highly contrived example, where I'm setting up an outer class in a Has-a relationship, containing a number of Actors. The inner class needs to access a method of the outer class; here the method get_name. I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; that would raise all sorts of other problems. Can anyone please advise me on how to achieve this magic? # define the outer class class Monty: def __init__( self, names ): self.actors = [] i = 0 for n in names: self.actors.append( Actor( n, i ) ) i += 1 # here is a case for python supporting post-increment! def count_actors( self ): return len( self.actors ) def list_actors( self ): h=[] for n in self.actors: h.append( n.get_name() ) return h # define the inner class class Actor: def __init__ ( self, name, id ): self.name = name self.id = id def get_name( self ): # and here lies the problem; # AttributeError: Actor instance has no attribute 'count_actors' # how do I access the method in the enclosing class txt = "I'm Actor {} Number {} of {}".\ format( self.name, self.id, self.count_actors() ) # this works, of course #txt = "I'm Actor \"{}\"; Number {}. ".\ format( self.name, self.id ) return txt if __name__ == '__main__': o = Monty( ["Cleese", "Idle", "Palin" ] ) print "number: ",o.count_actors() a = o.list_actors() for l in a: print l Thanks, Tony From ian.g.kelly at gmail.com Mon Dec 7 13:12:39 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 11:12:39 -0700 Subject: Issue In-Reply-To: <5664cfc9$0$1583$c3e8da3$5496439d@news.astraweb.com> References: <5664cfc9$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Dec 6, 2015 at 5:16 PM, Steven D'Aprano wrote: > Oh, I can make one guess... if you're using Windows XP, I'm afraid that > Python 3.5 is not supported. You'll have to either downgrade to Python 3.4, > or upgrade to Windows 7 or higher, or another operating system. For the sake of accuracy, the requirement is actually Windows Vista or higher. From rgaddi at highlandtechnology.invalid Mon Dec 7 13:21:45 2015 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Mon, 7 Dec 2015 18:21:45 -0000 (UTC) Subject: Accessing container's methods References: Message-ID: Tony van der Hoff wrote: > Hi, > > I have a class A, containing embedded embedded classes, which need to > access methods from A. > . > A highly contrived example, where I'm setting up an outer class in a > Has-a relationship, containing a number of Actors. The inner class needs > to access a method of the outer class; here the method get_name. > > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. > > Can anyone please advise me on how to achieve this magic? > > # define the outer class > class Monty: > def __init__( self, names ): > self.actors = [] > > i = 0 > for n in names: > self.actors.append( Actor( n, i ) ) > i += 1 # here is a case for python supporting post-increment! > > def count_actors( self ): > return len( self.actors ) > > def list_actors( self ): > h=[] > for n in self.actors: > h.append( n.get_name() ) > return h > > # define the inner class > class Actor: > def __init__ ( self, name, id ): > self.name = name > self.id = id > > def get_name( self ): > > # and here lies the problem; > # AttributeError: Actor instance has no attribute 'count_actors' > # how do I access the method in the enclosing class > txt = "I'm Actor {} Number {} of {}".\ > format( self.name, self.id, self.count_actors() ) > > # this works, of course > #txt = "I'm Actor \"{}\"; Number {}. ".\ > format( self.name, self.id ) > > return txt > > if __name__ == '__main__': > o = Monty( ["Cleese", "Idle", "Palin" ] ) > print "number: ",o.count_actors() > a = o.list_actors() > for l in a: > print l > > Thanks, Tony Ideally, you wouldn't. The Actor's name is independent of the number of them in the Monty, and all logic that needed to know about the full Monty would be there in list_actors, not delegated down to the Actor. That way all your dependencies are unidirectional: a Monty has a lot of expectations about an Actor but an Actor knows nothing about a Monty. And that's GREAT when you can make it work. Sometimes, in non-contrived examples, you get a situation where you can't avoid blending information around in both directions. In that case, your Monty instance is already acting as a factory for Actors. Keep going with that; have the Actor be init'ed with a .monty that refers back to the Monty containing it. It's a circular reference, but you can either a) break that using weakref or b) not care and trust Python's garbage collection to sort it all out eventually. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From torriem at gmail.com Mon Dec 7 13:36:02 2015 From: torriem at gmail.com (Michael Torrie) Date: Mon, 07 Dec 2015 11:36:02 -0700 Subject: Accessing container's methods In-Reply-To: References: Message-ID: <5665D192.9010504@gmail.com> On 12/07/2015 11:10 AM, Tony van der Hoff wrote: > Hi, > > I have a class A, containing embedded embedded classes, which need to > access methods from A. > . > A highly contrived example, where I'm setting up an outer class in a > Has-a relationship, containing a number of Actors. The inner class needs > to access a method of the outer class; here the method get_name. > > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. > > Can anyone please advise me on how to achieve this magic? You could add an attribute to each embedded object that provides a reference back to the container object. All in all, this design has a kind of smell to it. Would it not be better to ask the container class for information about the children, rather than the other way around? If a piece of code holds a reference to the child object then it must also by definition hold a reference to the container object, so why can't it ask the container object directly? From PointedEars at web.de Mon Dec 7 13:46:12 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 07 Dec 2015 19:46:12 +0100 Subject: Accessing container's methods References: Message-ID: <90599474.m2LfGONAbA@PointedEars.de> Tony van der Hoff wrote: > I have a class A, containing embedded embedded classes, which need to > access methods from A. Let the name of the "embedded class" (which is not embedded at all in your example code) be E. You could either store the information in the E instance upon or after construction, or you could pass a reference to the A instance to the E instance?s method, so that you can call the A instance?s public methods from the E instance?s methods. But consider the Law of Demeter. > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. It would simply be wrong. Monty (Python) is (literally) a group of Actors. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From __peter__ at web.de Mon Dec 7 13:59:54 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Dec 2015 19:59:54 +0100 Subject: Accessing container's methods References: Message-ID: Tony van der Hoff wrote: > Hi, > > I have a class A, containing embedded embedded classes, which need to > access methods from A. > . > A highly contrived example, where I'm setting up an outer class in a > Has-a relationship, containing a number of Actors. The inner class needs > to access a method of the outer class; here the method get_name. > > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. > > Can anyone please advise me on how to achieve this magic? > > # define the outer class > class Monty: > def __init__( self, names ): > self.actors = [] > > i = 0 > for n in names: > self.actors.append( Actor( n, i ) ) > i += 1 # here is a case for python supporting post-increment! > > def count_actors( self ): > return len( self.actors ) > > def list_actors( self ): > h=[] > for n in self.actors: > h.append( n.get_name() ) > return h > > # define the inner class > class Actor: > def __init__ ( self, name, id ): > self.name = name > self.id = id > > def get_name( self ): > > # and here lies the problem; > # AttributeError: Actor instance has no attribute 'count_actors' > # how do I access the method in the enclosing class > txt = "I'm Actor {} Number {} of {}".\ > format( self.name, self.id, self.count_actors() ) > > # this works, of course > #txt = "I'm Actor \"{}\"; Number {}. ".\ > format( self.name, self.id ) > > return txt > > if __name__ == '__main__': > o = Monty( ["Cleese", "Idle", "Palin" ] ) > print "number: ",o.count_actors() > a = o.list_actors() > for l in a: > print l I think I've seen the solution a long time a go in a Borland library -- a Collection and a CollectionItem class, the latter with a reference to the collection it belongs to. However, you are introducing a reference cycle, and a simpler solution like putting a print_actor() method into the Monty class is probably the way to go. Anyway, here's a variant of your code using the back reference (and a few cosmetical changes): __metaclass__ = type # python 2 compatibility class Monty: def __init__(self, names): self.actors = [] for id, name in enumerate(names, 1): Actor(name, id, container=self) def __len__(self): return len(self.actors) def __iter__(self): for actor in self.actors: yield actor def remove(self, actor): raise NotImplementedError def add(self, actor): self.actors.append(actor) class Actor: def __init__ (self, name, id, container=None): self.name = name self.id = id self._container = None self.container = container def get_container(self): return self._container def set_container(self, container): if self._container is not None: self._container.remove(self) if container is not None: container.add(self) self._container = container container = property(get_container, set_container) def __repr__(self): return "I'm Actor {} Number {} of {}".format( self.name, self.id, len(self.container)) if __name__ == '__main__': o = Monty( ["Cleese", "Idle", "Palin" ]) print("number: {}".format(len(o))) for l in o: print(l) From PointedEars at web.de Mon Dec 7 14:03:59 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 07 Dec 2015 20:03:59 +0100 Subject: Accessing container's methods References: Message-ID: <9541165.BHaEqqM5qn@PointedEars.de> Michael Torrie wrote: > On 12/07/2015 11:10 AM, Tony van der Hoff wrote: >> I have a class A, containing embedded embedded classes, which need to >> access methods from A. >> . >> A highly contrived example, where I'm setting up an outer class in a >> Has-a relationship, containing a number of Actors. The inner class needs >> to access a method of the outer class; here the method get_name. >> >> I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; >> that would raise all sorts of other problems. >> >> Can anyone please advise me on how to achieve this magic? > > You could add an attribute to each embedded object that provides a > reference back to the container object. ACK. > All in all, this design has a kind of smell to it. Would it not be > better to ask the container class for information about the children, > rather than the other way around? If a piece of code holds a reference > to the child object then it must also by definition hold a reference to > the container object, so why can't it ask the container object directly? Indeed, in this example asking the parent would be the best approach because only the number of actors is requested. That number should not change, and if it can change, then there should be an interface for that (a public method), in which the parent must update it. So Monty.count_actors() does not have to count the actors each time it is called from Actor.get_name(); it just has to return the value of a private attribute containing the current count. In other cases asking the parent would avoid inconsistencies, but that could be at the cost of efficiency; for example, a search for each child object, which does not scale well. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From ian.g.kelly at gmail.com Mon Dec 7 14:33:41 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 12:33:41 -0700 Subject: Accessing container's methods In-Reply-To: References: Message-ID: On Mon, Dec 7, 2015 at 11:10 AM, Tony van der Hoff wrote: > Hi, > > I have a class A, containing embedded embedded classes, which need to access > methods from A. > . > A highly contrived example, where I'm setting up an outer class in a Has-a > relationship, containing a number of Actors. The inner class needs to access > a method of the outer class; here the method get_name. > > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. > > Can anyone please advise me on how to achieve this magic? I'm guessing that you're coming from Java. Java has two different types of nested classes: non-static, where an instance of the inner class is implicitly associated with an instance of the outer class; and static, where an instance of the inner class is unrelated to any instance of the outer class. It looks like you're trying to do the former, but Python only has the static type of nested classes. So how would you go about creating a nested class of the non-static type? Make the association explicit. When Monty creates an Actor, pass it self as one of the arguments. Actor can then save that instance of Monty in an attribute and call the method thusly. As others have noted, this does create a reference cycle. The Python garbage collector is fine with cleaning up reference cycles as long as there are no objects __del__ methods anywhere in the cycle, so it's up to you whether you consider that to be a problem or not. From PointedEars at web.de Mon Dec 7 15:21:38 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 07 Dec 2015 21:21:38 +0100 Subject: Brief Code Review Please - Learning Python References: <8fce9c71-a7bf-43fa-b8cc-f23c268e2b05@googlegroups.com> Message-ID: <2734676.n8c9ur5snb@PointedEars.de> Joel Goldstick wrote: > On Sun, Dec 6, 2015 at 12:21 PM, wrote: >> * Same question as right above but with the if tests on lines 5-8. >> * I've also used ( ) around the if tests, but I'm not sure if this is >> good Python style or not. >> >> 1 def measure_string(desired_text, >> 2 desired_font_family, >> 3 desired_font_size, >> 4 is_multi_lines): >> 5 if (desired_text != '') and \ >> 6 (desired_font_family != '') and \ >> 7 (desired_font_size != '') and \ >> 8 ((is_multi_lines == "True") or (is_multi_lines == "False")): >> > > The above test will always be True. How did you get that idea? > Look up what is considered True in Python, and what is False. ISTM that *you* should do that. > I imagine you don't want quotes around True and False. I imagine also that they do not want to write ?== True? and ?== False?. Because you can omit the former and should replace ?x == False? with ?not x?. This applies to many programming languages, even those that do type conversion (and have ?!? instead of ?not?). > Any string will == True No, Python does not do type conversion on comparison by default. $ python -c 'print("" == False)' False $ python -c 'print("True" == True)' False $ python -c 'print(True == True)' True (You have to define the __eq__() method of an object for that, and then you should also define at least __ne__().) >> 9 with Image(filename='wizard:') as temp_image: >> 10 with Drawing() as measure: >> 11 measure.font_family = desired_font_family >> 12 measure.font_size = desired_font_size >> 13 measures = measure.get_font_metrics(temp_image, >> 14 desired_text, >> 15 >> multiline=is_multi_lines) >> > > No need to set multiline = ... when is_multiline is already defined Watch for word wrap. He sets the argument for the ?multiline? parameter in the measure.get_font_metrics() method call from the ?is_multi_lines? parameter of the measure_string() call. Please trim your quotes to the relevant minimum. OP: Please do not post code line numbers or any other "decoration" if you want a code review. Especially with Python it is important that you post the code verbatim. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail.$ From villascape at gmail.com Mon Dec 7 16:07:40 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Mon, 7 Dec 2015 13:07:40 -0800 (PST) Subject: Understanding Python from a PHP coder's perspective Message-ID: Hello all! Just started getting into Python, and am very excited about the prospect. I am struggling on some general concepts. My past experience with server-side code is mostly limited to PHP and websites. I have some file called "whatever.php", the browser accesses it, and PHP parses it and returns HTML, JSON, etc. Every now and then, I need to run some background PHP script, or have some PHP script initiated by a CRON job, or have some PHP script initiated by the command line running in an endless loop, and while it works, feel other languages might be more appropriate. So, my interest in Python... I've read up on Python, and while some aspects seem similar to PHP, some don't. I have learned how to create Python script, have run it from the command line, and have even accessed it with Apache by placing http://example.com/myscript.py in the browser. I am used to seeing .php extensions, but never .py extentions, and even visited multiple sites which I knew were written in Python, but never saw the browser expose the .py extensions. I am obviously missing something. Why don't I see the .py extension in my browser? Is Python event driven like PHP, or is it somehow different? How should I view Python differently than PHP? Thank you From villascape at gmail.com Mon Dec 7 16:21:42 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Mon, 7 Dec 2015 13:21:42 -0800 (PST) Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> Right after I sent my first post, I realized I did not include the following: Per https://wiki.python.org/moin/PythonVsPhp, "The vast majority of Python Web applications are run in a separate process. This has some important implications." >From a PHP background, guess I just don't understand the concept of "separate processes". What does this mean, how is it implemented, and what are the "important implications"? From cs at zip.com.au Mon Dec 7 16:33:57 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 8 Dec 2015 08:33:57 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: <20151207213357.GA87970@cskk.homeip.net> On 07Dec2015 13:07, villascape at gmail.com wrote: >Hello all! Just started getting into Python, and am very excited about the prospect. > >I am struggling on some general concepts. My past experience with server-side code is mostly limited to PHP and websites. I have some file called "whatever.php", the browser accesses it, and PHP parses it and returns HTML, JSON, etc. Every now and then, I need to run some background PHP script, or have some PHP script initiated by a CRON job, or have some PHP script initiated by the command line running in an endless loop, and while it works, feel other languages might be more appropriate. > >So, my interest in Python... > >I've read up on Python, and while some aspects seem similar to PHP, some don't. I have learned how to create Python script, have run it from the command line, and have even accessed it with Apache by placing http://example.com/myscript.py in the browser. I am used to seeing .php extensions, but never .py extentions, and even visited multiple sites which I knew were written in Python, but never saw the browser expose the .py extensions. I am obviously missing something. The most obvious thing is: a well produced website does not expose its implementation language in the URL. All those .php URLs? Sloppy! Suppose you wanted to change the implementation and switched languages? All your users' bookmarks would break! >Why don't I see the .py extension in my browser? Usually Python is used in a web server via a WSGI plugin and a framework of some kind (Django, Flask, CheryPy etc). All of these allow you to associate any URL with any piece of Python code. So you don't have that simple but also inflexible "map this URL to a specific .php file" model that you have with typical PHP. >Is Python event driven like PHP, or is it somehow different? Depends what you mean by "event driven". I suspect you mean "accessing a web page runs a python program". A .php file is a kind of macro file: it is ostensibly HTML until one hits the How should I view Python differently than PHP? It is more useful and nicer to work in. For a quick and dirty web page PHP is a handy tool, but almost entirely for the web. Python is not targeted specificly at web output. Cheers, Cameron Simpson From ian.g.kelly at gmail.com Mon Dec 7 16:37:23 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 14:37:23 -0700 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On Mon, Dec 7, 2015 at 2:07 PM, wrote: > Hello all! Just started getting into Python, and am very excited about the prospect. > > I am struggling on some general concepts. My past experience with server-side code is mostly limited to PHP and websites. I have some file called "whatever.php", the browser accesses it, and PHP parses it and returns HTML, JSON, etc. Every now and then, I need to run some background PHP script, or have some PHP script initiated by a CRON job, or have some PHP script initiated by the command line running in an endless loop, and while it works, feel other languages might be more appropriate. > > So, my interest in Python... > > I've read up on Python, and while some aspects seem similar to PHP, some don't. I have learned how to create Python script, have run it from the command line, and have even accessed it with Apache by placing http://example.com/myscript.py in the browser. I am used to seeing .php extensions, but never .py extentions, and even visited multiple sites which I knew were written in Python, but never saw the browser expose the .py extensions. I am obviously missing something. > > Why don't I see the .py extension in my browser? PHP tends to be served like CGI, which is that the URL mirrors the path to a script that lives under a particular directory, which the webserver locates and executes. This has some downsides: * It exposes details about the structure of your server to the public, which is considered a security weakness. * An improperly configured webserver might accidentally serve scripts or other files that are not intended to be served over the web, which is a much bigger security risk. * It's inflexible; if you move your script, then the URL must necessarily change as well. With Python, it's more usual to have a greater abstraction between URLs and code. A set of URLs are mapped to a single Python gateway, and the gateway dispatches the request to the appropriate request handler. With this scheme there is no reason to have .py extensions in the URLs because the URL structure is unrelated to how the actual scripts are organized in the file system. This also makes it easier to create meaningful URLs: see https://en.wikipedia.org/wiki/Semantic_URL. From tjreedy at udel.edu Mon Dec 7 16:38:33 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Dec 2015 16:38:33 -0500 Subject: Accessing container's methods In-Reply-To: References: Message-ID: On 12/7/2015 1:10 PM, Tony van der Hoff wrote: > Hi, > > I have a class A, containing embedded embedded classes, which need to > access methods from A. > . > A highly contrived example, where I'm setting up an outer class in a > Has-a relationship, containing a number of Actors. The inner class needs > to access a method of the outer class; here the method get_name. > > I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; > that would raise all sorts of other problems. > > Can anyone please advise me on how to achieve this magic? > > # define the outer class > class Monty: > def __init__( self, names ): > self.actors = [] > > i = 0 > for n in names: > self.actors.append( Actor( n, i ) ) > i += 1 # here is a case for python supporting post-increment! This is actually a case for using enumerate: for i, name in enumerate(names): > > def count_actors( self ): > return len( self.actors ) > > def list_actors( self ): > h=[] > for n in self.actors: > h.append( n.get_name() ) > return h return list(self.actors) # or perhaps even faster return self.actors[:] > # define the inner class > class Actor: > def __init__ ( self, name, id ): > self.name = name > self.id = id Tkinter, and I presume tk, works by creating circular references. widgets get a reference to a master widget, and container get a reference to widgets that are placed (or packed or gridded) therein. Widgets have an explicit .destroy method (inherited from tcl/tk) to undo the circularity. It works, but it is not completely without problems. -- Terry Jan Reedy From rosuav at gmail.com Mon Dec 7 16:40:22 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 08:40:22 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 8:07 AM, wrote: > I am struggling on some general concepts. My past experience with server-side code is mostly limited to PHP and websites. I have some file called "whatever.php", the browser accesses it, and PHP parses it and returns HTML, JSON, etc. Every now and then, I need to run some background PHP script, or have some PHP script initiated by a CRON job, or have some PHP script initiated by the command line running in an endless loop, and while it works, feel other languages might be more appropriate. > > So, my interest in Python... > > I've read up on Python, and while some aspects seem similar to PHP, some don't. I have learned how to create Python script, have run it from the command line, and have even accessed it with Apache by placing http://example.com/myscript.py in the browser. I am used to seeing .php extensions, but never .py extentions, and even visited multiple sites which I knew were written in Python, but never saw the browser expose the .py extensions. I am obviously missing something. > > Why don't I see the .py extension in my browser? > > Is Python event driven like PHP, or is it somehow different? > > How should I view Python differently than PHP? Hi there! Welcome to the list, and thank you for trying to understand the differences, instead of simply expecting Python to behave like the thing you already know. To demonstrate what I'm talking about, I'm going to use a tiny Python-based web site that I knocked together a little while ago. The source code is on GitHub, and the site itself is public, so you can see both: https://github.com/Rosuav/MinstrelHall http://minstrelhall.com/ The most important file is mh.py - click on that to see the code. In PHP-based web sites, the structure of your source code exactly matches the structure of your web site. The file system *is* your web site; any time the web server (say, Apache) comes across something that has the .php extension, it goes and runs it as code. In Python-based web sites like this one, the layout of the source tree follows a structure that keeps logically-similar things together, and the structure of the web site is defined by code. As you read through mh.py, you'll see a number of lines saying @app.route("...") - those are creating URLs (sloppy terminology, but close enough). There's one that says @app.route("/"), which handles http://minstrelhall.com/, and another just underneath it that says @app.route("/campaign/"), which handles http://minstrelhall.com/campaign/6 (and any other integer ID that might be passed in). One advantage of this kind of setup is that your URLs don't depend on your back end. I could replace all this with a Ruby on Rails site, and nobody would notice the difference. I could put together something using Node.js to replace the Ruby site, and continue to provide content at http://minstrelhall.com/campaign/6 - again, nobody would care. Another *massive* advantage is a complete separation of code and data. You can't see it in Minstrel Hall, but here's a web site that has a static-files collection: https://github.com/Rosuav/Flask1 http://rosuav.com/1/ (Note that this Flask site isn't running the whole domain, but only one subdirectory. What Python sees as @app.route("/foo") is actually http://rosuav.com/1/foo.) Any files in the static/ directory are made available by the framework - but they are, by definition, static files. Any file that I put there will be delivered as-is. Suppose I create a world-writable directory called "uploads", and then have a script that accepts a form submission with an attachment, saving the attachment into the uploads directory. (This, by the way, is not an engineered example; it's a real-world example from another web site that I host.) If the uploads directory is inside static, anything saved to there will be viewable as http://rosuav.com/1/uploads/some_file_name, but - and this is the important part - no matter what its file extension, *it will not be run*. You can upload a .py file, and it'll be visible as Python source code. You can upload a .cgi script, and it'll be visible as plain text. You can upload a .php file, and nothing will run it. This is quite tricky to do with PHP, and requires some careful management of Apache config files (or presumably the equivalent in nginx or other servers). With Python+Flask (or any other code-based server setup), it's automatic. This safety makes a *huge* difference to the compromisability of your web site; you can accept uploads without worrying about remote users running code and creating reverse shells and stuff. So that's a quick potted summary of why the URLs don't reflect the language used. Python is event-driven, but instead of defining events at the file level, the way PHP does, they're defined at the function level. Of course, if you *want* to put ".py" on the end of all your URLs, Python won't stop you... :) ChrisA From tjreedy at udel.edu Mon Dec 7 16:53:48 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Dec 2015 16:53:48 -0500 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On 12/7/2015 4:07 PM, villascape at gmail.com wrote: > Hello all! Just started getting into Python, and am very excited about the prospect. > > I am struggling on some general concepts. My past experience with server-side code is mostly limited to PHP and websites. I have some file called "whatever.php", the browser accesses it, and PHP parses it and returns HTML, JSON, etc. Every now and then, I need to run some background PHP script, or have some PHP script initiated by a CRON job, or have some PHP script initiated by the command line running in an endless loop, and while it works, feel other languages might be more appropriate. > > So, my interest in Python... > > I've read up on Python, and while some aspects seem similar to PHP, some don't. I have learned how to create Python script, have run it from the command line, and have even accessed it with Apache by placing http://example.com/myscript.py in the browser. I am used to seeing .php extensions, but never .py extentions, and even visited multiple sites which I knew were written in Python, but never saw the browser expose the .py extensions. I am obviously missing something. > > Why don't I see the .py extension in my browser? Better security, I believe. > Is Python event driven like PHP, or is it somehow different? Python is not event-driven as you mean it, but you can do event-driven systems in Python. > How should I view Python differently than PHP? You should formulate your own general view. For specific aspects, ask more specific quesitons, like you did above. -- Terry Jan Reedy From ian.g.kelly at gmail.com Mon Dec 7 16:59:26 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 14:59:26 -0700 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On Mon, Dec 7, 2015 at 2:40 PM, Chris Angelico wrote: > So that's a quick potted summary of why the URLs don't reflect the > language used. Python is event-driven, but instead of defining events > at the file level, the way PHP does, they're defined at the function > level. Of course, if you *want* to put ".py" on the end of all your > URLs, Python won't stop you... :) Or, if it's a poorly implemented site, ".rb". ;-) From rosuav at gmail.com Mon Dec 7 17:00:17 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 09:00:17 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> Message-ID: On Tue, Dec 8, 2015 at 8:21 AM, wrote: > Per https://wiki.python.org/moin/PythonVsPhp, "The vast majority of Python Web applications are run in a separate process. This has some important implications." > > From a PHP background, guess I just don't understand the concept of "separate processes". What does this mean, how is it implemented, and what are the "important implications"? This is talking about how PHP code is generally run inside the server's process. I'll use Apache as my example, as that's what I have handy. There are a couple of ways that Apache can run PHP code. One is spawning a new process for every page request, and using CGI mode; and the other is a thing called mod_php, which runs PHP as a module inside the Apache process. The first one gives great isolation between pages, but it's horribly slow (every page request has to start a process - cheap on Unix, expensive on Windows - and fully initialize PHP, which is expensive everywhere); the second fixes the performance problem, at the cost of maintaining hidden state in the Apache process. Most PHP web sites out there are using (the equivalent of) mod_php. Coupled with features like persistent database connections (another way of improving performance at the cost of isolation), or changes to PHP error handling configs, this can create *very* debug-hard problems that depend on the exact distribution of work among Apache processes. This becomes even worse if you have multiple PHP web sites running in the same Apache instance; any one of them could interfere with any other. In contrast, Python code is run in a separate process from Apache. It openly and honestly does NOT reset its state between page requests (which you do need to be aware of; for instance, always commit/roll back your database transactions before returning), but there's no way for Python to affect Apache or vice versa. If you have two Python web sites on the same server, they are completely isolated from each other. As well as the massively-beneficial implications of this isolation, there are some less positive effects. One is that you need to have a complete Python process for each site you have active - or else pay a hefty startup penalty on first page load. This can cost a lot of memory, especially if you have a lot of isolated little web sites running. But the benefits of isolation are usually worth that cost; it's possible to run the web server as one user (say, www-data) and the application server as a different user (say, python-app), and then grant file system permissions differently to the different users. You could have two apps running in different versions of Python, or with different versions of third-party packages. You can put memory or CPU usage limits on the Python process, without worrying about the web server itself going down. It's a very different structure from the mod_php model, and worth understanding. Personally, I think the costs are worth it; but if you have a mostly-static web site with just a tiny amount of scripting in it, it might be better to follow a PHP model. ChrisA From rosuav at gmail.com Mon Dec 7 17:02:33 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 09:02:33 +1100 Subject: Accessing container's methods In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 8:38 AM, Terry Reedy wrote: >> def list_actors( self ): >> h=[] >> for n in self.actors: >> h.append( n.get_name() ) >> return h > > > return list(self.actors) # or perhaps even faster > return self.actors[:] Not identical semantics. This is a use-case for a comprehension: return [n.get_name() for n in self.actors] (although I would eschew the getter in favour of just "n.name") ChrisA From rosuav at gmail.com Mon Dec 7 17:03:04 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 09:03:04 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 8:59 AM, Ian Kelly wrote: > On Mon, Dec 7, 2015 at 2:40 PM, Chris Angelico wrote: >> So that's a quick potted summary of why the URLs don't reflect the >> language used. Python is event-driven, but instead of defining events >> at the file level, the way PHP does, they're defined at the function >> level. Of course, if you *want* to put ".py" on the end of all your >> URLs, Python won't stop you... :) > > Or, if it's a poorly implemented site, ".rb". ;-) Well hey. Python won't stop me from adding ".rb" to the ends of my URLs either... ChrisA From villascape at gmail.com Mon Dec 7 17:27:21 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Mon, 7 Dec 2015 14:27:21 -0800 (PST) Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> Message-ID: <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Thank you all! Okay, the concept of a WSGI along with a framework provides insight on my main questions. In regards to Chris's statement: "It openly and honestly does NOT reset its state between page requests" With PHP, I have sessions to preserve state. I have a feeling that this is significantly different. Yes? How? Does this somehow relate to how websockets are implemented? From python.list at tim.thechases.com Mon Dec 7 17:28:23 2015 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 7 Dec 2015 16:28:23 -0600 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: <20151207162823.4f97539e@bigbox.christie.dr> On 2015-12-08 08:40, Chris Angelico wrote: > One advantage of this kind of setup is that your URLs don't depend > on your back end. I could replace all this with a Ruby on Rails > site, and nobody would notice the difference. I could put together > something using Node.js to replace the Ruby site, and continue to > provide content at http://minstrelhall.com/campaign/6 Of course, this assumes that your Ruby/Node.js skills allow you to create a site that's as robust as Python. Trust me...if I were to swap out my Python web code with Ruby or Node.js, it would be pretty noticeable. Not because of URL issues, but because I don't do Ruby/Node.js so it would fail pretty spectacularly. :-D -tkc From cs at zip.com.au Mon Dec 7 18:07:19 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 8 Dec 2015 10:07:19 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> References: <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: <20151207230719.GA87383@cskk.homeip.net> On 07Dec2015 14:27, villascape at gmail.com wrote: >In regards to Chris's statement: "It openly and honestly does NOT reset its >state between page requests" >With PHP, I have sessions to preserve state. I have a feeling that this is >significantly different. Yes? How? Does this somehow relate to how >websockets are implemented? Plenty of things use sessions, and I suspect most frameworks provide handy mechanisms to make using them easier. I expect that normally, as with PHP, you'd pass a cookie back to the user to track them and store the session state either in an in memory data structure (loses state over an app or web server restart) or in some persistent storage, typically a database of some kind (which also allows another process implementing your app/site to handle the state even if it did not issue the original session). Cannot address your websockets query. Cheers, Cameron Simpson From rosuav at gmail.com Mon Dec 7 18:09:58 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 10:09:58 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: On Tue, Dec 8, 2015 at 9:27 AM, wrote: > In regards to Chris's statement: "It openly and honestly does NOT reset its state between page requests" > > With PHP, I have sessions to preserve state. I have a feeling that this is significantly different. Yes? How? Does this somehow relate to how websockets are implemented? All three are very different. 1) Process state. You start up a Python program, and it sits there waiting for a request. You give it a request, and get back a response; it goes back to waiting for a request. If you change a global variable, or maintain persistent state, or anything, the next request will 'see' that change. This is completely global. 2) Sessions, cookies, and related concepts. A request comes in, and the response goes out "Hi! You're caller number 52635686412, and your call is important to us". Another request comes in from the same web browser, and the browser says "Hi! You said I was caller number 52635686412". The server looks up its information about that caller, which might be in a database, or on disk in the /tmp directory, or stored in process state (see above), or anything at all. This gives the appearance of per-client state, but it's all a simulation. 3) Websockets. A client makes a request saying "Hey, I want a websocket, please". The server says "Sure", and then they start maintaining true state. The socket would be broken if either the server or the client restarts (unlike sessions, although normally they're set up so a client restart will wipe the session). Websocket state is per-connection. Does that answer your question? The one I was talking about there was #1, process state. ChrisA From ian.g.kelly at gmail.com Mon Dec 7 18:10:31 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 16:10:31 -0700 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: On Mon, Dec 7, 2015 at 3:27 PM, wrote: > Thank you all! > > Okay, the concept of a WSGI along with a framework provides insight on my main questions. > > In regards to Chris's statement: "It openly and honestly does NOT reset its state between page requests" > > With PHP, I have sessions to preserve state. I have a feeling that this is significantly different. Yes? How? Does this somehow relate to how websockets are implemented? Session state is different from process state. Whether you start a new process for each request or reuse an existing process has no bearing on whether you're storing and reading data related to the user's session (except that in the reuse case it's possible to cache the data in-process, whereas an in-memory cache for a restarted process must be in a separate process; but it's good practice to have your in-memory cache in a separate process anyway). I'm not sure where websockets come into this, as that's a completely separate technology that is not used by most web apps. From python at lucidity.plus.com Mon Dec 7 18:47:26 2015 From: python at lucidity.plus.com (Erik) Date: Mon, 7 Dec 2015 23:47:26 +0000 Subject: Accessing container's methods In-Reply-To: References: Message-ID: <56661A8E.7010201@lucidity.plus.com> Hi Tony, On 07/12/15 18:10, Tony van der Hoff wrote: > A highly contrived example, where I'm setting up an outer class in a > Has-a relationship, containing a number of Actors. The inner class needs > to access a method of the outer class; here the method get_name. Generally, an object should not need to know which container it's in (let alone its "index" or "key" in that container). Amongst other things, you can't put the object into multiple containers which might be organised differently and you are asking for bugs where the container and the object get out of sync WRT just where the object is in the container (in your example, if you found you wanted to add a method where the 'actors' list is modified (say, calling "self.actors.insert(3, ...)", or sorting the list) then things get nasty quickly. However, you've said this is a highly contrived example, so I'll bear with you and assume what you're trying to do is not quite as nasty as the example implies ;) > Can anyone please advise me on how to achieve this magic? As you can't sensibly put the object into more than one container at a time anyway, then you can pass the container object to the Actor object as its "parent". It can then call its parent object for things that the parent will know (such as, the total number of contained objects): class Actor: def __init__ ( self, name, id, parent ): self.name = name self.id = id self.parent = parent def get_name( self ): txt = "I'm Actor {} Number {} of {}".\ format( self.name, self.id, self.parent.count_actors() ) return txt Then you can add a new actor with: self.actors.append( Actor( n, i, self ) ) Note that you are creating circular references here, too (the container references the Actor object and the Actor object references the container). Just another possible issue to bear in mind ... Also, while I'm looking at this, you have this loop and comment: > def __init__( self, names ): > self.actors = [] > > i = 0 > for n in names: > self.actors.append( Actor( n, i ) ) > i += 1 # here is a case for python supporting post-increment! However, if you refactor that loop to use iterators, you don't need to manually manipulate 'i' at all (you need to import the itertools module first, and this is the "new" version where the container is passed in as the parent): def __init__( self, names ): self.actors = [ Actor ( n, i, self ) for n, i in itertools.izip(names, itertools.count()) ] Or, if you don't like list comprehensions: def __init__( self, names ): self.actors = [] for n, i in itertools.izip(names, itertools.count()): self.actors.append( Actor( n, i, self ) ) (I assume you're using Python 3 because of your print statement - in Python 3, 'itertools.izip' should just be 'zip'.) HTH, E. From rr.codeproject at outlook.com Mon Dec 7 18:53:10 2015 From: rr.codeproject at outlook.com (Raheel Rao) Date: Mon, 7 Dec 2015 23:53:10 +0000 Subject: Python Script - Windows Task Scheduler - Logging Message-ID: Hello there,I created a python script that connects to an ftp and downloads files to a specifed folder and logs each event in a log file.?This script works perfectly fine as i want it to however when i put this in a task scheduler, the script runs and downloads the file just fine except that there is no log created.?Any suggestions? I remember task scheduler have a bug where you have to put something in "start in". Have been searching froums but so far no luck.?Thanks in advance! From ian.g.kelly at gmail.com Mon Dec 7 19:24:44 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 7 Dec 2015 17:24:44 -0700 Subject: increment/decrement operators In-Reply-To: References: <20151205094115.01751274@imp> Message-ID: On Dec 5, 2015 10:21 AM, "BartC" wrote: > > > The latter is not the same. Some of the differences are: > > * ++ and -- are often inside inside expressions and return values (unlike x+=1 in Python) > > * x++ and x-- return the /current/ value of x, unlike x+=1 even if it were to return a value; it would be the new value Since x+=1 is not an expression, this is moot. > * x+=1 requires you to hard-code the value 1, but ++ is not necessarily stepping by 1. You can imagine ++ stepping something to its next value. Note that x+=1 does not necessarily have to mean stepping by 1 either. You could even do something like x+=5 to mean skip the next four values and step x to the value after that. > However, if ++ and -- are only used as statements, then why not simply map them to x+=1? In Python, that would need to be x++ and x-- as ++x or --x have existing meanings. I think a better question is if they're only going to be statements, then why bother adding them? x++ doesn't give you anything you can't get from x+=1, so why commit to supporting the extra syntax? From villascape at gmail.com Mon Dec 7 20:00:17 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Mon, 7 Dec 2015 17:00:17 -0800 (PST) Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: Ah, I was confused that process state somehow allowed Python to support per-connection state without using sessions (which lead me to ask about websockets). I guess Python could do it without storing the session ID in a file or database and instead in process state (i.e. application memory, right?), but the effect seems basically the same. Without being per-connection, what is the value of process state? From lalith at kohoku.lk Mon Dec 7 20:03:48 2015 From: lalith at kohoku.lk (lalith) Date: Tue, 08 Dec 2015 01:03:48 +0000 Subject: Packages installing problem In-Reply-To: <201512071551.tB7FpJMn003110@fido.openend.se> Message-ID: Thank for reply.. some packages does not exist for windows. Thanks, Lalith. ------ Original Message ------ From: "Laura Creighton" To: "lalith" Cc: python-list at python.org; lac at openend.se Sent: 12/7/2015 9:21:19 PM Subject: Re: Packages installing problem >In a message of Mon, 07 Dec 2015 00:32:37 +0000, lalith writes: >>Dear sir. >> >>I was using Python2.7 and i move to Python3.5. >>I face big trouble with installing software packages, i need in my >>development. >> >>Lalith >>-- >>https://mail.python.org/mailman/listinfo/python-list > >Do you want to install your packages system-wide? > >Try py -3.5 -m install > >Do you want to install your python packages in a virtual environment? > >Start reading here: >https://docs.python.org/3/library/venv.html > >If you sometimes want a python 2.7 virtual env you cannot get it with >venv. You will have to use the older virtualenv. >https://virtualenv.readthedocs.org/en/latest/ > >Laura From rxjwg98 at gmail.com Mon Dec 7 20:05:55 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 7 Dec 2015 17:05:55 -0800 (PST) Subject: Help on for loop understanding Message-ID: Hi, When I learn for loop with below link: http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html it has such explanation: \\\\\\\\\ for loop under the hood First let's look at the for loop under the hood. When Python executes the for loop, it first invokes the __iter__() method of the container to get the iterator of the container. It then repeatedly calls the next() method (__next__() method in Python 3.x) of the iterator until the iterator raises a StopIteration exception. Once the exception is raised, the for loop ends. \\\\\\\\\ When I follow a list example from the above link, and one example of myself: ////////// xx=[1,2,3,4,5] xx.next --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 xx.next AttributeError: 'list' object has no attribute 'next' xx.__iter__ Out[77]: for c in xx: print c 1 2 3 4 5 ////////////// I am puzzled that the list examples have no next method, but it can run as a for loop. Could you explain it to me the difference? Thanks, From robin.koch at t-online.de Mon Dec 7 20:14:29 2015 From: robin.koch at t-online.de (Robin Koch) Date: Tue, 8 Dec 2015 02:14:29 +0100 Subject: Help on for loop understanding In-Reply-To: References: Message-ID: Am 08.12.2015 um 02:05 schrieb Robert: > Hi, > When I learn for loop with below link: > > http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html > > it has such explanation: > > \\\\\\\\\ > for loop under the hood > > First let's look at the for loop under the hood. When Python executes the > for loop, it first invokes the __iter__() method of the container to get the > iterator of the container. It then repeatedly calls the next() method > (__next__() method in Python 3.x) of the iterator until the iterator raises a > StopIteration exception. Once the exception is raised, the for loop ends. > \\\\\\\\\ > > When I follow a list example from the above link, and one example of myself: > > ////////// > xx=[1,2,3,4,5] > > xx.next > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 xx.next > > AttributeError: 'list' object has no attribute 'next' > > xx.__iter__ > Out[77]: > > for c in xx: print c > 1 > 2 > 3 > 4 > 5 > ////////////// > > I am puzzled that the list examples have no next method, but it can run as > a for loop. Could you explain it to me the difference? Lists don't have a next method. Their iterators have: xx.__iter__().__next__() or xxIterator = xx.__iter__() xxIterator.__next__() xxIterator.__next__() xxIterator.__next__() xxIterator.__next__() xxIterator.__next__() That's also what your quoted paragraph states: | It then repeatedly calls the next() method | (__next__() method in Python 3.x) of the iterator -- Robin Koch From rxjwg98 at gmail.com Mon Dec 7 20:31:51 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 7 Dec 2015 17:31:51 -0800 (PST) Subject: Help on for loop understanding In-Reply-To: References: Message-ID: On Monday, December 7, 2015 at 8:14:46 PM UTC-5, Robin Koch wrote: > Am 08.12.2015 um 02:05 schrieb Robert: > > Hi, > > When I learn for loop with below link: > > > > http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html > > > > it has such explanation: > > > > \\\\\\\\\ > > for loop under the hood > > > > First let's look at the for loop under the hood. When Python executes the > > for loop, it first invokes the __iter__() method of the container to get the > > iterator of the container. It then repeatedly calls the next() method > > (__next__() method in Python 3.x) of the iterator until the iterator raises a > > StopIteration exception. Once the exception is raised, the for loop ends. > > \\\\\\\\\ > > > > When I follow a list example from the above link, and one example of myself: > > > > ////////// > > xx=[1,2,3,4,5] > > > > xx.next > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 xx.next > > > > AttributeError: 'list' object has no attribute 'next' > > > > xx.__iter__ > > Out[77]: > > > > for c in xx: print c > > 1 > > 2 > > 3 > > 4 > > 5 > > ////////////// > > > > I am puzzled that the list examples have no next method, but it can run as > > a for loop. Could you explain it to me the difference? > > Lists don't have a next method. Their iterators have: > > xx.__iter__().__next__() > > or > > xxIterator = xx.__iter__() > xxIterator.__next__() > xxIterator.__next__() > xxIterator.__next__() > xxIterator.__next__() > xxIterator.__next__() > > That's also what your quoted paragraph states: > > | It then repeatedly calls the next() method > | (__next__() method in Python 3.x) of the iterator > > -- > Robin Koch I use Python 2.7. I have tried these commands: xx=[1,2,3,4,5] xx.__iter__ Out[2]: xx.__iter__().__next__() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 xx.__iter__().__next__() AttributeError: 'listiterator' object has no attribute '__next__' xx.__iter__.__next__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 xx.__iter__.__next__ AttributeError: 'method-wrapper' object has no attribute '__next__' xx.__iter__() Out[5]: xx.__iter__().__next__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 xx.__iter__().__next__ AttributeError: 'listiterator' object has no attribute '__next__' xxIterator = xx.__iter__() xxIterator Out[8]: xxIterator.__next__() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 xxIterator.__next__() AttributeError: 'listiterator' object has no attribute '__next__' for c in xx: print c 1 2 3 4 5 ------------ I don't find a way to show __next__ yet. Can we explicitly get the iterator for a list? Thanks, From rxjwg98 at gmail.com Mon Dec 7 20:39:21 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 7 Dec 2015 17:39:21 -0800 (PST) Subject: Help on for loop understanding In-Reply-To: References: Message-ID: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> On Monday, December 7, 2015 at 8:32:30 PM UTC-5, Robert wrote: > On Monday, December 7, 2015 at 8:14:46 PM UTC-5, Robin Koch wrote: > > Am 08.12.2015 um 02:05 schrieb Robert: > > > Hi, > > > When I learn for loop with below link: > > > > > > http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html > > > > > > it has such explanation: > > > > > > \\\\\\\\\ > > > for loop under the hood > > > > > > First let's look at the for loop under the hood. When Python executes the > > > for loop, it first invokes the __iter__() method of the container to get the > > > iterator of the container. It then repeatedly calls the next() method > > > (__next__() method in Python 3.x) of the iterator until the iterator raises a > > > StopIteration exception. Once the exception is raised, the for loop ends. > > > \\\\\\\\\ > > > > > > When I follow a list example from the above link, and one example of myself: > > > > > > ////////// > > > xx=[1,2,3,4,5] > > > > > > xx.next > > > --------------------------------------------------------------------------- > > > AttributeError Traceback (most recent call last) > > > in () > > > ----> 1 xx.next > > > > > > AttributeError: 'list' object has no attribute 'next' > > > > > > xx.__iter__ > > > Out[77]: > > > > > > for c in xx: print c > > > 1 > > > 2 > > > 3 > > > 4 > > > 5 > > > ////////////// > > > > > > I am puzzled that the list examples have no next method, but it can run as > > > a for loop. Could you explain it to me the difference? > > > > Lists don't have a next method. Their iterators have: > > > > xx.__iter__().__next__() > > > > or > > > > xxIterator = xx.__iter__() > > xxIterator.__next__() > > xxIterator.__next__() > > xxIterator.__next__() > > xxIterator.__next__() > > xxIterator.__next__() > > > > That's also what your quoted paragraph states: > > > > | It then repeatedly calls the next() method > > | (__next__() method in Python 3.x) of the iterator > > > > -- > > Robin Koch > > I use Python 2.7. I have tried these commands: > > xx=[1,2,3,4,5] > > xx.__iter__ > Out[2]: > > xx.__iter__().__next__() > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 xx.__iter__().__next__() > > AttributeError: 'listiterator' object has no attribute '__next__' > > xx.__iter__.__next__ > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 xx.__iter__.__next__ > > AttributeError: 'method-wrapper' object has no attribute '__next__' > > xx.__iter__() > Out[5]: > > xx.__iter__().__next__ > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 xx.__iter__().__next__ > > AttributeError: 'listiterator' object has no attribute '__next__' > > xxIterator = xx.__iter__() > > xxIterator > Out[8]: > > xxIterator.__next__() > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 xxIterator.__next__() > > AttributeError: 'listiterator' object has no attribute '__next__' > > for c in xx: print c > 1 > 2 > 3 > 4 > 5 > ------------ > > I don't find a way to show __next__ yet. > Can we explicitly get the iterator for a list? > Thanks, Excuse me. I find it as the following: xx.__iter__().next Out[16]: xx.__iter__().next() Out[17]: 1 From rxjwg98 at gmail.com Mon Dec 7 20:50:37 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 7 Dec 2015 17:50:37 -0800 (PST) Subject: Help on for loop understanding In-Reply-To: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> References: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> Message-ID: <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> On Monday, December 7, 2015 at 8:39:48 PM UTC-5, Robert wrote: > On Monday, December 7, 2015 at 8:32:30 PM UTC-5, Robert wrote: > > On Monday, December 7, 2015 at 8:14:46 PM UTC-5, Robin Koch wrote: > > > Am 08.12.2015 um 02:05 schrieb Robert: > > > > Hi, > > > > When I learn for loop with below link: > > > > > > > > http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html > > > > > > > > it has such explanation: > > > > > > > > \\\\\\\\\ > > > > for loop under the hood > > > > > > > > First let's look at the for loop under the hood. When Python executes the > > > > for loop, it first invokes the __iter__() method of the container to get the > > > > iterator of the container. It then repeatedly calls the next() method > > > > (__next__() method in Python 3.x) of the iterator until the iterator raises a > > > > StopIteration exception. Once the exception is raised, the for loop ends. > > > > \\\\\\\\\ > > > > > > > > When I follow a list example from the above link, and one example of myself: > > > > > > > > ////////// > > > > xx=[1,2,3,4,5] > > > > > > > > xx.next > > > > --------------------------------------------------------------------------- > > > > AttributeError Traceback (most recent call last) > > > > in () > > > > ----> 1 xx.next > > > > > > > > AttributeError: 'list' object has no attribute 'next' > > > > > > > > xx.__iter__ > > > > Out[77]: > > > > > > > > for c in xx: print c > > > > 1 > > > > 2 > > > > 3 > > > > 4 > > > > 5 > > > > ////////////// > > > > > > > > I am puzzled that the list examples have no next method, but it can run as > > > > a for loop. Could you explain it to me the difference? > > > > > > Lists don't have a next method. Their iterators have: > > > > > > xx.__iter__().__next__() > > > > > > or > > > > > > xxIterator = xx.__iter__() > > > xxIterator.__next__() > > > xxIterator.__next__() > > > xxIterator.__next__() > > > xxIterator.__next__() > > > xxIterator.__next__() > > > > > > That's also what your quoted paragraph states: > > > > > > | It then repeatedly calls the next() method > > > | (__next__() method in Python 3.x) of the iterator > > > > > > -- > > > Robin Koch > > > > I use Python 2.7. I have tried these commands: > > > > xx=[1,2,3,4,5] > > > > xx.__iter__ > > Out[2]: > > > > xx.__iter__().__next__() > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 xx.__iter__().__next__() > > > > AttributeError: 'listiterator' object has no attribute '__next__' > > > > xx.__iter__.__next__ > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 xx.__iter__.__next__ > > > > AttributeError: 'method-wrapper' object has no attribute '__next__' > > > > xx.__iter__() > > Out[5]: > > > > xx.__iter__().__next__ > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 xx.__iter__().__next__ > > > > AttributeError: 'listiterator' object has no attribute '__next__' > > > > xxIterator = xx.__iter__() > > > > xxIterator > > Out[8]: > > > > xxIterator.__next__() > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 xxIterator.__next__() > > > > AttributeError: 'listiterator' object has no attribute '__next__' > > > > for c in xx: print c > > 1 > > 2 > > 3 > > 4 > > 5 > > ------------ > > > > I don't find a way to show __next__ yet. > > Can we explicitly get the iterator for a list? > > Thanks, > > Excuse me. I find it as the following: > > xx.__iter__().next > Out[16]: > > xx.__iter__().next() > Out[17]: 1 One example, see below please, is in the above mentioned link. I don't see the purpose of the example. \\\\\\\\\\\ class MyList(list): def __iter__(self): return MyListIter(self) class MyListIter(object): """ A sample implementation of a list iterator. NOTE: This is just a demonstration of concept!!! YOU SHOULD NEVER IMPLEMENT SOMETHING LIKE THIS! Even if you have to (for any reason), there are many better ways to implement this.""" def __init__(self, lst): self.lst = lst self.i = -1 def __iter__(self): return self def next(self): if self.i References: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> Message-ID: <5666381E.5060906@lucidity.plus.com> Hi Robert, On 08/12/15 01:39, Robert wrote: >> I don't find a way to show __next__ yet. >> Can we explicitly get the iterator for a list? >> Thanks, > > Excuse me. I find it as the following: > > xx.__iter__().next > Out[16]: > > xx.__iter__().next() > Out[17]: 1 Robin has told you how things work under the hood for the particular version of Python that he is running (Python 3). As you've seen, it works a bit different under the hood in your version (Python 2). This is why you should not be calling the __ ("dunder") methods directly. Until you understand more and want to write your own classes that support being iterated using the 'for' keyword, you should probably ignore them. Instead, the way to do this which works on all versions is: x = [1, 2, 3, 4] xit = iter(x) next(xit) next(xit) next(xit) next(xit) next(xit) This is what the 'for' keyword is doing for you - it first gets an iterator for the list (using iter()) and then processes each element that the iterator returns (from next()) until it raises the exception. It then suppresses the exception (so you don't have to catch it yourself) and exits the for loop. Of course, it might actually do this using the __ methods and other things as a shortcut internally, but that's just an implementation detail. E. From python at lucidity.plus.com Mon Dec 7 21:36:00 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 8 Dec 2015 02:36:00 +0000 Subject: Help on for loop understanding In-Reply-To: <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> References: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> Message-ID: <56664210.7040007@lucidity.plus.com> On 08/12/15 01:50, Robert wrote: > One example, see below please, is in the above mentioned link. I don't see > the purpose of the example. OK, so there are two parts to this. The first, is "how do I iterate over something". The answer to that is using "for" or using "iter()" followed by zero or more calls to "next()". In this case, by using the correct syntax/function calls your script can work under various versions of Python without change. The second is "how do I make my own classes iterable". This is what the example you pasted is trying to show. In this case, you are implementing things which are "internal" to the way the version of Python you are using does things (which is why the code Robin posted wasn't quite right for you). > I have the following two same results. What do they tell me? They tell you that the implementation does the same thing as the default implementation for a list. That perhaps doesn't help much - especially with the comment in the example telling you not to do it! Instead, try the following (Python 2): class MyList(list): def __iter__(self): return MyListIter(self) class MyListIter(object): def __init__(self, lst): self.lst = lst self.i = -1 def __iter__(self): return self def next(self): if self.i >= -len(self.lst): item = self.lst[self.i] self.i -= 1 return item raise StopIteration if __name__ == "__main__": a = MyList([1, 2, 3, 4]) ia = iter(a) print 'type(a): %r, type(ia): %r' %(type(a), type(ia)) for i in a: print i, print while True: print next(ia) What we have here is the same class that subclasses 'list'. It's just a list. However, it has a custom iterator. In this implementation the iterator works BACKWARDS through the list - the final element is returned first, the penultimate element second, and so on. After the first element has been returned, the iterator raises StopIteration. This tells you not to call next() again, or if in a for loop, the loop is exited. So, you can write your class's iterator to do anything that makes sense when someone says "for i in myclassinstance:". If your class is a subclass of a class ("is-a") that already has a defined iterator (such as a list or a dict) and the behaviour of that is correct for you, then you need to do nothing (you inherit that class's __iter__() method). If your class should iterate over an embedded object ("has-a") that already has a defined iterator, then your __iter__() method can just delegate to that object's iterator using something like: def __iter__(self): return iter(self.embedded_thing) Does that make more sense? E. From python.list at tim.thechases.com Mon Dec 7 22:11:14 2015 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 7 Dec 2015 21:11:14 -0600 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: <20151207211114.49a82ef3@bigbox.christie.dr> On 2015-12-08 10:09, Chris Angelico wrote: > All three are very different. > > 1) Process state. > > You start up a Python program, and it sits there waiting for a > request. You give it a request, and get back a response; it goes > back to waiting for a request. If you change a global variable, or > maintain persistent state, or anything, the next request will 'see' > that change. This is completely global. 1) This is completely global *to the process* (you can have multiple Python processes sitting around waiting, taking advantage of multiple cores) 2) This is almost always a bad idea for multiple reasons (it can get in the way of scaling, it can produce hard-to-track-down bugs, etc). Use a real session store (a database, a key/value store like memcached, a NoSQL store like Redis, store session info in cookies, etc.) instead. -tkc From rosuav at gmail.com Mon Dec 7 22:23:40 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 14:23:40 +1100 Subject: Help on for loop understanding In-Reply-To: <56664210.7040007@lucidity.plus.com> References: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> <56664210.7040007@lucidity.plus.com> Message-ID: On Tue, Dec 8, 2015 at 1:36 PM, Erik wrote: > So, you can write your class's iterator to do anything that makes sense when > someone says "for i in myclassinstance:". > > If your class is a subclass of a class ("is-a") that already has a defined > iterator (such as a list or a dict) and the behaviour of that is correct for > you, then you need to do nothing (you inherit that class's __iter__() > method). > > If your class should iterate over an embedded object ("has-a") that already > has a defined iterator, then your __iter__() method can just delegate to > that object's iterator using something like: > > def __iter__(self): > return iter(self.embedded_thing) Another great way to write an __iter__ method is as a generator. def __iter__(self): yield "thing" yield from self.things yield "other thing" Like returning an embedded object's iterator, this saves you having to write a __next__ method. The less work you do, the less bugs you get. ChrisA From rosuav at gmail.com Mon Dec 7 22:26:57 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 14:26:57 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> Message-ID: On Tue, Dec 8, 2015 at 12:00 PM, wrote: > Ah, I was confused that process state somehow allowed Python to support per-connection state without using sessions (which lead me to ask about websockets). I guess Python could do it without storing the session ID in a file or database and instead in process state (i.e. application memory, right?), but the effect seems basically the same. Without being per-connection, what is the value of process state? > Caches and stuff. For example, you might establish a database connection, and then hang onto it for all queries; or maybe you load up a bunch of user objects and keep them in memory for when you need them again. Anything that you store in a global (module-level) variable will hang around. ChrisA From vincent at vincentdavis.net Mon Dec 7 22:30:19 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 7 Dec 2015 20:30:19 -0700 Subject: manually build a unittest/doctest object. Message-ID: If I have a string that is python code, for example mycode = "print('hello world')" myresult = "hello world" How can a "manually" build a unittest (doctest) and test I get myresult I have attempted to build a doctest but that is not working. e = doctest.Example(source="print('hello world')/n", want="hello world\n") t = doctest.DocTestRunner() t.run(e) Thanks Vincent Davis From rosuav at gmail.com Mon Dec 7 22:47:40 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 14:47:40 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: <20151207211114.49a82ef3@bigbox.christie.dr> References: <44d92f52-4f92-470d-a724-102a14d185de@googlegroups.com> <3e30fc58-4460-40a6-a639-22cd4d406f0b@googlegroups.com> <20151207211114.49a82ef3@bigbox.christie.dr> Message-ID: On Tue, Dec 8, 2015 at 2:11 PM, Tim Chase wrote: > On 2015-12-08 10:09, Chris Angelico wrote: >> All three are very different. >> >> 1) Process state. >> >> You start up a Python program, and it sits there waiting for a >> request. You give it a request, and get back a response; it goes >> back to waiting for a request. If you change a global variable, or >> maintain persistent state, or anything, the next request will 'see' >> that change. This is completely global. > > 1) This is completely global *to the process* (you can have multiple > Python processes sitting around waiting, taking advantage of multiple > cores) > > 2) This is almost always a bad idea for multiple reasons (it can get > in the way of scaling, it can produce hard-to-track-down bugs, etc). > Use a real session store (a database, a key/value store like > memcached, a NoSQL store like Redis, store session info in cookies, > etc.) instead. If your goal is session state, then yes - use something that actually persists past the process life. But for caches and stuff, where dropping them has performance implications but nothing else, it makes good sense to keep them in globals. Particularly if you simply populate the cache on process load and then never lose it. ChrisA From villascape at gmail.com Mon Dec 7 23:11:49 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Mon, 7 Dec 2015 20:11:49 -0800 (PST) Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: Based on your responses, it is my understanding that process-state might offer some efficiency benefits, but it is typically not a driving factor. If I misunderstand, please advise. Thanks From steve+comp.lang.python at pearwood.info Tue Dec 8 00:56:52 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 08 Dec 2015 16:56:52 +1100 Subject: manually build a unittest/doctest object. References: Message-ID: <56667126$0$1497$c3e8da3$5496439d@news.astraweb.com> On Tuesday 08 December 2015 14:30, Vincent Davis wrote: > If I have a string that is python code, for example > mycode = "print('hello world')" > myresult = "hello world" > How can a "manually" build a unittest (doctest) and test I get myresult Not easily. Effectively, you would have to re-invent the doctest module and re-engineer it to accept a completely different format. But if you are willing to write your tests in doctest format, this might help you: import doctest def rundoctests(text, name='', globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, quiet=False,): # Assemble the globals. if globs is None: globs = globals() globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' # Parse the text looking for doc tests. parser = doctest.DocTestParser() test = parser.get_doctest(text, globs, name, name, 0) # Run the tests. if raise_on_error: runner = doctest.DebugRunner( verbose=verbose, optionflags=optionflags) else: runner = doctest.DocTestRunner( verbose=verbose, optionflags=optionflags) if quiet: runner.run(test, out=lambda s: None) else: runner.run(test) if report: runner.summarize() # Return a (named, if possible) tuple (failed, attempted). a, b = runner.failures, runner.tries try: TestResults = doctest.TestResults except AttributeError: return (a, b) return TestResults(a, b) Then call rundoctests(text) to run any doc tests in text. By default, if there are no errors, it prints nothing. If there are errors, it prints the failing tests. Either way, it returns a tuple (number of failures, number of tests run) Examples in use: py> good_code = """ ... >>> import math ... >>> print "Hello World!" ... Hello World! ... >>> math.sqrt(100) ... 10.0 ... ... """ py> rundoctests(good_code) TestResults(failed=0, attempted=3) py> bad_code = """ ... >>> print 10 ... 11 ... """ py> rundoctests(bad_code) ********************************************************************** File "", line 2, in Failed example: print 10 Expected: 11 Got: 10 ********************************************************************** 1 items had failures: 1 of 1 in ***Test Failed*** 1 failures. TestResults(failed=1, attempted=1) From dieter at handshake.de Tue Dec 8 02:40:27 2015 From: dieter at handshake.de (dieter) Date: Tue, 08 Dec 2015 08:40:27 +0100 Subject: Help with stale exception Python References: <99840119-b7c2-4171-b2f8-7c600c85bd87@googlegroups.com> Message-ID: <87si3dtml0.fsf@handshake.de> iverson.zhou at gmail.com writes: > ... > I have tried uncountable number of methods (e.g. explicit, implicit wait) but the stale error still persists as it seems to stays stale as long as it is staled. > > Have anyone come up with a solution to this and what is the best way to deal with DOM tree changes. > ... > with open('C:/Python34/email.csv','w') as f: > z=csv.writer(f, delimiter='\t',lineterminator = '\n',) > while True: > row = [] > for link in driver.find_elements_by_xpath("//*[@id='wrapper']/div[2]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[position() = 1 or position() = 2 or position() = 3]"): The "find_elements_by_xpath" likely gives you a list of elements on the *initial* page. The "for" sets things up that this list is iterated over. > try: > ... > c=driver.find_element_by_id('detail-pagination-next-btn') > ... > c.click() > ... > except StaleElementReferenceException as e: This "click" may change the page which means that you would now be on a page different from the initial page. It is likely that your web access framework contains some form of automatic garbage collection: when you switch to a new page, references to the old page may become stale. This could explain that you sometimes observe a "StaleElementReferenceException". Read the documentation of your web access framework to find out whether you can control stalelifying of elements when you switch a page. If this is impossible, avoid accessing elements of a page once you have switched to a new page. To this end, extract (and store) all relevant information from the page before you switch to a new one and, if necessary, use the extracted information to later restore the previous page state. As you can see from my explanation: your question is much more related to your web access framework than to Python in general. Likely, there is a forum (dedicated to this framework) that can better help you with this question than this general Python list. From dieter at handshake.de Tue Dec 8 02:50:07 2015 From: dieter at handshake.de (dieter) Date: Tue, 08 Dec 2015 08:50:07 +0100 Subject: writing an email.message.Message in UTF-8 References: Message-ID: <87oae1tm4w.fsf@handshake.de> Adam Funk writes: > I'm trying to write an instance of email.message.Message, whose body > contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 > again.) > > reply = email.message.Message() > reply.set_charset('utf-8') > ... # set various headers > reply.set_payload('\n'.join(body_lines) + '\n') > ... > outfile = codecs.open(outfilename, 'w', encoding='utf-8', errors='ignore') > outfile.write(reply.as_string()) > outfile.close() > > Then reply.as_string() barfs a UnicodeDecodeError. I look in the > documentation, which says the generator is better. So I replace the > outfile.write(...) line with the following: > > g = email.generator.Generator(outfile, mangle_from_=False) > g.flatten(reply) > > which still barfs a UnicodeDecodeError. Looking closer at the first > error, I see that the exception was in g.flatten(...) already & thrown > up to reply.as_string(). How can I force the thing to do UTF-8 > output? You could try replacing "reply.set_payload('\n'.join(body_lines) + '\n')" by "reply.set_payload(('\n'.join(body_lines) + '\n').encode('utf-8'))", i.e. you would not pass in a unicode payload but an "utf-8" encode "str" payload. From __peter__ at web.de Tue Dec 8 04:06:32 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2015 10:06:32 +0100 Subject: manually build a unittest/doctest object. References: Message-ID: Vincent Davis wrote: > If I have a string that is python code, for example > mycode = "print('hello world')" > myresult = "hello world" > How can a "manually" build a unittest (doctest) and test I get myresult > > I have attempted to build a doctest but that is not working. > e = doctest.Example(source="print('hello world')/n", want="hello world\n") > t = doctest.DocTestRunner() > t.run(e) There seems to be one intermediate step missing: example --> doctest --> runner >>> import doctest >>> example = doctest.Example( ... "print('hello world')\n", ... want="hello world\n") >>> test = doctest.DocTest([example], {}, None, None, None, None) >>> runner = doctest.DocTestRunner(verbose=True) >>> runner.run(test) Trying: print('hello world') Expecting: hello world ok TestResults(failed=0, attempted=1) But why would you want to do that? From __peter__ at web.de Tue Dec 8 04:24:48 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2015 10:24:48 +0100 Subject: Understanding Python from a PHP coder's perspective References: Message-ID: Chris Angelico wrote: > On Tue, Dec 8, 2015 at 8:59 AM, Ian Kelly wrote: >> On Mon, Dec 7, 2015 at 2:40 PM, Chris Angelico wrote: >>> So that's a quick potted summary of why the URLs don't reflect the >>> language used. Python is event-driven, but instead of defining events >>> at the file level, the way PHP does, they're defined at the function >>> level. Of course, if you *want* to put ".py" on the end of all your >>> URLs, Python won't stop you... :) >> >> Or, if it's a poorly implemented site, ".rb". ;-) > > Well hey. Python won't stop me from adding ".rb" to the ends of my > URLs either... Or ".php". Leaking the suffix is both ugly and excellent marketing -- a combination that is also common in the fashion industry. From info at egenix.com Tue Dec 8 04:25:01 2015 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 8 Dec 2015 10:25:01 +0100 Subject: ANN: eGenix pyOpenSSL Distribution 0.13.12 Message-ID: <5666A1ED.3040805@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.13.12 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.12.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 includes the following updates: New in OpenSSL -------------- * Updated included OpenSSL libraries from OpenSSL 1.0.1p to 1.0.1q. See https://www.openssl.org/news/secadv/20151203.txt ?for a complete list of changes. The following fixes are relevant for pyOpenSSL applications: - CVE-2015-3194 The signature verification routines will crash with a NULL pointer dereference, if presented with an ASN.1 signature using the RSA PSS algorithm and absent mask generation function parameter. This can be exploited in as DoS attack in applications which performs certificate verification. - CVE-2015-3195: When presented with a malformed X509_ATTRIBUTE structure OpenSSL will leak memory. - CVE-2015-3196: If PSK identity hints are received by a multi-threaded client, then the values are wrongly updated in the parent SSL_CTX structure. This can potentially lead to a double free of the identify hint data, leading to a segfault. * Updated the Mozilla CA root bundle to version 2015-10-27. * Added support to allow building wheels from source or prebuilt packages. Please see the product changelog for the full set of changes. http://www.egenix.com/products/python/pyOpenSSL/changelog.html 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, Linux, Mac OS X and FreeBSD, for x86 and x64. To simplify installation, we have uploaded a web installer to PyPI which will automatically choose the right binary for your platform, so a simple pip install egenix-pyopenssl will get you the package with OpenSSL libraries installed. Please see our installation instructions for details: http://www.egenix.com/products/python/pyOpenSSL/#Installation We have 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. About eGenix (http://www.egenix.com/): eGenix is a Python software project, consulting and product company delivering expert services and professional quality products for companies, Python users and developers. We specialize in database driven applications, large scale software designs and integration. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Dec 08 2015) >>> Python Projects, Coaching and Consulting ... http://www.egenix.com/ >>> Python Database Interfaces ... http://products.egenix.com/ >>> Plone/Zope Database Interfaces ... http://zope.egenix.com/ ________________________________________________________________________ ::: We implement business ideas - efficiently in both time and costs ::: 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/ http://www.malemburg.com/ From a24061 at ducksburg.com Tue Dec 8 04:35:06 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Tue, 08 Dec 2015 09:35:06 +0000 Subject: writing an email.message.Message in UTF-8 References: Message-ID: On 2015-12-08, dieter wrote: > Adam Funk writes: > >> I'm trying to write an instance of email.message.Message, whose body >> contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 >> again.) >> >> reply = email.message.Message() >> reply.set_charset('utf-8') >> ... # set various headers >> reply.set_payload('\n'.join(body_lines) + '\n') >> ... >> outfile = codecs.open(outfilename, 'w', encoding='utf-8', errors='ignore') >> outfile.write(reply.as_string()) >> outfile.close() >> >> Then reply.as_string() barfs a UnicodeDecodeError. I look in the >> documentation, which says the generator is better. So I replace the >> outfile.write(...) line with the following: >> >> g = email.generator.Generator(outfile, mangle_from_=False) >> g.flatten(reply) >> >> which still barfs a UnicodeDecodeError. Looking closer at the first >> error, I see that the exception was in g.flatten(...) already & thrown >> up to reply.as_string(). How can I force the thing to do UTF-8 >> output? > > You could try replacing "reply.set_payload('\n'.join(body_lines) + '\n')" > by "reply.set_payload(('\n'.join(body_lines) + '\n').encode('utf-8'))", > i.e. you would not pass in a unicode payload but an "utf-8" encode > "str" payload. That didn't work (I got the same error) but switching to python 3.2 did. Thanks, though. -- A mathematical formula should never be "owned" by anybody! Mathematics belonga to God. --- Donald Knuth From a24061 at ducksburg.com Tue Dec 8 04:35:56 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Tue, 08 Dec 2015 09:35:56 +0000 Subject: writing an email.message.Message in UTF-8 References: Message-ID: On 2015-12-07, Terry Reedy wrote: > On 12/7/2015 9:57 AM, Adam Funk wrote: >> I'm trying to write an instance of email.message.Message, whose body >> contains unicode characters, to a UTF-8 file. (Python 2.7.3 & 2.7.10 >> again.) > > The email package was rewritten for, I believe, 3.3. I believe it > should handle unicode email encoded as utf-8 more easily. Actually it works in Python 3.2.3, & fortunately my program doesn't depend on anything that isn't available for python 3 yet. Thanks! -- Most Americans are too civilized to hang skulls from baskets, having been headhunters, of course, only as recently as Vietnam. --- Kinky Friedman From rosuav at gmail.com Tue Dec 8 04:40:31 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Dec 2015 20:40:31 +1100 Subject: Understanding Python from a PHP coder's perspective In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 8:24 PM, Peter Otten <__peter__ at web.de> wrote: > Chris Angelico wrote: > >> On Tue, Dec 8, 2015 at 8:59 AM, Ian Kelly wrote: >>> On Mon, Dec 7, 2015 at 2:40 PM, Chris Angelico wrote: >>>> So that's a quick potted summary of why the URLs don't reflect the >>>> language used. Python is event-driven, but instead of defining events >>>> at the file level, the way PHP does, they're defined at the function >>>> level. Of course, if you *want* to put ".py" on the end of all your >>>> URLs, Python won't stop you... :) >>> >>> Or, if it's a poorly implemented site, ".rb". ;-) >> >> Well hey. Python won't stop me from adding ".rb" to the ends of my >> URLs either... > > Or ".php". Leaking the suffix is both ugly and excellent marketing -- a > combination that is also common in the fashion industry. Worst I've ever done there is create shim redirects. I refuse to have my Python site advertise PHP. https://github.com/Rosuav/Flask1/blob/master/1.py#L82 ChrisA From wxjmfauth at gmail.com Tue Dec 8 05:57:25 2015 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 8 Dec 2015 02:57:25 -0800 (PST) Subject: py -3.5 ... Message-ID: D:\>py -3.5 Requested Python version (3.5) not installed D:\> ;-) From ganesh1pal at gmail.com Tue Dec 8 06:00:53 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Tue, 8 Dec 2015 16:30:53 +0530 Subject: storing test logs under /var/log/ In-Reply-To: <20151203081723.GA48121@cskk.homeip.net> References: <20151203081723.GA48121@cskk.homeip.net> Message-ID: > Finally. sys.exit accepts an integer, not a string. > Most of code uses sys.exit("some error message") , I did notice that the error message is not displayed by sys .exit("some error message") , do u mean that using string is not advisable with sys.exit ? How to I display error messages with sys.exit then ? PS:Thanks for all your previous comments , all were quite helpful . Regards, Ganesh From __peter__ at web.de Tue Dec 8 07:24:54 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2015 13:24:54 +0100 Subject: storing test logs under /var/log/ References: <20151203081723.GA48121@cskk.homeip.net> Message-ID: Ganesh Pal wrote: [Cameron Simpson:] >> Finally. sys.exit accepts an integer, not a string. > Most of code uses sys.exit("some error message") , I did notice > that the error message is not displayed by sys .exit("some error > message") , do u mean that using string is not advisable with > sys.exit ? Cameron is wrong (he's probably coming from the C side of things). You can invoke sys.exit() with arbitrary objects: """ Help on built-in function exit in module sys: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). """ > How to I display error messages with sys.exit then ? Wrong question; if you want to use sys.exit() in a way similar to C display the error message first and invoke sys.exit() afterwards with a numerical argument. From tony at vanderhoff.org Tue Dec 8 07:35:48 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Tue, 8 Dec 2015 12:35:48 +0000 Subject: Accessing container's methods In-Reply-To: References: Message-ID: On 07/12/15 23:47, Erik wrote: > Hi Tony, > > On 07/12/15 18:10, Tony van der Hoff wrote: >> A highly contrived example, where I'm setting up an outer class in a >> Has-a relationship, containing a number of Actors. The inner class needs >> to access a method of the outer class; here the method get_name. > > Generally, an object should not need to know which container it's in > (let alone its "index" or "key" in that container). Amongst other > things, you can't put the object into multiple containers which might be > organised differently and you are asking for bugs where the container > and the object get out of sync WRT just where the object is in the > container (in your example, if you found you wanted to add a method > where the 'actors' list is modified (say, calling "self.actors.insert(3, > ...)", or sorting the list) then things get nasty quickly. > > However, you've said this is a highly contrived example, so I'll bear > with you and assume what you're trying to do is not quite as nasty as > the example implies ;) > >> Can anyone please advise me on how to achieve this magic? > > As you can't sensibly put the object into more than one container at a > time anyway, then you can pass the container object to the Actor object > as its "parent". It can then call its parent object for things that the > parent will know (such as, the total number of contained objects): > > class Actor: > def __init__ ( self, name, id, parent ): > self.name = name > self.id = id > self.parent = parent > > def get_name( self ): > txt = "I'm Actor {} Number {} of {}".\ > format( self.name, self.id, self.parent.count_actors() ) > return txt > > Then you can add a new actor with: > > self.actors.append( Actor( n, i, self ) ) > > > Note that you are creating circular references here, too (the container > references the Actor object and the Actor object references the > container). Just another possible issue to bear in mind ... > > > Also, while I'm looking at this, you have this loop and comment: > > > def __init__( self, names ): > > self.actors = [] > > > > i = 0 > > for n in names: > > self.actors.append( Actor( n, i ) ) > > i += 1 # here is a case for python supporting post-increment! > > However, if you refactor that loop to use iterators, you don't need to > manually manipulate 'i' at all (you need to import the itertools module > first, and this is the "new" version where the container is passed in as > the parent): > > def __init__( self, names ): > self.actors = [ Actor ( n, i, self ) for n, i in > itertools.izip(names, itertools.count()) ] > > Or, if you don't like list comprehensions: > > def __init__( self, names ): > self.actors = [] > for n, i in itertools.izip(names, itertools.count()): > self.actors.append( Actor( n, i, self ) ) > > (I assume you're using Python 3 because of your print statement - in > Python 3, 'itertools.izip' should just be 'zip'.) > HTH, > E. From lac at openend.se Tue Dec 8 08:28:34 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 08 Dec 2015 14:28:34 +0100 Subject: Python Script - Windows Task Scheduler - Logging In-Reply-To: References: Message-ID: <201512081328.tB8DSYDk028244@fido.openend.se> In a message of Mon, 07 Dec 2015 23:53:10 +0000, Raheel Rao writes: >Hello there,I created a python script that connects to an ftp and downloads files to a specifed folder and logs each event in a log file.?This script works perfectly fine as i want it to however when i put this in a task scheduler, the script runs and downloads the file just fine except that there is no log created.?Any suggestions? I remember task scheduler have a bug where you have to put something in "start in". Have been searching froums but so far no luck.?Thanks in advance! > >-- >https://mail.python.org/mailman/listinfo/python-list Maybe related to this? tackoverflow.com/questions/20196049/problems-running-python-script-by-windows-task-scheduler-that-does-pscp Laura From villascape at gmail.com Tue Dec 8 08:30:16 2015 From: villascape at gmail.com (villascape at gmail.com) Date: Tue, 8 Dec 2015 05:30:16 -0800 (PST) Subject: Is Python a good choice for a data logger? Message-ID: <70759320-547a-4e9c-b546-3bc6e273dac4@googlegroups.com> Let's say there are multiple data-loggers (PCs probably running Linux) behind various firewalls which communicate to other devices on their respective LAN via a proprietary protocol using UDP/IP to collect data. On perhaps a sixty second periodic basis, the data-loggers will send the data to a server located outside of their firewalls (via TCP/IP and probably using HTTP). The server (probably running Linux) will store the data monitored by the data-loggers. Web clients will then make HTTP requests to the server to retrieve the data. Is Python a good choice for the following: 1) The data-loggers to pole data and/or receive data from the UDP devices and send the data to the server? 2) The daemon/application running on the server which receives the data from the data-loggers, and stores it in the database? If Python is a good choice, please explain why. Also, please provide a very high level strategy to implement (I am not asking for script, but just enough so I can initially focus on learning those parts of Python). Thanks! From tony at vanderhoff.org Tue Dec 8 08:46:09 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Tue, 8 Dec 2015 13:46:09 +0000 Subject: Accessing container's methods [solved] In-Reply-To: References: Message-ID: Hum, sorry about the empty reply; just finger trouble! Anyway I wasn't expecting such a great response; thanks to all. On 07/12/15 23:47, Erik wrote: [snip] > As you can't sensibly put the object into more than one container at a > time anyway, then you can pass the container object to the Actor object > as its "parent". It can then call its parent object for things that the > parent will know (such as, the total number of contained objects): > > class Actor: > def __init__ ( self, name, id, parent ): > self.name = name > self.id = id > self.parent = parent > > def get_name( self ): > txt = "I'm Actor {} Number {} of {}".\ > format( self.name, self.id, self.parent.count_actors() ) > return txt > > Then you can add a new actor with: > > self.actors.append( Actor( n, i, self ) ) > Whilst I'm grateful for all the responses, this is the one that got me out of the hole I dug myself into. In fact, this is precisely what I tried previously, and got: TypeError: 'instancemethod' object has no attribute '__getitem__' In my naivety, I concluded that this meant I couldn't use the 'self' pointer in this way. However, trying it with the Monty example, it worked fine, and I have now tracked down my error elsewhere. > > Note that you are creating circular references here, too (the container > references the Actor object and the Actor object references the > container). Just another possible issue to bear in mind ... > Yes, I guess it's quite nasty, but, in the non-trivial case, I'm only calling for dynamic data from the parent, and not modifying it in any way, so I think I can get away with it. Otherwise, I'd have to pass a vast list of initialization data to the (many) children, and keep that up to date by passing it down the line to each one, just in case it's required, which would slow down things excessively. I know that if a design doesn't feel comfortable, then it's probably wrong, but I believe that in this case it's probably the best way forward. > > Also, while I'm looking at this, you have this loop and comment: > > > def __init__( self, names ): > > self.actors = [] > > > > i = 0 > > for n in names: > > self.actors.append( Actor( n, i ) ) > > i += 1 # here is a case for python supporting post-increment! > > However, if you refactor that loop to use iterators, you don't need to > manually manipulate 'i' at all (you need to import the itertools module > first, and this is the "new" version where the container is passed in as > the parent): > > def __init__( self, names ): > self.actors = [ Actor ( n, i, self ) for n, i in > itertools.izip(names, itertools.count()) ] > > Or, if you don't like list comprehensions: > > def __init__( self, names ): > self.actors = [] > for n, i in itertools.izip(names, itertools.count()): > self.actors.append( Actor( n, i, self ) ) > I rather liked Terry's suggestion of using enumerate. The comment was tounge-in-cheek: Referring to an earlier thread, I'm yet to be convinced that Python is better for not having pre/post-increment/decrement operators. But, hey, I'm sure better minds than mine have addressed the subject ;) > (I assume you're using Python 3 because of your print statement - in > Python 3, 'itertools.izip' should just be 'zip'.) No, Im actually stuck on Python 2.7. I don't see how you jumped to that conclusion from a simple print statement. On 07/12/15 21:38, Terry Reedy wrote: [snip] > This is actually a case for using enumerate: > for i, name in enumerate(names): > I've not come across this previously, but shall certainly use it in future. Thanks! > return list(self.actors) # or perhaps even faster > return self.actors[:] That doesn't seem to work: <__main__.Actor instance at 0x7fc7478ba560> <__main__.Actor instance at 0x7fc7478ba5a8> <__main__.Actor instance at 0x7fc7478ba5f0> Anyway, I'm no longer in a hole; thanks for all the excellent help. I'll certainly review the design of my current project, to see if it can be improved. Cheers, Tony From vincent at vincentdavis.net Tue Dec 8 09:04:39 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 8 Dec 2015 07:04:39 -0700 Subject: manually build a unittest/doctest object. In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 2:06 AM, Peter Otten <__peter__ at web.de> wrote: > But why would you want to do that? Thanks Peter, I want to do that because I want to test jupyter notebooks. ?The notebook is in JSON and I can get the source and result out but it was unclear to me how to stick this into a test. doctest seemed the simplest but maybe there is a better way. I also tried something like: assert exec("""print('hello word')""") == 'hello word' Vincent Davis 720-301-3003 From rosuav at gmail.com Tue Dec 8 09:17:42 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 9 Dec 2015 01:17:42 +1100 Subject: Is Python a good choice for a data logger? In-Reply-To: <70759320-547a-4e9c-b546-3bc6e273dac4@googlegroups.com> References: <70759320-547a-4e9c-b546-3bc6e273dac4@googlegroups.com> Message-ID: On Wed, Dec 9, 2015 at 12:30 AM, wrote: > Is Python a good choice for the following: > > 1) The data-loggers to pole data and/or receive data from the UDP devices and send the data to the server? > > 2) The daemon/application running on the server which receives the data from the data-loggers, and stores it in the database? > > > If Python is a good choice, please explain why. > Yep! Both of these applications are going to spend virtually all their time *waiting*. That means you don't have to stress about performance, and can concentrate on writing code in the easiest and cleanest way possible. To my mind, that says either Python or Pike; both languages have excellent networking libraries, but in this case, Python definitely takes the edge, because you already have broad familiarity with it. > Also, please provide a very high level strategy to implement (I am not asking for script, but just enough so I can initially focus on learning those parts of Python). > Start with the socket module: https://docs.python.org/3/library/socket.html Get to know something of how TCP/IP works, if you don't already. Then once you're ready to do your actual implementation, since you've considered using HTTP, I would suggest looking into the third-party 'requests' library for the HTTP clients (you can do everything with the standard library if you prefer, but you owe it to yourself to at least have a quick _look_ at requests), and one of the standard web frameworks for the server (personally, I use Flask, but any would do). You'll probably want a database back end to store the actual content; I strongly recommend PostgreSQL, which you can access from Python using psycopg2. If you don't like hand-writing SQL, you could use something like SQLAlchemy as middleware; otherwise, direct use of psycopg2 works just fine. Every part in this can be replaced without affecting the rest, but if I were doing this kind of job, these would be the tools I'd first reach for. requests: http://requests.readthedocs.org/en/latest/ Flask: http://flask.pocoo.org/docs/ psycopg2: http://initd.org/psycopg/docs/ SQLAlchemy: http://www.sqlalchemy.org/ You asked for a "very high level" strategy. This is so high level it's practically in LEO, but it's a start :) ChrisA From rosuav at gmail.com Tue Dec 8 09:27:10 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 9 Dec 2015 01:27:10 +1100 Subject: manually build a unittest/doctest object. In-Reply-To: References: Message-ID: On Wed, Dec 9, 2015 at 1:04 AM, Vincent Davis wrote: > I also tried something like: > assert exec("""print('hello word')""") == 'hello word' I'm pretty sure exec() always returns None. If you want this to work, you would need to capture sys.stdout into a string: import io import contextlib output = io.StringIO() with contextlib.redirect_stdout(output): exec("""print("Hello, world!")""") assert output.getvalue() == "Hello, world!\n" # don't forget the \n You could wrap this up into a function, if you like. Then your example would work (modulo the \n): def capture_output(code): """Execute 'code' and return its stdout""" output = io.StringIO() with contextlib.redirect_stdout(output): exec(code) return output.getvalue() assert capture_output("""print('hello word')""") == 'hello word\n' # no error ChrisA From lac at openend.se Tue Dec 8 09:30:39 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 08 Dec 2015 15:30:39 +0100 Subject: manually build a unittest/doctest object. In-Reply-To: References: Message-ID: <201512081430.tB8EUdZ8032414@fido.openend.se> In a message of Tue, 08 Dec 2015 07:04:39 -0700, Vincent Davis writes: >On Tue, Dec 8, 2015 at 2:06 AM, Peter Otten <__peter__ at web.de> wrote: > >> But why would you want to do that? > > >Thanks Peter, I want to do that because I want to test jupyter notebooks. >?The notebook is in JSON and I can get the source and result out but it was >unclear to me how to stick this into a test. doctest seemed the simplest >but maybe there is a better way. > >I also tried something like: >assert exec("""print('hello word')""") == 'hello word' > > >Vincent Davis >720-301-3003 >-- >https://mail.python.org/mailman/listinfo/python-list Check out this: https://pypi.python.org/pypi/pytest-ipynb Laura From vincent at vincentdavis.net Tue Dec 8 09:31:19 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 8 Dec 2015 07:31:19 -0700 Subject: manually build a unittest/doctest object. In-Reply-To: References: Message-ID: On Tue, Dec 8, 2015 at 2:06 AM, Peter Otten <__peter__ at web.de> wrote: > >>> import doctest > >>> example = doctest.Example( > ... "print('hello world')\n", > ... want="hello world\n") > >>> test = doctest.DocTest([example], {}, None, None, None, None) > >>> runner = doctest.DocTestRunner(verbose=True) > >>> runner.run(test) > Trying: > print('hello world') > Expecting: > hello world > ok > TestResults(failed=0, attempted=1) > ?and now how to do a multi line statement?. >>> import doctest >>> example = doctest.Example("print('hello')\nprint('world')",want="hello\nworld") >>> test = doctest.DocTest([example], {}, None, None, None, None) >>> runner = doctest.DocTestRunner(verbose=True) >>> runner.run(test) Trying: print('hello') print('world') Expecting: hello world ********************************************************************** Line 1, in None Failed example: print('hello') print('world') Exception raised: Traceback (most recent call last): File "/Users/vincentdavis/anaconda/envs/py35/lib/python3.5/doctest.py", line 1320, in __run compileflags, 1), test.globs) File "", line 1 print('hello') ^ SyntaxError: multiple statements found while compiling a single statement Vincent Davis From vincent at vincentdavis.net Tue Dec 8 09:36:41 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 8 Dec 2015 07:36:41 -0700 Subject: manually build a unittest/doctest object. In-Reply-To: <201512081430.tB8EUdZ8032414@fido.openend.se> References: <201512081430.tB8EUdZ8032414@fido.openend.se> Message-ID: On Tue, Dec 8, 2015 at 7:30 AM, Laura Creighton wrote: > >-- > >https://mail.python.org/mailman/listinfo/python-list > > Check out this: > https://pypi.python.org/pypi/pytest-ipynb > ?Thanks Laura, I think I read the descript as saying I could run untittests on source code from a jupyter notebook. Reading closer this seems like it will work. Not that I mind learning more about how doctests work ;-) Vincent Davis From rxjwg98 at gmail.com Tue Dec 8 09:59:56 2015 From: rxjwg98 at gmail.com (Robert) Date: Tue, 8 Dec 2015 06:59:56 -0800 (PST) Subject: Help on for loop understanding In-Reply-To: References: <5d02c61f-a979-4121-a9ae-764b44903156@googlegroups.com> <4f64bcda-15f2-4c6f-a279-b76330fb7f39@googlegroups.com> <56664210.7040007@lucidity.plus.com> Message-ID: <6df7b851-92d3-429e-ae6a-8ec7addff8b0@googlegroups.com> On Monday, December 7, 2015 at 10:24:09 PM UTC-5, Chris Angelico wrote: > On Tue, Dec 8, 2015 at 1:36 PM, Erik wrote: > > So, you can write your class's iterator to do anything that makes sense when > > someone says "for i in myclassinstance:". > > > > If your class is a subclass of a class ("is-a") that already has a defined > > iterator (such as a list or a dict) and the behaviour of that is correct for > > you, then you need to do nothing (you inherit that class's __iter__() > > method). > > > > If your class should iterate over an embedded object ("has-a") that already > > has a defined iterator, then your __iter__() method can just delegate to > > that object's iterator using something like: > > > > def __iter__(self): > > return iter(self.embedded_thing) > > Another great way to write an __iter__ method is as a generator. > > def __iter__(self): > yield "thing" > yield from self.things > yield "other thing" > > Like returning an embedded object's iterator, this saves you having to > write a __next__ method. The less work you do, the less bugs you get. > > ChrisA Thanks. One more question is here. I see the following code snippet. It can run as expected. That is, zeros array is iterable, but I don't see the iterator of it. And I do see some codes using np.nditer, but the following without it. seq = [ im for im in zeros((20,240,320), int)] 1. What difference for iterate with and without np.nditer? 2. How can I know one object whether it is iterable (only by testing?) From nam.anwar at gmail.com Tue Dec 8 10:03:27 2015 From: nam.anwar at gmail.com (Namrah Anwar) Date: Tue, 8 Dec 2015 20:03:27 +0500 Subject: Problem Message-ID: Dear Administration, I am Namrah Anwar writing to you from Pakistan. I downloaded Python version 3.5.1 and 2.7 and after installation at first, upon opening again it asked for Modify, repair or uninstall options. I tried to fix it but could not. Can you please help me out how to fix this and why it is asking every time for same option? Thanking you in anticipation. -- *Regards,Namrah Anwar* *PhD Student (Fellowship) - Cancer Biology - Agha Khan University-Karachi* *Masters in Health care Biotechnology (ASAB) NUST, Islamabad* *Pakistan.* From dalmia.anmol at gmail.com Tue Dec 8 10:08:49 2015 From: dalmia.anmol at gmail.com (Anmol Dalmia) Date: Tue, 8 Dec 2015 07:08:49 -0800 (PST) Subject: Can one use Python 3.4 lzma library to initialize file_reader for a 7z file? Message-ID: <65acc58c-463b-4615-8b09-cef6c0da6d18@googlegroups.com> Hello all. I am trying to read lines from a compressed xml file in a 7z format contained archive. The native lzma library of Python 3.4 allows to do so, but I am not sure it does so for 7z files. I explored many threads and found very unsatisfactory answers such as this one. https://groups.google.com/forum/#!search/lzma$207z/linux.debian.changes.devel/3vVvPIxnMuQ/3sPm5GEBbH4J Can anyone please clear this out to me once? Or if it doesn't, can anyone help on how to do it using any python or wrapped C functions? Thanks From lac at openend.se Tue Dec 8 10:09:22 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 08 Dec 2015 16:09:22 +0100 Subject: Problem In-Reply-To: References: Message-ID: <201512081509.tB8F9Mes002733@fido.openend.se> In a message of Tue, 08 Dec 2015 20:03:27 +0500, Namrah Anwar writes: >Dear Administration, > >I am Namrah Anwar writing to you from Pakistan. I downloaded Python version >3.5.1 and 2.7 and after installation at first, upon opening again it asked >for Modify, repair or uninstall options. I tried to fix it but could not. >Can you please help me out how to fix this and why it is asking every time >for same option? > >Thanking you in anticipation. > >-- > > >*Regards,Namrah Anwar* >*PhD Student (Fellowship) - Cancer Biology - Agha Khan University-Karachi* >*Masters in Health care Biotechnology (ASAB) NUST, Islamabad* >*Pakistan.* What OS version are you running? Laura Creighton From fabien.maussion at gmail.com Tue Dec 8 10:11:53 2015 From: fabien.maussion at gmail.com (Fabien) Date: Tue, 8 Dec 2015 16:11:53 +0100 Subject: Problem References: Message-ID: On 12/08/2015 04:03 PM, Namrah Anwar wrote: > Dear Administration, > > I am Namrah Anwar writing to you from Pakistan. I downloaded Python version > 3.5.1 and 2.7 and after installation at first, upon opening again it asked (snip) > -- *Regards,Namrah Anwar* *PhD Student (Fellowship) - Cancer Biology - I can see from your signature that you are going to use python for scientific purposes. I recommend to go directly for Anaconda: https://www.continuum.io/downloads Cheers, Fabien From lac at openend.se Tue Dec 8 10:25:57 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 08 Dec 2015 16:25:57 +0100 Subject: Problem In-Reply-To: References: Message-ID: <201512081525.tB8FPvPM003866@fido.openend.se> In a message of Tue, 08 Dec 2015 16:11:53 +0100, Fabien writes: >On 12/08/2015 04:03 PM, Namrah Anwar wrote: >> Dear Administration, >> >> I am Namrah Anwar writing to you from Pakistan. I downloaded Python version >> 3.5.1 and 2.7 and after installation at first, upon opening again it asked >(snip) >> -- *Regards,Namrah Anwar* *PhD Student (Fellowship) - Cancer Biology - > >I can see from your signature that you are going to use python for >scientific purposes. I recommend to go directly for Anaconda: > >https://www.continuum.io/downloads > >Cheers, > >Fabien That is a very good idea. Laura From __peter__ at web.de Tue Dec 8 10:31:39 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2015 16:31:39 +0100 Subject: manually build a unittest/doctest object. References: Message-ID: Vincent Davis wrote: > On Tue, Dec 8, 2015 at 2:06 AM, Peter Otten <__peter__ at web.de> wrote: > >> >>> import doctest >> >>> example = doctest.Example( >> ... "print('hello world')\n", >> ... want="hello world\n") >> >>> test = doctest.DocTest([example], {}, None, None, None, None) >> >>> runner = doctest.DocTestRunner(verbose=True) >> >>> runner.run(test) >> Trying: >> print('hello world') >> Expecting: >> hello world >> ok >> TestResults(failed=0, attempted=1) >> > > ?and now how to do a multi line statement?. doctest doesn't do tests with multiple *statements.* A docstring like """ >>> x = 42 >>> print(x) 42 """ is broken into two examples: >> import doctest >>> p = doctest.DocTestParser() >>> doctest.Example.__repr__ = lambda self: "Example(source={0.source!r}, want={0.want!r})".format(self) >>> p.get_examples(""" ... >>> x = 42 ... >>> print(x) ... 42 ... """) [Example(source='x = 42\n', want=''), Example(source='print(x)\n', want='42\n')] From dalmia.anmol at gmail.com Tue Dec 8 11:52:06 2015 From: dalmia.anmol at gmail.com (Anmol Dalmia) Date: Tue, 8 Dec 2015 22:22:06 +0530 Subject: Reading lines of text from 7z compressed files in Python Message-ID: Hello all. I am trying to read a compressed xml file line by line under the 7z format. I found an answer to a related question here: http://stackoverflow.com/questions/20104460/how-to-read-from-a-text-file-compressed-with-7z-in-python I wish to use the native LZMA library of Python 3.4 for faster performance than any other third- party packages. Is it possible to do so? Thanks -- With Regards ANMOL DALMIA M Tech (Dual) Information Security, 2017 National Institute of Technology, Rourkela, India From rr.codeproject at outlook.com Tue Dec 8 12:56:51 2015 From: rr.codeproject at outlook.com (Raheel Rao) Date: Tue, 8 Dec 2015 12:56:51 -0500 Subject: Python Script - Windows Task Scheduler - Logging In-Reply-To: References: Message-ID: Update: I was able to figure this one out eventually. I had to put path of where the script is in "Start in" section of my task. Consider this ticket 'closed' :) > Date: Mon, 7 Dec 2015 23:53:10 +0000 > From: rr.codeproject at outlook.com > To: python-list at python.org > Subject: Python Script - Windows Task Scheduler - Logging > > Hello there,I created a python script that connects to an ftp and downloads files to a specifed folder and logs each event in a log file. This script works perfectly fine as i want it to however when i put this in a task scheduler, the script runs and downloads the file just fine except that there is no log created. Any suggestions? I remember task scheduler have a bug where you have to put something in "start in". Have been searching froums but so far no luck. Thanks in advance! > > -- > https://mail.python.org/mailman/listinfo/python-list From chrisandsue61 at hotmail.com Tue Dec 8 12:59:12 2015 From: chrisandsue61 at hotmail.com (Chris Harwood) Date: Tue, 8 Dec 2015 17:59:12 +0000 Subject: tkinter Message-ID: Hi, Python ? 3.5.0 Documentation ? The Python Standard Library ? 25. Graphical User Interfaces with Tk ? states that "You can check that tkinter is properly installed on your system by running python -m tkinter from the command line; this should open a window demonstrating a simple Tk interface." Having recently installed Python 3.5.0 I find that python -m tkinter produces: 'python' is not recognised as an internal or external command, operable program or batch file. Can you help, please? Thank you, Chris Harwood. From anthony at cajuntechie.org Tue Dec 8 13:21:43 2015 From: anthony at cajuntechie.org (Anthony Papillion) Date: Tue, 8 Dec 2015 12:21:43 -0600 Subject: Getting data out of Mozilla Thunderbird with Python? Message-ID: <56671FB7.7090104@cajuntechie.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Hello Everyone, I have a TON of email (years) stored in my Thunderbird. My backup strategy for the last few years has been to periodically dump it all in a tar file, encrypt that tar file, and move it up to the cloud. That way, if my machine ever crashes, I don't lose years of email. But I've been thinking about bringing Python into the mix to build a bridge between Thunderbird and SQLite or MySQL (probably sqlite) where all mail would be backed up to a database where I could run analytics against it and search it more effectively. I'm looking for a way to get at the mail stored in Thunderbird using Python and, so far, I can't find anything. I did find the mozmail package but it seems to be geared more towards testing and not really the kind of use I need. Can anyone suggest anything? Many Thanks, Anthony Papillion - -- Phone: 1.845.666.1114 Skype: cajuntechie PGP Key: 0x028ADF7453B04B15 Fingerprint: C5CE E687 DDC2 D12B 9063 56EA 028A DF74 53B0 4B15 -----BEGIN PGP SIGNATURE----- iQIcBAEBCgAGBQJWZx+3AAoJEAKK33RTsEsVVa8QAKf1AmFdJsi4/b08vpkfwP3c akGV98EuZzEva29jr8nnfXGgqw7xD/nDjMyLzuO0/q4Kn7eKpEnxkcGDLSbDgxaW O8kD5eALHCVlUp9p/h7RMBBAyZ4mH8YC6qwvd5SWtH0TIMR7ClcWmDYwPF1Ahk7n NAFvTsMl8PSnhcIoWHE4vebN4wHR8gZAxOLI8WVPA2BbER64EXiL00nWBav6UDN5 NUosAAVa549rrH0ibEf7Lada63DRTHCYnESxNIkAAHIO0z69WjnfZQ8gmmGFhuaW AZzqYV5pIhdRnvrwjCQ06LtUNtz/qPqLbLSWF0hA6lwPKqzNum9EdvS4c1xjcXsU KpOCTmJXy40x1Oi8h+yT6PGiDxt5VCHCdN8ppToI3HY5pYmoiPgWszJzrqYMz7hz ruhNFAksKNUSI9QQupYcPw6oKQdnoGWmBH1yvGlZqeZuIxhGEv87oqRISE4NRQLe yL4aDebwXdDgBzIZvFOFy2W4L43jdravg2/LliSC18iCUKBnIpWhazy7NZHw6h55 h3QP84DeuB/9tPLQUZF+BEJm3I+V8WfSKVVnsSbk/n/chHgYpWnu+h/wpD6lx43x y0lPJm0ni5LeQM1bK4TsIXVEAOzl8UaOwn/VUG7P6Jnt6VEqvQutWZ0/WEeP1nIX M7+e9hLlQWtlEbl6ud1K =Dz7N -----END PGP SIGNATURE----- From PointedEars at web.de Tue Dec 8 13:42:56 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 08 Dec 2015 19:42:56 +0100 Subject: Getting data out of Mozilla Thunderbird with Python? References: Message-ID: <4306369.OX057VMHEH@PointedEars.de> Anthony Papillion wrote: > -----BEGIN PGP SIGNED MESSAGE----- Please don?t do that again. > I have a TON of email (years) stored in my Thunderbird. My backup > strategy for the last few years has been to periodically dump it all > in a tar file, encrypt that tar file, and move it up to the cloud. > That way, if my machine ever crashes, I don't lose years of email. > > But I've been thinking about bringing Python into the mix to build a > bridge between Thunderbird and SQLite or MySQL (probably sqlite) where > all mail would be backed up to a database where I could run analytics > against it and search it more effectively. > > I'm looking for a way to get at the mail stored in Thunderbird using > Python and, so far, I can't find anything. I did find the mozmail > package but it seems to be geared more towards testing and not really > the kind of use I need. > > Can anyone suggest anything? Yes. (Please never ask that question again: ) Thunderbird uses the mbox format to store both e-mails and news messages. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Tue Dec 8 14:02:10 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 08 Dec 2015 20:02:10 +0100 Subject: Accessing container's methods References: Message-ID: <5516674.oipO6xLiNU@PointedEars.de> Erik wrote: ^^^^ Please fix, Erik #75656. > On 07/12/15 18:10, Tony van der Hoff wrote: >> A highly contrived example, where I'm setting up an outer class in a >> Has-a relationship, containing a number of Actors. The inner class needs >> to access a method of the outer class; here the method get_name. > > Generally, an object should not need to know which container it's in NAK. All kinds of objects already "know" which container they are in. > (let alone its "index" or "key" in that container). That is a different issue. > Amongst other things, you can't put the object into multiple containers You could if you made it a list of container references. > which might be organised differently and you are asking for bugs where the > container and the object get out of sync WRT just where the object is in > the container It is the container?s job to make sure that this does not happen. >> Can anyone please advise me on how to achieve this magic? > > As you can't sensibly put the object into more than one container at a > time anyway, You can. Quickhack: class Child: self._parents = [] def add_to_parent (self, parent): self._parents.append(parent) self._parents = list(set(self._parents)) def get_parents (self) return self._parents class Parent: self._children = [] def add_child (self, child): self._children.append(child) child.add_to_parent(self) | >>> p = Parent() | >>> c = Child() | >>> p.add_child(c) | >>> p2 = Parent() | >>> p2.add_child(c) | >>> c.get_parents() | [p, p2] ?As a child, I want to know who my parents are.? Certainly you will not deny the validity of that user story ;-) -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From vincent.vande.vyvre at telenet.be Tue Dec 8 14:54:25 2015 From: vincent.vande.vyvre at telenet.be (Vincent Vande Vyvre) Date: Tue, 8 Dec 2015 20:54:25 +0100 Subject: Accessing container's methods In-Reply-To: <5516674.oipO6xLiNU@PointedEars.de> References: <5516674.oipO6xLiNU@PointedEars.de> Message-ID: <56673571.1050507@telenet.be> Le 08/12/2015 20:02, Thomas 'PointedEars' Lahn a ?crit : > Erik wrote: > ^^^^ > Please fix, Erik #75656. > >> On 07/12/15 18:10, Tony van der Hoff wrote: >>> A highly contrived example, where I'm setting up an outer class in a >>> Has-a relationship, containing a number of Actors. The inner class needs >>> to access a method of the outer class; here the method get_name. >> Generally, an object should not need to know which container it's in > NAK. All kinds of objects already "know" which container they are in. > >> (let alone its "index" or "key" in that container). > That is a different issue. > >> Amongst other things, you can't put the object into multiple containers > You can. Quickhack: > > class Child: > self._parents = [] > > def add_to_parent (self, parent): > self._parents.append(parent) > self._parents = list(set(self._parents)) > > def get_parents (self) > return self._parents > > class Parent: > self._children = [] > ..... I thing you should test your code before post it. >>> class Child: ... self.parents = [] ... Traceback (most recent call last): File "", line 1, in File "", line 2, in Child NameError: name 'self' is not defined From breamoreboy at yahoo.co.uk Tue Dec 8 15:30:18 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 8 Dec 2015 20:30:18 +0000 Subject: Accessing container's methods In-Reply-To: <5516674.oipO6xLiNU@PointedEars.de> References: <5516674.oipO6xLiNU@PointedEars.de> Message-ID: On 08/12/2015 19:02, Thomas 'PointedEars' Lahn wrote: > Erik wrote: > ^^^^ > Please fix, Erik #75656. > Please fix what? -- 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 Tue Dec 8 15:31:20 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 8 Dec 2015 20:31:20 +0000 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: <4306369.OX057VMHEH@PointedEars.de> References: <4306369.OX057VMHEH@PointedEars.de> Message-ID: On 08/12/2015 18:42, Thomas 'PointedEars' Lahn wrote: > Anthony Papillion wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- > > Please don?t do that again. > Says who? -- 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 lucidity.plus.com Tue Dec 8 17:37:46 2015 From: python at lucidity.plus.com (Erik) Date: Tue, 8 Dec 2015 22:37:46 +0000 Subject: Accessing container's methods In-Reply-To: <5516674.oipO6xLiNU@PointedEars.de> References: <5516674.oipO6xLiNU@PointedEars.de> Message-ID: <56675BBA.6000806@lucidity.plus.com> Annoyingly, there seemed to be no responses to the original question when I wrote that and then shortly after, I saw all the others (and we all pretty much said the same thing - so I'm not sure why I was singled out for special attention ;)). On 08/12/15 19:02, Thomas 'PointedEars' Lahn wrote: > Erik wrote: > ^^^^ > Please fix, Erik #75656. Fixed(*) Thomas 'PointerEars', you have chosen to selectively quote snippets of code and comments out of context, so I think it's futile to respond to those arguments individually. The original request (if you read it) was to return a string that said, essentially, "I am element 2 of 3 in my container". You posted a "Quickhack" (which, to be fair, is an accurate description) which is incomplete, has errors and makes no sense in the context of the original question. We all know we can create a list in Python (of parent objects or whatever), but I think that if you expanded on that class a bit more (methods for the containers to update the contained objects on just what their index/key is etc) that you'll soon realise it's not a scalable option. Also, WRT the original question, what is the method supposed to return now? "I am element 0 of 3 in container , key 'bar' of ('bar', 'foo', 'spam') in container "? Just curious. I'm interested in this response though: >> Generally, an object should not need to know which container it's in > > NAK. All kinds of objects already "know" which container they are in. Please elucidate. Examples from the standard library would be interesting. E. (*) In the sense that it's not going to change ;) From PointedEars at web.de Tue Dec 8 17:51:10 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 08 Dec 2015 23:51:10 +0100 Subject: Accessing container's methods References: <5516674.oipO6xLiNU@PointedEars.de> Message-ID: <3619885.mg2BhAsQCr@PointedEars.de> Vincent Vande Vyvre wrote: > Le 08/12/2015 20:02, Thomas 'PointedEars' Lahn a ?crit : >> Erik wrote: >>> Amongst other things, you can't put the object into multiple containers >> You can. Quickhack: ^^^^^^^^^ >> class Child: >> self._parents = [] >> >> def add_to_parent (self, parent): >> self._parents.append(parent) >> self._parents = list(set(self._parents)) >> >> def get_parents (self) >> return self._parents >> >> class Parent: >> self._children = [] >> ..... > I thing you should test your code before post it. I _think_ you should read postings more carefully before replying to them. > >>> class Child: > ... self.parents = [] > ... > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in Child > NameError: name 'self' is not defined Can be fixed easily by omitting ?self.? there; likewise in Parent. (In other programming languages I know, you need to refer to the class/instance explicitly to which you add attributes/properties.) -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Tue Dec 8 17:52:03 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 08 Dec 2015 23:52:03 +0100 Subject: Accessing container's methods References: <5516674.oipO6xLiNU@PointedEars.de> Message-ID: <8148791.79CPUYHJkR@PointedEars.de> Mark Lawrence wrote: > On 08/12/2015 19:02, Thomas 'PointedEars' Lahn wrote: >> Erik wrote: >> ^^^^ >> Please fix, Erik #75656. > > Please fix what? You are not ready for the answer yet. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Tue Dec 8 17:58:42 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 08 Dec 2015 23:58:42 +0100 Subject: filter a list of strings References: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> Message-ID: <2598115.t018ozAsXX@PointedEars.de> Mark Lawrence wrote: > On 03/12/2015 01:15, c.buhtz at posteo.jp wrote: >> I would like to know how this could be done more elegant/pythonic. >> >> I have a big list (over 10.000 items) with strings (each 100 to 300 >> chars long) and want to filter them. >> >> list = ..... >> [?] > > targets = ['Banana', 'Car'...] > for item in list[:]: > for target in targets: > if target in item: > list.remove(item) > >> btw: Is it correct to iterate over a copy (list[:]) of that string list >> and not the original one? > > Absolutely :) However, ?list? is a built-in class/constructor that would be overwritten this way. One should choose another identifier than ?list? for one?s variables. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From breamoreboy at yahoo.co.uk Tue Dec 8 17:59:55 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 8 Dec 2015 22:59:55 +0000 Subject: Accessing container's methods In-Reply-To: <8148791.79CPUYHJkR@PointedEars.de> References: <5516674.oipO6xLiNU@PointedEars.de> <8148791.79CPUYHJkR@PointedEars.de> Message-ID: On 08/12/2015 22:52, Thomas 'PointedEars' Lahn wrote: > Mark Lawrence wrote: > >> On 08/12/2015 19:02, Thomas 'PointedEars' Lahn wrote: >>> Erik wrote: >>> ^^^^ >>> Please fix, Erik #75656. >> >> Please fix what? > > You are not ready for the answer yet. > I'll be all pointed ears when you actually manage to provide an answer to anything here. -- 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 Tue Dec 8 18:41:20 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 8 Dec 2015 16:41:20 -0700 Subject: Accessing container's methods In-Reply-To: <56675BBA.6000806@lucidity.plus.com> References: <5516674.oipO6xLiNU@PointedEars.de> <56675BBA.6000806@lucidity.plus.com> Message-ID: On Tue, Dec 8, 2015 at 3:37 PM, Erik wrote: > On 08/12/15 19:02, Thomas 'PointedEars' Lahn wrote: >> >> Erik wrote: >> ^^^^ >> Please fix, Erik #75656. > > > Fixed(*) [SNIP] > (*) In the sense that it's not going to change ;) Then I think you mean "Working as Intended", not "Fixed". B-) From rosuav at gmail.com Tue Dec 8 20:04:47 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 9 Dec 2015 12:04:47 +1100 Subject: Accessing container's methods In-Reply-To: References: <5516674.oipO6xLiNU@PointedEars.de> <56675BBA.6000806@lucidity.plus.com> Message-ID: On Wed, Dec 9, 2015 at 10:41 AM, Ian Kelly wrote: > On Tue, Dec 8, 2015 at 3:37 PM, Erik wrote: >> On 08/12/15 19:02, Thomas 'PointedEars' Lahn wrote: >>> >>> Erik wrote: >>> ^^^^ >>> Please fix, Erik #75656. >> >> >> Fixed(*) > > [SNIP] > >> (*) In the sense that it's not going to change ;) > > Then I think you mean "Working as Intended", not "Fixed". B-) No, he's doing a brilliant equivocation on the word 'fixed'. Once you use superglue on something, it is fixed in place. Win for Erik. ChrisA From cs at zip.com.au Tue Dec 8 20:51:22 2015 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 9 Dec 2015 12:51:22 +1100 Subject: storing test logs under /var/log/ In-Reply-To: References: Message-ID: <20151209015122.GA76853@cskk.homeip.net> On 08Dec2015 13:24, Peter Otten <__peter__ at web.de> wrote: >Ganesh Pal wrote: >[Cameron Simpson:] >>> Finally. sys.exit accepts an integer, not a string. > >> Most of code uses sys.exit("some error message") , I did notice >> that the error message is not displayed by sys .exit("some error >> message") , do u mean that using string is not advisable with >> sys.exit ? > >Cameron is wrong (he's probably coming from the C side of things). Correct on both counts. >You can invoke sys.exit() with arbitrary objects: [...] > Exit the interpreter by raising SystemExit(status). > If the status is omitted or None, it defaults to zero (i.e., success). > If the status is an integer, it will be used as the system exit status. > If it is another kind of object, it will be printed and the system > exit status will be one (i.e., failure). I Did Not Know That! It says "printed". To stderr or stdout? If it isn't stderr, I think I will avoid this anyway. >> How to I display error messages with sys.exit then ? >Wrong question; if you want to use sys.exit() in a way similar to C display >the error message first and invoke sys.exit() afterwards with a numerical >argument. Indeed. My general habit is that fatal errors (when the code decides that they are fatal) print or log an error message and set a suitable failure flag. Which is then caught later somewhere suitable. Cheers, Cameron Simpson From cs at zip.com.au Tue Dec 8 23:00:37 2015 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 9 Dec 2015 15:00:37 +1100 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: <56671FB7.7090104@cajuntechie.org> References: <56671FB7.7090104@cajuntechie.org> Message-ID: <20151209040037.GA22043@cskk.homeip.net> On 08Dec2015 12:21, Anthony Papillion wrote: >I have a TON of email (years) stored in my Thunderbird. [...] >I've been thinking about bringing Python into the mix to build a >bridge between Thunderbird and SQLite or MySQL (probably sqlite) where >all mail would be backed up to a database where I could run analytics >against it and search it more effectively. > >I'm looking for a way to get at the mail stored in Thunderbird using >Python and, so far, I can't find anything. I did find the mozmail >package but it seems to be geared more towards testing and not really >the kind of use I need. > >Can anyone suggest anything? The local messges folders in Thunderbird are plain old mbox files IIRC. You can read these with the email.* modules and analyse them to your heart's content. So I'd just write a Python program to read a single mbox file and break it into messages, make each one into an email Message object, and the process as you see fit. Then point it at each of the TBird mbox files in turn. Cheers, Cameron Simpson From ashwath at nanoheal.com Tue Dec 8 23:46:26 2015 From: ashwath at nanoheal.com (ashwath at nanoheal.com) Date: Tue, 08 Dec 2015 21:46:26 -0700 Subject: Image download failure from wget.download function. Message-ID: <20151208214626.d600875ec5143fcc53c5b00e1a6550c2.443987524e.mailapi@email23.secureserver.net> Hi I am trying to download the image from a URL, I am able to download a file but after downloading if I try to open the image it says file format is corrupted or damaged. I use this function to download the image - wget.download('http:////realpython.com//learn//python-first-steps//images//pythonlogo.jpg') For all the other URLs also same image format failure is happening. So can you please check and lemme know the reason for failure. Thank you Ashwath From ganesh1pal at gmail.com Wed Dec 9 01:16:36 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 9 Dec 2015 11:46:36 +0530 Subject: storing test logs under /var/log/ In-Reply-To: References: <20151203081723.GA48121@cskk.homeip.net> Message-ID: > Wrong question; if you want to use sys.exit() in a way similar to C display > the error message first and invoke sys.exit() afterwards with a numerical > argument. > > -- oh ok , got it thanks :) From steve+comp.lang.python at pearwood.info Wed Dec 9 02:38:08 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 09 Dec 2015 18:38:08 +1100 Subject: Shadowing built-ins [was Re: filter a list of strings] References: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> <2598115.t018ozAsXX@PointedEars.de> Message-ID: <5667da63$0$14486$c3e8da3@news.astraweb.com> On Wednesday 09 December 2015 09:58, Thomas 'PointedEars' Lahn wrote: > Mark Lawrence wrote: > >> On 03/12/2015 01:15, c.buhtz at posteo.jp wrote: >>> I would like to know how this could be done more elegant/pythonic. >>> >>> I have a big list (over 10.000 items) with strings (each 100 to 300 >>> chars long) and want to filter them. >>> >>> list = ..... >>> [?] [...] > However, ?list? is a built-in class/constructor that would be overwritten > this way. One should choose another identifier than ?list? for one?s > variables. Correct, well mostly correct. The original built-in list is *not* overridden, as such, but shadowed: it still exists, but access to it is blocked by the local variable "list". The list *type* still exists, only the *name* list is shadowed. So you can easily recover from accidentally shadowing the name by deleting the local: del list To beginners, accidental shadowing of built-ins is a serious source of confusion. But to experts, intentional shadowing can be useful. There's nothing wrong with (say): def sort_and_pop(list): list.sort() list.pop(0) Yes, the local "list" shadows the built-in list. So what? More usefully, one can monkey-patch a module by shadowing a built-in in that module: # Python 3 only. import builtins def print(*args, **kwargs): log_something() builtins.print(*args, **kwargs) -- Steve From steve+comp.lang.python at pearwood.info Wed Dec 9 02:43:35 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 09 Dec 2015 18:43:35 +1100 Subject: META email [was Re: Getting data out of Mozilla Thunderbird with Python?] References: <4306369.OX057VMHEH@PointedEars.de> Message-ID: <5667dba7$0$14486$c3e8da3@news.astraweb.com> On Wednesday 09 December 2015 05:42, Thomas 'PointedEars' Lahn wrote: [snip] Thomas, your sig says: Please do not cc me. / Bitte keine Kopien per E-Mail. but you have a Reply-To set. That implies that you want replies to be sent directly to you by email, not to the list or newsgroup. Is that really what you want? That seems incompatible with your signature. Which is correct? -- Steve From auriocus at gmx.de Wed Dec 9 03:03:46 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Wed, 9 Dec 2015 09:03:46 +0100 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: References: Message-ID: Am 08.12.15 um 19:21 schrieb Anthony Papillion: > I have a TON of email (years) stored in my Thunderbird. My backup > strategy for the last few years has been to periodically dump it all > in a tar file, encrypt that tar file, and move it up to the cloud. > That way, if my machine ever crashes, I don't lose years of email. > > But I've been thinking about bringing Python into the mix to build a > bridge between Thunderbird and SQLite or MySQL (probably sqlite) where > all mail would be backed up to a database where I could run analytics > against it and search it more effectively. > > I'm looking for a way to get at the mail stored in Thunderbird using > Python and, so far, I can't find anything. I did find the mozmail > package but it seems to be geared more towards testing and not really > the kind of use I need. You have several options. 1) As noted before, Thunderbird ususally stores mail in mbox format, which you can read and parse. However it keeps an extra index file (.msf) to track deleted messages etc. Until you "compact" the folders, the messages are not deleted in the mbox file 2) You can configure it to use maildir instead. Maildir is a directory where every mail is stored in a single file. That might be easier to parse and much faster to access. 3) Are you sure that you want to solve the problem using Python? Thunderbird has excellent filters and global full text search (stored in sqlite, btw). You can instruct it to archive mails, which means it creates a folder for each year - once created for a past year, that folder will never change. This is how I do my mail backup, and these folders are backed up by my regular backup (TimeMachine). You could also try to open the full text index with sqlite and run some query on it. 4) Yet another option using Thunderbird alone is IMAP. If you can either use a commercial IMAP server, have your own server in the cloud or even write an IMAP server using Python, then Thunderbird can access/manipulate the mail there as a usual folder. 5) There are converters like Hypermail or MHonArc to create HTML archives of mbox email files for viewing in a browser Christian From rosuav at gmail.com Wed Dec 9 04:44:44 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 9 Dec 2015 20:44:44 +1100 Subject: tkinter In-Reply-To: References: Message-ID: On Wed, Dec 9, 2015 at 4:59 AM, Chris Harwood wrote: > Having recently installed Python 3.5.0 I find that python -m tkinter produces: > 'python' is not recognised as an internal or external command, operable program or batch file. Try instead: python3 -m tkinter But it might mean that you didn't put Python on yout $PATH. ChrisA From __peter__ at web.de Wed Dec 9 04:57:34 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Dec 2015 10:57:34 +0100 Subject: Image download failure from wget.download function. References: <20151208214626.d600875ec5143fcc53c5b00e1a6550c2.443987524e.mailapi@email23.secureserver.net> Message-ID: ashwath at nanoheal.com wrote: > I am trying to download the image from a URL, I am able to download a > file but after downloading if I try to open the image it says file format > is corrupted or damaged. What version of python are you using? Where did you get the wget libary? > I use this function to download the image - > wget.download('http:////realpython.com//learn//python-first-steps//images//pythonlogo.jpg') The above snippet will not work because all slashes are duplicated. Please post a small but runnable script. > For all the other URLs also same image format failure is happening. How do you "open" the images? Do you mean you try to view them in an image viewer or are you reading the contents with Python? If the latter, show us your code for that, too. From steve at pearwood.info Wed Dec 9 06:11:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Dec 2015 22:11:20 +1100 Subject: Getting data out of Mozilla Thunderbird with Python? References: Message-ID: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> On Wed, 9 Dec 2015 07:03 pm, Christian Gollwitzer wrote: > 1) As noted before, Thunderbird ususally stores mail in mbox format, > which you can read and parse. However it keeps an extra index file > (.msf) to track deleted messages etc. Until you "compact" the folders, > the messages are not deleted in the mbox file > > 2) You can configure it to use maildir instead. Maildir is a directory > where every mail is stored in a single file. That might be easier to > parse and much faster to access. Maildir is also *much* safer too. With mbox, a single error when writing email to the mailbox will likely corrupt *all* emails from that point on, so potentially every email in the mailbox. With maildir, a single error when writing will, at worst, corrupt one email. Thanks Mozilla, for picking the *less* efficient and *more* risky format as the default. Good choice! > 3) Are you sure that you want to solve the problem using Python? > Thunderbird has excellent filters and global full text search (stored in > sqlite, btw). Sqlite is unsafe on Linux systems if you are using ntfs. I have had no end of database corruption with Firefox and Thunderbird due to this, although in fairness I haven't had any problems for a year or so now. -- Steven From zachary.ware+pylist at gmail.com Wed Dec 9 08:56:19 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 9 Dec 2015 07:56:19 -0600 Subject: tkinter In-Reply-To: References: Message-ID: On Dec 9, 2015 3:36 AM, "Chris Harwood" wrote: > > Hi, > > Python ? 3.5.0 Documentation ? The Python Standard Library ? 25. Graphical User Interfaces with Tk ? states that "You can check that tkinter is properly installed on your system by running python -m tkinter from the command line; this should open a window demonstrating a simple Tk interface." > > Having recently installed Python 3.5.0 I find that python -m tkinter produces: > 'python' is not recognised as an internal or external command, operable program or batch file. > > Can you help, please? Try "py -3.5 -m tkinter" instead. On Windows, you have tkinter unless you deselected it when you installed Python. For future reference, it's very helpful to provide your OS and OS version when asking questions like this; I'm just assuming you're on Windows since that's the default "that's not on PATH" message. Hope this helps, -- Zach (On a phone) From mr.eightnoteight at gmail.com Wed Dec 9 09:06:52 2015 From: mr.eightnoteight at gmail.com (srinivas devaki) Date: Wed, 9 Dec 2015 19:36:52 +0530 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Dec 9, 2015 4:45 PM, "Steven D'Aprano" wrote: > > Maildir is also *much* safer too. With mbox, a single error when writing > email to the mailbox will likely corrupt *all* emails from that point on, > so potentially every email in the mailbox. With maildir, a single error > when writing will, at worst, corrupt one email. > may be with frequent backup of mbox file and storing checksum to each email will be faster and safe too. I wonder if they already do that. From rosuav at gmail.com Wed Dec 9 09:15:15 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 10 Dec 2015 01:15:15 +1100 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: References: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Dec 10, 2015 at 1:06 AM, srinivas devaki wrote: > On Dec 9, 2015 4:45 PM, "Steven D'Aprano" wrote: >> >> Maildir is also *much* safer too. With mbox, a single error when writing >> email to the mailbox will likely corrupt *all* emails from that point on, >> so potentially every email in the mailbox. With maildir, a single error >> when writing will, at worst, corrupt one email. >> > > may be with frequent backup of mbox file and storing checksum to each email > will be faster and safe too. > I wonder if they already do that. Yes, because we all know that frequent checking is better than prevention. That's why MySQL's myisamchk command makes it so much better than PostgreSQL's transactional DDL. ChrisA From hemla21 at gmail.com Wed Dec 9 09:23:23 2015 From: hemla21 at gmail.com (Heli) Date: Wed, 9 Dec 2015 06:23:23 -0800 (PST) Subject: 3D numpy array subset Message-ID: <2e1a80e9-cd0a-46b5-a8c0-97f208f71f54@googlegroups.com> Dear all, I am reading a dataset from a HDF5 file using h5py. my datasets are 3D. Then I will need to check if another 3d numpy array is a subset of this 3D array i am reading from the file. In general, is there any way to check if two 3d numpy arrays have intersections and if so, get the indices of the intersection area. By intersection, I exactly mean the intersection definition used in set theory. Thanks in Advance for your help, From sivan at vitakka.co Wed Dec 9 09:35:23 2015 From: sivan at vitakka.co (Sivan Greenberg) Date: Wed, 9 Dec 2015 16:35:23 +0200 Subject: filter a list of strings In-Reply-To: <2598115.t018ozAsXX@PointedEars.de> References: <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> <2598115.t018ozAsXX@PointedEars.de> Message-ID: That might also work: new_list = [i for i in the_list if i not in targets] # given you have no special requirements for the selection # out of 'targets' -Sivan On Wed, Dec 9, 2015 at 12:58 AM, Thomas 'PointedEars' Lahn < PointedEars at web.de> wrote: > Mark Lawrence wrote: > > > On 03/12/2015 01:15, c.buhtz at posteo.jp wrote: > >> I would like to know how this could be done more elegant/pythonic. > >> > >> I have a big list (over 10.000 items) with strings (each 100 to 300 > >> chars long) and want to filter them. > >> > >> list = ..... > >> [?] > > > > targets = ['Banana', 'Car'...] > > for item in list[:]: > > for target in targets: > > if target in item: > > list.remove(item) > > > >> btw: Is it correct to iterate over a copy (list[:]) of that string list > >> and not the original one? > > > > Absolutely :) > > However, ?list? is a built-in class/constructor that would be overwritten > this way. One should choose another identifier than ?list? for one?s > variables. > > -- > PointedEars > > Twitter: @PointedEars2 > Please do not cc me. / Bitte keine Kopien per E-Mail. > -- > https://mail.python.org/mailman/listinfo/python-list > -- Sivan Greenberg Co founder & CTO Vitakka Consulting From hemla21 at gmail.com Wed Dec 9 11:06:59 2015 From: hemla21 at gmail.com (Heli) Date: Wed, 9 Dec 2015 08:06:59 -0800 (PST) Subject: np.searchSorted over 2D array Message-ID: <2b660168-3322-4bf6-bd8b-2dc846a3a874@googlegroups.com> Dear all, I need to check whether two 2d numpy arrays have intersections and if so I will need to have the cell indices of the intersection. By intersection, I exactly mean the intersection definition used in set theory. I will give an example of what I need to do: a=[[0,1,2],[3,4,5],[6,7,8]] b=[[0,1,2],[3,4,5]] I would like to check whether b is subset of a and then get the indices in a where b matches. cellindices=[[True,True,True],[True,True,True],[False,False,False]] What is the best way to do this in numpy? Thanks in Advance for your help, From __peter__ at web.de Wed Dec 9 11:36:31 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Dec 2015 17:36:31 +0100 Subject: np.searchSorted over 2D array References: <2b660168-3322-4bf6-bd8b-2dc846a3a874@googlegroups.com> Message-ID: Heli wrote: [Please don't open a new thread for the same problem] > I need to check whether two 2d numpy arrays have intersections and if so I > will need to have the cell indices of the intersection. > > By intersection, I exactly mean the intersection definition used in set > theory. > > I will give an example of what I need to do: > > a=[[0,1,2],[3,4,5],[6,7,8]] > b=[[0,1,2],[3,4,5]] > > I would like to check whether b is subset of a and then get the indices in > a where b matches. > > cellindices=[[True,True,True],[True,True,True],[False,False,False]] > > What is the best way to do this in numpy? Providing an example is an improvement over your previous post, but to me it's still not clear what you want. >>> functools.reduce(lambda x, y: x | y, (a == i for i in b.flatten())) array([[ True, True, True], [ True, True, True], [False, False, False]], dtype=bool) produces the desired result for the example input, but how do you want to handle repeating numbers as in >>> a = numpy.array([[0,1,2],[3,4,5],[3, 2, 1]]) >>> functools.reduce(lambda x, y: x | y, (a == i for i in b.flatten())) array([[ True, True, True], [ True, True, True], [ True, True, True]], dtype=bool) ? Try to be clear about your requirement, describe it in english and provide a bit of context. You might even write a solution that doesn't use numpy and ask for help in translating it. At the very least we need more/better examples. From invalid at invalid.invalid Wed Dec 9 12:25:13 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 9 Dec 2015 17:25:13 +0000 (UTC) Subject: Getting data out of Mozilla Thunderbird with Python? References: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2015-12-09, Steven D'Aprano wrote: > Thanks Mozilla, for picking the *less* efficient and *more* risky format as > the default. Good choice! At least they picked a standard format as the default and gave you the option to use a different standard format (cf. Microsoft and Outlook). -- Grant Edwards grant.b.edwards Yow! Are you the at self-frying president? gmail.com From ictezy at gmail.com Wed Dec 9 12:49:26 2015 From: ictezy at gmail.com (ICT Ezy) Date: Wed, 9 Dec 2015 09:49:26 -0800 (PST) Subject: Python variable assigning problems... Message-ID: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Pl refer question which attached image here: link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 From ictezy at gmail.com Wed Dec 9 12:51:18 2015 From: ictezy at gmail.com (ICT Ezy) Date: Wed, 9 Dec 2015 09:51:18 -0800 (PST) Subject: How to connect the MYSQL database to Python program? Message-ID: Pl explain me how to connect the MYSQL database to Python program? From joel.goldstick at gmail.com Wed Dec 9 12:51:29 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 9 Dec 2015 12:51:29 -0500 Subject: Python variable assigning problems... In-Reply-To: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: On Wed, Dec 9, 2015 at 12:49 PM, ICT Ezy wrote: > Pl refer question which attached image here: > > link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From joel.goldstick at gmail.com Wed Dec 9 12:52:29 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 9 Dec 2015 12:52:29 -0500 Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: On Wed, Dec 9, 2015 at 12:51 PM, Joel Goldstick wrote: > > > On Wed, Dec 9, 2015 at 12:49 PM, ICT Ezy wrote: > >> Pl refer question which attached image here: >> >> link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > > You have a link to somewhere that needs permission to view. Why not just ask your question here? Many people won't follow links, and anyway, no one can follow yours > > -- > Joel Goldstick > http://joelgoldstick.com/stats/birthdays > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From rosuav at gmail.com Wed Dec 9 12:57:45 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 10 Dec 2015 04:57:45 +1100 Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: Message-ID: On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > Pl explain me how to connect the MYSQL database to Python program? You start by looking for a module that lets you do that. You can use your favourite web search engine, or go directly to PyPI. Then you learn how to use that module, including learning SQL if you don't already know it. ChrisA From mr.eightnoteight at gmail.com Wed Dec 9 14:12:41 2015 From: mr.eightnoteight at gmail.com (srinivas devaki) Date: Thu, 10 Dec 2015 00:42:41 +0530 Subject: Reading lines of text from 7z compressed files in Python In-Reply-To: References: Message-ID: On Dec 9, 2015 3:07 PM, "Anmol Dalmia" wrote: > > > I wish to use the native LZMA library of Python 3.4 for faster performance > than any other third- party packages. Is it possible to do so? > you can check the source of lzma module main compression and decompression algorithms were written in c. so obviously you will get faster performance. In [21]: import _lzma In [22]: _lzma.__file__ Out[22]: '/home/eightnoteight/.anaconda3/envs/snakes3.4.3/lib/python3.4/lib-dynload/_ lzma.cpython-34m.so' and regarding your problem, here's a simple example on how you can read line by line of your compressed 7z text file. import lzma with lzma.open('test.7z', 'w') as lf: lf.write(b'123\n'*1000) with lzma.open('test.7z', 'r') as lf: arr = list(lf) print(len(arr)) print(set(arr)) print(arr[0]) print(arr[0].decode('utf-8')) [gist] https://gist.github.com/38681cad88928b089abb later you can even extract that test.7z with 7z command line client with (7z x test.7z) From oscar.j.benjamin at gmail.com Wed Dec 9 15:20:20 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Dec 2015 20:20:20 +0000 Subject: 3D numpy array subset In-Reply-To: <2e1a80e9-cd0a-46b5-a8c0-97f208f71f54@googlegroups.com> References: <2e1a80e9-cd0a-46b5-a8c0-97f208f71f54@googlegroups.com> Message-ID: On 9 Dec 2015 14:26, "Heli" wrote: > > Dear all, > > I am reading a dataset from a HDF5 file using h5py. my datasets are 3D. > > Then I will need to check if another 3d numpy array is a subset of this 3D array i am reading from the file. > > In general, is there any way to check if two 3d numpy arrays have intersections and if so, get the indices of the intersection area. > > By intersection, I exactly mean the intersection definition used in set theory. Does this help: http://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html I'm not sure how the 3d part is relevant but that function finds the common elements of two arrays. Use .flat or something to make the 3d arrays be treated as 1d. Otherwise it's not clear what you mean by intersection. -- Oscar From william.abdo at verio.net Wed Dec 9 15:33:38 2015 From: william.abdo at verio.net (William Abdo) Date: Wed, 9 Dec 2015 20:33:38 +0000 Subject: Windows 10 and PYODBC Message-ID: Hi All, I am not sure if anyone has asked this question already or not but I will again. Hopefully someone else has had and found a fix for this issue. I'm grateful for any and all assistance. I have recently upgraded to Windows 10 and I have an issue with PYODBC connecting to Oracle 11g. It was working OK in Windows 7, till I upgraded to Windows 10, Anyone have any IDEAS? I have tried setting it to Windows 7 compatibility mode . I have updated the drivers to the latest (Which I think I already had). The actual error I get is Traceback (most recent call last): File "oraclecountsDec1.py", line 32, in pconnObj = pyodbc.connect( pconnString ) pyodbc.Error: ('NA000', "[NA000] [Microsoft][ODBC driver for Oracle][Oracle]Error while trying to retrieve text for error ORA-01019 (1019) (SQLDriverConnect); [01000] [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr). (0)") SQL Log file states: Fatal NI connect error 12560, connecting to: (DESCRIPTION=(ADDRESS=(PROTOCOL=BEQ)(PROGRAM=oracle)(ARGV0=oracleORCX)(ARGS='(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))'))(CONNECT_DATA=(SID=ORCX)(CID=(PROGRAM=D:\Python26\python.exe)(HOST=xxxxxxx-xxxxxxxx)(USER=xxxxxxxxxxxxxx)))) VERSION INFORMATION: TNS for 32-bit Windows: Version 12.1.0.2.0 - Production Oracle Bequeath NT Protocol Adapter for 32-bit Windows: Version 12.1.0.2.0 - Production Windows NT TCP/IP NT Protocol Adapter for 32-bit Windows: Version 12.1.0.2.0 - Production Time: 06-AUG-2015 17:12:31 Tracing not turned on. Tns error struct: ns main err code: 12560 TNS-12560: Message 12560 not found; No message file for product=NETWORK, facility=TNS ns secondary err code: 0 nt main err code: 530 TNS-00530: Message 530 not found; No message file for product=NETWORK, facility=TNS nt secondary err code: 126 nt OS err code: 0 Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] ________________________________ This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. makes no warranty that this email is error or virus free. Thank you. ________________________________ This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. ________________________________ From breamoreboy at yahoo.co.uk Wed Dec 9 16:38:14 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 9 Dec 2015 21:38:14 +0000 Subject: Python variable assigning problems... In-Reply-To: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: On 09/12/2015 17:49, ICT Ezy wrote: > Pl refer question which attached image here: > > link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 > Please put your code, query or whatever it is inline here, I'm not going off into the great wide world just to suit you. If it has anything to do with installing 3.5 on Windows asked and answered roughly one trillion times. -- 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 Wed Dec 9 16:42:48 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 9 Dec 2015 21:42:48 +0000 Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: Message-ID: On 09/12/2015 17:51, ICT Ezy wrote: > Pl explain me how to connect the MYSQL database to Python program? > Use a search engine. Then run up an editor, write some code, run said code. If you then have problems state your OS, Python version and provide us with the full traceback. An alternative is to write a cheque for (say) GBP 1000 payable to the Python Software Foundation and if you're lucky somebody will do your homework 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 rxjwg98 at gmail.com Wed Dec 9 16:57:54 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 9 Dec 2015 13:57:54 -0800 (PST) Subject: Is there a data type rule on 'x+=' and 'x0=x+'? Message-ID: <1628c4a2-c924-4e0c-8baa-322eb5620ff5@googlegroups.com> Hi, I have a numpy np.array data x: x= np.array([[157, 185], [169, 195], [162, 179], [145, 195], [159, 199], [165, 180], [172, 195], [180, 201], [163, 195], [169, 191]]) Here is the original code snippet: x+=uniform(-8, 8, x.shape) x Out[557]: array([[163, 192], [163, 187], [171, 200], [165, 186], [162, 185], [160, 193], [156, 194], [168, 197], [186, 207], [184, 208]]) I am curious about the integer data type of result x. When I use this code: x0=x+uniform(-8, 8, x.shape) x0 is a floating format: x0 Out[555]: array([[ 150.84633535, 188.93254259], [ 170.29185044, 197.22753051], [ 175.65371771, 190.59168953], [ 159.61401655, 175.06364015], [ 168.35531363, 180.19243277], [ 163.79970077, 206.28600694], [ 157.89342616, 203.39444556], [ 179.86956647, 192.91265609], [ 182.48075601, 208.02397713], [ 187.59332123, 207.41482024]]) I would like to know what rule makes these two different result formats. Could you help me? Thanks, From nickgeovanis at gmail.com Wed Dec 9 19:17:05 2015 From: nickgeovanis at gmail.com (nickgeovanis at gmail.com) Date: Wed, 9 Dec 2015 16:17:05 -0800 (PST) Subject: PyTk cascaded radiobuttons, howto? Message-ID: <589c87de-5712-4efb-80a2-3a862b6dafd8@googlegroups.com> Using python 3.4.2. Tcl/tk example here is from /usr/share/tk8.5/demos/widget and .../menu.tcl. The way tcl/tk adds cascaded radiobuttons to a menu is like this: set m $w.menu.cascade $w.menu add cascade -label "Cascades" -menu $m -underline 0 .... $m add cascade -label "Radio buttons" -menu $w.menu.cascade.radio... set m $w.menu.cascade.radio $m add radio -label "Roman" -variable style... $m add radio -label "Italic" -variable style... ...and so on. My difficulty doing the same in PyTk is the following: When creating that uppermost cascade, you do something like menu.add_cascade(label = "Cascades") ...but there is no ability to save a usable reference to that top-level cascade. If I do so anyway and add a radiobutton to it, nothing appears, no errors either. What is the correct way to cascade radiobuttons from a cascaded menu in PyTk? Thanks....Nick From steve at pearwood.info Wed Dec 9 19:25:17 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Dec 2015 11:25:17 +1100 Subject: Is there a data type rule on 'x+=' and 'x0=x+'? References: <1628c4a2-c924-4e0c-8baa-322eb5620ff5@googlegroups.com> Message-ID: <5668c66f$0$1595$c3e8da3$5496439d@news.astraweb.com> On Thu, 10 Dec 2015 08:57 am, Robert wrote: > Hi, > > I have a numpy np.array data x: > > x= np.array([[157, 185], [169, 195], [162, 179], [145, 195], [159, 199], > [165, 180], [172, 195], [180, 201], [163, 195], [169, 191]]) > > Here is the original code snippet: > > x+=uniform(-8, 8, x.shape) What is "uniform"? I thought it might be numpy.uniform, but that doesn't appear to exist. So I will guess that it might be numpy.random.uniform. Is that right? [...] > I am curious about the integer data type of result x. py> x = np.array([[157, 185], [169, 195], [162, 179], [145, 195], [159, 199], ... [165, 180], [172, 195], [180, 201], [163, 195], [169, 191]]) py> x.dtype dtype('int32') py> y = np.random.uniform(-8, 8, x.shape) py> y.dtype dtype('float64') So the array x is an array of int32 and the array of random numbers is an array of float64. When you do an in-place add using += the data type doesn't change, but when you do an external add using + the result is coerced to the "wider" type, which is float64. py> x.dtype dtype('int32') py> (x + y).dtype dtype('float64') You can read up on numpy types here: http://docs.scipy.org/doc/numpy/user/basics.types.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.result_type.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.promote_types.html I'm not quite sure if the specific type promotion rules are documented anywhere, but basically any arithmetic operation between different types can involve loss of precision. Consider adding an integer 100 and a float 1.1, since they are different types, numpy must coerce the types to a common format: 100 + int32(1.1) = 101 float64(100) + 1.1 = 101.1 Since the first result loses precision, numpy will choose the second. This is called "type promotion": float64 can represent every value that int32 can, but int32 cannot represent every float64 without loss of precision. When Numpy creates a new array as the result of an calculation, it will promote the types involved to avoid data loss. But an in-place operation like += has to use the type of the original, because that is fixed. py> x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) py> x ** 0.5 # creates a new array array([ 1. , 1.41421356, 1.73205081, 2. , 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ]) py> x **= 0.5 py> x array([1, 1, 1, 2, 2, 2, 2, 2, 3]) -- Steven From nickgeovanis at gmail.com Wed Dec 9 20:53:00 2015 From: nickgeovanis at gmail.com (nickgeovanis at gmail.com) Date: Wed, 9 Dec 2015 17:53:00 -0800 (PST) Subject: PyTk cascaded radiobuttons, howto? In-Reply-To: <589c87de-5712-4efb-80a2-3a862b6dafd8@googlegroups.com> References: <589c87de-5712-4efb-80a2-3a862b6dafd8@googlegroups.com> Message-ID: <0bf9b6af-66d4-4ffc-b8dc-22842023cfd3@googlegroups.com> This is of course using tkinter from python, PyTk is a misnomer. Python 3.4.2 wit tcl/tk 8.5 under CentOS 7. From mr.eightnoteight at gmail.com Wed Dec 9 23:44:14 2015 From: mr.eightnoteight at gmail.com (srinivas devaki) Date: Thu, 10 Dec 2015 10:14:14 +0530 Subject: How to use internal python c funtions, from python code Message-ID: Hi I'm coming from this link ( https://groups.google.com/forum/#!topic/python-ideas/cBFvxq1LQHM), which proposes to use long_to_decimal_string(), int_to_decimal_string() functions for printing integers in different bases. Now is there anyway i can use such internal functions from pure python code, passing ctypes when the arguments are c datatypes. For competitive programming purposes I really want to use those functions for speed. From rosuav at gmail.com Wed Dec 9 23:53:48 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 10 Dec 2015 15:53:48 +1100 Subject: How to use internal python c funtions, from python code In-Reply-To: References: Message-ID: On Thu, Dec 10, 2015 at 3:44 PM, srinivas devaki wrote: > For competitive programming purposes I really want to use those functions > for speed. Recommendation: Write your code the simple and obvious way, and *then* start thinking about speed. And before you look at calling on C code manually, try running your code in PyPy, and then try making use of Cython. For the specific example of converting an integer into a string using a particular base, there are quite a few options available; but I would recommend using the very simplest you can get away with. ChrisA From steve+comp.lang.python at pearwood.info Thu Dec 10 00:33:34 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 10 Dec 2015 16:33:34 +1100 Subject: Python variable assigning problems... References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: <56690eb3$0$1584$c3e8da3$5496439d@news.astraweb.com> On Thursday 10 December 2015 04:49, ICT Ezy wrote: > Pl refer question which attached image here: > > link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 Do you really expect us to sign in to Google in order to help you? Let me give you some friendly advice. You are asking us for free support. In the commercial world, this sort of support can cost hundreds of dollars an hour, and you are getting it for free. Every barrier you add, you lose 50% of the potential answers. You ask us to click a link, instead of including the question direct in your message? That's 50% of potential helpers gone. Link is to an image instead of actual text and code? That's 75% gone. Link requires a login to Google? That's 87.5% gone. If you want good quality answers, you need to ask good quality questions. If you ask lazy questions and expect us to do all the work, you'll probably be disappointed. -- Steve From torriem at gmail.com Thu Dec 10 01:23:34 2015 From: torriem at gmail.com (Michael Torrie) Date: Wed, 09 Dec 2015 23:23:34 -0700 Subject: Getting data out of Mozilla Thunderbird with Python? In-Reply-To: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56691A66.9090102@gmail.com> On 12/09/2015 04:11 AM, Steven D'Aprano wrote: > Maildir is also *much* safer too. With mbox, a single error when writing > email to the mailbox will likely corrupt *all* emails from that point on, > so potentially every email in the mailbox. With maildir, a single error > when writing will, at worst, corrupt one email. > > Thanks Mozilla, for picking the *less* efficient and *more* risky format as > the default. Good choice! Not so long ago, many filesystems were very poor at storing lots of small files. For disk efficiency, storing them in one big file, periodically compacting the file, was seen as a better way to go. After all mbox format has been around for a very long time for certain reasons (which no longer exist today). Maildir came later. Back when hard drives were smaller, it was also not uncommon to run out of inodes in a file system on a server that had many small files. Neither of these issues is much of a problem these days. Ext4 added the ability to store small files right in the inode, so internal fragmentation (and wasting of space) isn't a big issue anymore. It's good to know I can configure Thunderbird to use maildir for local storage. I'll have to make the change here. Will make my backups a lot easier and faster. From framstag at rus.uni-stuttgart.de Thu Dec 10 03:28:29 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 10 Dec 2015 08:28:29 +0000 (UTC) Subject: non-blocking getkey? References: Message-ID: Ulli Horlacher wrote: > > But... is there a windows program with which one can select files and the > > result is written to STDOUT? > > Found it: > > from Tkinter import Tk > from tkFileDialog import askopenfilename > > Tk().withdraw() > file = askopenfilename() My users do not like it :-( They want to drag&drop files. Therefore I have added it as another option to enter files: [f] select a file [d] select a directory [e] enter a file or directory (with drag&drop or copy&paste) With [f] starts askopenfilename and [d] starts askdirectory The problem with [e] is: my users do not press ENTER after pasting. My idea now is: instead of raw_input() I use a get_paste() function, which reads input character for input character and after a (say) 1 s timeout it returns the string. Pasting a string with the mouse is rather fast, there should be no big delay between the characters. How can I implement such a get_paste() function? I need a non-blocking getkey() function. It must work on Windows and Linux. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From auriocus at gmx.de Thu Dec 10 03:54:26 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Thu, 10 Dec 2015 09:54:26 +0100 Subject: non-blocking getkey? In-Reply-To: References: Message-ID: Am 10.12.15 um 09:28 schrieb Ulli Horlacher: > Ulli Horlacher wrote: >> Found it: >> >> from Tkinter import Tk >> from tkFileDialog import askopenfilename >> >> Tk().withdraw() >> file = askopenfilename() > > My users do not like it :-( > They want to drag&drop files. > Therefore I have added it as another option to enter files: > > [f] select a file > [d] select a directory > [e] enter a file or directory (with drag&drop or copy&paste) Well I know that you won't take my advice but..... There are standard protocols for drag'n'drop of files and folders on all three major platforms. Tk supports this using the optional TkDND module, which unfortunately isn't installed with a standard Python distribution. Beware there is a "Tkdnd" Python module which implements local Drag'n'drop only; you need the "real thing" from here http://sourceforge.net/projects/tkdnd/ plus the correct Python bindings: Maybe this is the correct one: http://osdir.com/ml/python.tkinter/2005-07/msg00000.html I'm not sure - never used it from Python, only from Tcl. Using "the real thing" also allows you to accept multiple files/drectories dragged from the system file manager. Of course, you need a Tk main window to implement this, which you refused earlier. > With [f] starts askopenfilename and [d] starts askdirectory > > The problem with [e] is: my users do not press ENTER after pasting. > > My idea now is: instead of raw_input() I use a get_paste() function, which > reads input character for input character and after a (say) 1 s timeout it > returns the string. Pasting a string with the mouse is rather fast, there > should be no big delay between the characters. > > How can I implement such a get_paste() function? > I need a non-blocking getkey() function. > > It must work on Windows and Linux. Raw tty input. You'll have to write two different versions for Windows and Linux. Sorry I can't help with that one. Christian From auriocus at gmx.de Thu Dec 10 03:57:27 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Thu, 10 Dec 2015 09:57:27 +0100 Subject: non-blocking getkey? In-Reply-To: References: Message-ID: Am 10.12.15 um 09:28 schrieb Ulli Horlacher: > Ulli Horlacher wrote: > My users do not like it :-( > They want to drag&drop files. Another cheap solution comes to mind: On windows, dropping files onto an icon on the desktop is interpreted as "launch the program with additional arguments", where the arguments are the file names. Maybe you could try interpreting the cmdline args first? I'm not so sure how it will work with non-ASCII characters, though. On Linux, you can probably also create simliar icons. The only drawback is that you start a new instance of your file manager each time. Christian From __peter__ at web.de Thu Dec 10 04:27:53 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2015 10:27:53 +0100 Subject: tkinter cascaded menus, was Re: PyTk cascaded radiobuttons, howto? References: <589c87de-5712-4efb-80a2-3a862b6dafd8@googlegroups.com> Message-ID: nickgeovanis at gmail.com wrote: > Using python 3.4.2. > Tcl/tk example here is from /usr/share/tk8.5/demos/widget and > .../menu.tcl. The way tcl/tk adds cascaded radiobuttons to a menu is like > this: set m $w.menu.cascade > $w.menu add cascade -label "Cascades" -menu $m -underline 0 > .... > $m add cascade -label "Radio buttons" -menu $w.menu.cascade.radio... > set m $w.menu.cascade.radio > $m add radio -label "Roman" -variable style... > $m add radio -label "Italic" -variable style... > > ...and so on. > > My difficulty doing the same in PyTk is the following: When creating that > uppermost cascade, you do something like menu.add_cascade(label = > "Cascades") ...but there is no ability to save a usable reference to that > top-level cascade. If I do so anyway and add a radiobutton to it, nothing > appears, no errors either. What is the correct way to cascade radiobuttons > from a cascaded menu in PyTk? Thanks....Nick You build the inner menu and then add it to the outer. After looking into the examples in the Demo/tkinter folder of the Python 2.7 source distribution I came up with the following: import tkinter from tkinter import Menu root = tkinter.Tk() menubar = Menu(root) editmenu = Menu(menubar) editmenu.add_command(label="Cut") editmenu.add_command(label="Copy") editmenu.add_command(label="Paste") fontmenu = Menu(editmenu, name="font") fontmenu.add_command(label="Family") fontmenu.add_command(label="Size") editmenu.add_cascade(label="Font", menu=fontmenu) colormenu = Menu(editmenu, name="color") colormenu.add_radiobutton(label="Red") colormenu.add_radiobutton(label="Yellow") colormenu.add_radiobutton(label="Blue") fontmenu.add_cascade(label="Color", menu=colormenu) menubar.add_cascade(label="Edit", menu=editmenu) root["menu"] = menubar root.mainloop() From framstag at rus.uni-stuttgart.de Thu Dec 10 05:26:03 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 10 Dec 2015 10:26:03 +0000 (UTC) Subject: non-blocking getkey? References: Message-ID: Christian Gollwitzer wrote: > > My users do not like it :-( > > They want to drag&drop files. > > Therefore I have added it as another option to enter files: > > > > [f] select a file > > [d] select a directory > > [e] enter a file or directory (with drag&drop or copy&paste) > > > Well I know that you won't take my advice but..... > > There are standard protocols for drag'n'drop of files and folders on all > three major platforms. Tk supports this using the optional TkDND module, > which unfortunately isn't installed with a standard Python distribution. Then this is no-go. My users cannot install any additional software. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From framstag at rus.uni-stuttgart.de Thu Dec 10 05:40:59 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 10 Dec 2015 10:40:59 +0000 (UTC) Subject: non-blocking getkey? References: Message-ID: Christian Gollwitzer wrote: > Another cheap solution comes to mind: On windows, dropping files onto an > icon on the desktop is interpreted as "launch the program with > additional arguments", where the arguments are the file names. Ohhh... great! This helps me a lot! > Maybe you could try interpreting the cmdline args first? I have implemented this since the beginning of the project :-) > I'm not so sure how it will work with non-ASCII characters, My users have to test it. I do not have non-ASCII filenames. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From nonami.ayo at gmail.com Thu Dec 10 06:21:59 2015 From: nonami.ayo at gmail.com (nonami) Date: Thu, 10 Dec 2015 12:21:59 +0100 Subject: Problems using celery and pyelasticsearch In-Reply-To: <201512070150.tB71oP7W010189@fido.openend.se> References: <5664E2CB.9010104@gmail.com> <201512070150.tB71oP7W010189@fido.openend.se> Message-ID: <56696057.2000506@gmail.com> On 07/12/2015 02:50, Laura Creighton wrote: > In a message of Mon, 07 Dec 2015 02:37:15 +0100, nonami writes: > >> Does anyone have any idea what could be going on or how I can further >> inspect running tasks. > Not sure this will help, but it might ... > https://www.caktusgroup.com/blog/2013/10/30/using-strace-debug-stuck-celery-tasks/ This was really helpful Laura, thanks. From palpandi111 at gmail.com Thu Dec 10 06:29:19 2015 From: palpandi111 at gmail.com (Palpandi) Date: Thu, 10 Dec 2015 03:29:19 -0800 (PST) Subject: SystemError in python 2.5.4 Message-ID: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Hi All, I am getting the error mentioned below in python 2.5.4. SystemError: \loewis\25\python\Objects\longobject.c:225: bad argument to internal function. I also ran the same code in python 2.7. There I am not getting this error. I don't know which causes this error. Any solution for this? Note: The error is coming from the method call findall(path). Thanks. From rosuav at gmail.com Thu Dec 10 06:37:48 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 10 Dec 2015 22:37:48 +1100 Subject: SystemError in python 2.5.4 In-Reply-To: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> References: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Message-ID: On Thu, Dec 10, 2015 at 10:29 PM, Palpandi wrote: > Hi All, > > I am getting the error mentioned below in python 2.5.4. > > SystemError: \loewis\25\python\Objects\longobject.c:225: bad argument to internal function. > > I also ran the same code in python 2.7. > There I am not getting this error. > > I don't know which causes this error. Any solution for this? > > Note: The error is coming from the method call findall(path). > Interesting! What platform (OS, etc) are you running this on? Python 2.5 isn't supported any more, so you might have to talk to Red Hat or someone. Alternatively, given that 2.7 doesn't have this problem, can you simply write it off as an issue with the older Python, and use 2.7 instead? ChrisA From eshikafe at gmail.com Thu Dec 10 07:57:20 2015 From: eshikafe at gmail.com (austin aigbe) Date: Thu, 10 Dec 2015 04:57:20 -0800 (PST) Subject: IO Redirection to Console Message-ID: <097c5635-bc90-42a6-ba9f-969c3be26078@googlegroups.com> Hello, I am trying to port the following C++ code for IO redirection to console. // C++ (from Synfig) void redirectIOToConsole() { int hConHandle; HANDLE lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // allocate console if( GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE ) AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); //redirect unbuffered STDOUT to the console lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle((intptr_t) lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle((intptr_t) lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle((intptr_t) lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); } My Python port: from ctypes import windll, create_string_buffer,Structure, byref from ctypes.wintypes import DWORD,SHORT, WORD import os import msvcrt import sys STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 INVALID_HANDLE_VALUE = DWORD(-1).value MAX_LINES = 500 def consoleOptionEnabled(argv): value = False if ("--console" in argv) or ("-c" in argv): value = True return value def redirectIOToConsole(): class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", DWORD)] coninfo = CONSOLE_SCREEN_BUFFER_INFO() # allocate console if(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE): windll.kernel32.AllocConsole() # set the screen buffer to be big enough to let us scroll text windll.kernel32.GetConsoleScreenBufferInfo(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE), byref(coninfo)) coninfo.dwSize.Y = MAX_LINES windll.kernel32.SetConsoleScreenBufferSize(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize) #redirect unbuffered STDOUT to the console lStdHandle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) hConHandle = msvcrt.open_osfhandle(lStdHandle, os.O_TEXT) fp = os.fdopen( hConHandle, "w" ) sys.stdout = fp setvbuf( stdout, NULL, _IONBF, 0 ) # redirect unbuffered STDIN to the console lStdHandle = windll.kernel32.GetStdHandle(STD_INPUT_HANDLE) hConHandle = msvcrt.open_osfhandle(lStdHandle, os.O_TEXT) fp = os.fdopen( hConHandle, "r" ) sys.stdin = fp setvbuf( stdin, NULL, _IONBF, 0 ) #redirect unbuffered STDERR to the console lStdHandle = windll.kernel32.GetStdHandle(STD_ERROR_HANDLE) hConHandle = msvcrt.open_osfhandle(lStdHandle, os.O_TEXT) fp = os.fdopen( hConHandle, "w" ) sys.stderr = fp setvbuf( stderr, NULL, _IONBF, 0 ) # make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog # point to console as well Is there a better way to handling IO redirection to console in Python? Thanks. Austin From palpandi111 at gmail.com Thu Dec 10 08:14:45 2015 From: palpandi111 at gmail.com (Palpandi) Date: Thu, 10 Dec 2015 05:14:45 -0800 (PST) Subject: SystemError in python 2.5.4 In-Reply-To: References: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Message-ID: On Thursday, December 10, 2015 at 5:08:05 PM UTC+5:30, Chris Angelico wrote: > On Thu, Dec 10, 2015 at 10:29 PM, Palpandi wrote: > > Hi All, > > > > I am getting the error mentioned below in python 2.5.4. > > > > SystemError: \loewis\25\python\Objects\longobject.c:225: bad argument to internal function. > > > > I also ran the same code in python 2.7. > > There I am not getting this error. > > > > I don't know which causes this error. Any solution for this? > > > > Note: The error is coming from the method call findall(path). > > > > Interesting! What platform (OS, etc) are you running this on? Python > 2.5 isn't supported any more, so you might have to talk to Red Hat or > someone. Alternatively, given that 2.7 doesn't have this problem, can > you simply write it off as an issue with the older Python, and use 2.7 > instead? > > ChrisA ChrisA, Thanks for your quick response. I am using Windows and we are using 2.5.4 only. Is there any workaround? From rosuav at gmail.com Thu Dec 10 08:25:55 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 11 Dec 2015 00:25:55 +1100 Subject: SystemError in python 2.5.4 In-Reply-To: References: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Message-ID: On Fri, Dec 11, 2015 at 12:14 AM, Palpandi wrote: > ChrisA, Thanks for your quick response. > I am using Windows and we are using 2.5.4 only. > Is there any workaround? I wouldn't know. All I know is, upgrading to 2.7 gives you a lot of other improvements too, so unless there's something serious holding you back, move forward! ChrisA From PointedEars at web.de Thu Dec 10 08:26:27 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Thu, 10 Dec 2015 14:26:27 +0100 Subject: Getting data out of Mozilla Thunderbird with Python? References: <56680c59$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <11986323.g8sR6m0TfB@PointedEars.de> Michael Torrie wrote: > It's good to know I can configure Thunderbird to use maildir for local > storage. I'll have to make the change here. Will make my backups a lot > easier and faster. But see also . Not all of those bugs have been resolved/fixed. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From denismfmcmahon at gmail.com Thu Dec 10 09:03:59 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 10 Dec 2015 14:03:59 -0000 (UTC) Subject: Python variable assigning problems... References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: On Wed, 09 Dec 2015 09:49:26 -0800, ICT Ezy wrote: > Pl refer question which attached image here: > > link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8 I can't access the image with my G+ account because the image owner hasn't given me permission. Perhaps you'd like to post a short self contained example of the problem here instead. -- Denis McMahon, denismfmcmahon at gmail.com From hemla21 at gmail.com Thu Dec 10 09:40:58 2015 From: hemla21 at gmail.com (Heli) Date: Thu, 10 Dec 2015 06:40:58 -0800 (PST) Subject: np.searchSorted over 2D array In-Reply-To: References: <2b660168-3322-4bf6-bd8b-2dc846a3a874@googlegroups.com> Message-ID: <168a11ec-dd1e-481c-827b-8f5021a315cb@googlegroups.com> Thanks Peter, I will try to explain what I really need. I have a 3D numpy array of 100*100*100 (1M elements). Then I have another numpy array of for example 10*2*10 (200 elements). I want to know if in the bigger dataset of 100*100*100, there is anywhere, where the second numpy array of 200 elements with shape 10*2*10 appears. If it does, then I want the indices of the bigger dataset where this happens. I hope I?m making myself more clear :) Thanks for your comments, On Wednesday, December 9, 2015 at 5:37:07 PM UTC+1, Peter Otten wrote: > Heli wrote: > > [Please don't open a new thread for the same problem] > > > I need to check whether two 2d numpy arrays have intersections and if so I > > will need to have the cell indices of the intersection. > > > > By intersection, I exactly mean the intersection definition used in set > > theory. > > > > I will give an example of what I need to do: > > > > a=[[0,1,2],[3,4,5],[6,7,8]] > > b=[[0,1,2],[3,4,5]] > > > > I would like to check whether b is subset of a and then get the indices in > > a where b matches. > > > > cellindices=[[True,True,True],[True,True,True],[False,False,False]] > > > > What is the best way to do this in numpy? > > Providing an example is an improvement over your previous post, but to me > it's still not clear what you want. > > >>> functools.reduce(lambda x, y: x | y, (a == i for i in b.flatten())) > array([[ True, True, True], > [ True, True, True], > [False, False, False]], dtype=bool) > > produces the desired result for the example input, but how do you want to > handle repeating numbers as in > > >>> a = numpy.array([[0,1,2],[3,4,5],[3, 2, 1]]) > >>> functools.reduce(lambda x, y: x | y, (a == i for i in b.flatten())) > array([[ True, True, True], > [ True, True, True], > [ True, True, True]], dtype=bool) > > ? > > Try to be clear about your requirement, describe it in english and provide a > bit of context. You might even write a solution that doesn't use numpy and > ask for help in translating it. > > At the very least we need more/better examples. From romapera15 at gmail.com Thu Dec 10 09:44:27 2015 From: romapera15 at gmail.com (=?UTF-8?Q?fran=C3=A7ai_s?=) Date: Thu, 10 Dec 2015 12:44:27 -0200 Subject: Administrators and moderators of Python-list, please erase all the messages that I not should have posted here in python-list! Message-ID: Administrators and moderators of Python-list, please erase all the messages that I not should have posted here in python-list. I ask this because I probably be in future a good programmer famous and I do not want to talk about the topics that I should not have posted here in python-list. I decided prevent substantial harm to important relationships that probably I will have in future with other developers. From ganesh1pal at gmail.com Thu Dec 10 09:59:57 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Thu, 10 Dec 2015 20:29:57 +0530 Subject: python unit test frame work Message-ID: Hello Team, Iam on python 2.7 and linux. Iam trying to understand the python unit test frame work and also trying to fix the below code , any help in this regard would be appreciated ? # Sample code starts here inject_failure = {} report = "" ClassIsSetup = False ClassCleanup = False class Test_filesystem(unittest.TestCase): """ """ def TestSetup(self): """ Initial setup before unittests run """ logging.info("SETUP.....Started !!!") if not os.path.ismount("/tmp"): # Comment 1. logging.error("Error: /tmp is not mounted") sys.exit("/tmp is not mounted ...Exiting !!!") if self.create_dataset() and capture_chksum(): try: test01_log = os.path.join(LOG_DIR, "test01_corrupt.log") self.inject_failure['test01'] = tool.run_tool(test01_log) time.sleep(10) test02_log = os.path.join(LOG_DIR, "test01_corrupt.log") self.inject_failure['test01'] = tool.run_tool(test02_log) time.sleep(10) except Exception, e: logging.error(e) sys.exit(1) if not run_scanner(): sys.exit(1) else: try: self.__class__.report = report_tool() except Exception, e: logging.error(e) sys.exit("Running Reporting tool failed") logging.info("SETUP.....Done !!!") def setUp(self): if not self.ClassIsSetup: self.__class__.ClassIsSetup = True self.setupClass() def setupClass(self): self.TestSetup() def test_01_inode_test(self): """ test01: """ logging.info("### Executing test01: inode corruption ###") self.assertTrue(run_db_tool(self.__class__.report, self.find_failure['test01'])) def test_02_hardlink_test(self): """ test02: """ logging.info("### Executing test01: inode corruption ###") self.assertTrue(run_db_tool(self.__class__.report, def tearDown(self): if self.ClassCleanup: self.tearDownClass() def tearDownClass(self): self.cleanup() # Comment 2 def cleanup(self): """ Cleanup all the data & logs """ logging.info("Cleaning all data") os.system("rm -rf /tmp/data_set") def main(): unittest.main() if __name__ == '__main__': main() # Sample code ends here Questions : 1. If the setUp() fails the code still tries to run through the test and assert's with error. How do I avoid these Error on the console , actually test01, test02, . etc , shouldn't run if the setup Failed ? Example: If the mount fails i.e if not os.path.ismount("/tmp"): in TestSetup(). we will get the below output: #c_t.py EEEE ====================================================================== ERROR: test01: test_01_inode_test ---------------------------------------------------------------------- Traceback (most recent call last): File "c_t.py", line xx, in setUp self.setupClass() File "c_t.py", line xxx, in TestSetup self.TestSetup() File "c_t.py", line xx, in corruptSetup sys.exit("/tmp is not mounted ...Exiting !!!") SystemExit: /tmp is not mounted ...Exiting !!! ====================================================================== ERROR: test02 ---------------------------------------------------------------------- Traceback (most recent call last): File "c_t.py", line 162, in test_02_hardlink_test self.inject_failures['test02'])) KeyError: 'test02' Ran 2 tests in 0.003s FAILED (errors=2) 2. The cleanup() never gets executed at the end of the test. 3. Any better idea or suggestions to improve the above code ? Regards, Ganesh From nick.a.sarbicki at gmail.com Thu Dec 10 10:02:03 2015 From: nick.a.sarbicki at gmail.com (Nick Sarbicki) Date: Thu, 10 Dec 2015 15:02:03 +0000 Subject: Administrators and moderators of Python-list, please erase all the messages that I not should have posted here in python-list! In-Reply-To: References: Message-ID: Great, now I have something I can use as blackmail when you are a rich and famous programmer! /s Joking aside, don't worry about embarrassing questions from your past. We've all had a journey to being programmers and we've all done dumb things. If anything, by trying to cover up your past you will do more to damage any future relationships you will have with developers. - Nick. On Thu, Dec 10, 2015 at 2:55 PM fran?ai s wrote: > Administrators and moderators of Python-list, please erase all the messages > that I not should have posted here in python-list. > > I ask this because I probably be in future a good programmer famous and I > do not want to talk about the topics that I should not have posted here in > python-list. > > I decided prevent substantial harm to important relationships that probably > I will have in future with other developers. > -- > https://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Thu Dec 10 10:50:29 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2015 16:50:29 +0100 Subject: python unit test frame work References: Message-ID: Ganesh Pal wrote: > Hello Team, > > Iam on python 2.7 and linux. Iam trying to understand the python unit > test frame work and also trying to fix the below code , any help in > this regard would be appreciated ? I recommend that you reread the unittest documentation. setUpClass() should be a class method, and if it succeeds you can release the ressources it required in the corresponding tearDownClass() method. As written the flags and the setUp()/tearDown() seem unnecessary. If a necessary ressource cannot be acquired you can raise a SkipTest exception and the test or tests will not run. > logging.info("### Executing test01: inode corruption ###") In --verbose mode unittest will print the first line of the test methods' docstring. That should be sufficient most of the time. Only loosely related: Drop the habit to sprinkle sys.exit() all over the place. A well-behaved application has one exit point, at the end of the main module. > self.__class__.report When reading the report attribute this is the same as just self.report (unless you shaded it in the instance). > # Sample code starts here > inject_failure = {} > report = "" > ClassIsSetup = False > ClassCleanup = False > > class Test_filesystem(unittest.TestCase): > """ """ > def TestSetup(self): > """ Initial setup before unittests run """ > logging.info("SETUP.....Started !!!") > if not os.path.ismount("/tmp"): # Comment 1. > logging.error("Error: /tmp is not mounted") > sys.exit("/tmp is not mounted ...Exiting !!!") > > if self.create_dataset() and capture_chksum(): > try: > test01_log = os.path.join(LOG_DIR, "test01_corrupt.log") > self.inject_failure['test01'] = tool.run_tool(test01_log) > time.sleep(10) > test02_log = os.path.join(LOG_DIR, "test01_corrupt.log") > self.inject_failure['test01'] = tool.run_tool(test02_log) > time.sleep(10) > except Exception, e: > logging.error(e) > sys.exit(1) > if not run_scanner(): > sys.exit(1) > else: > try: > self.__class__.report = report_tool() > except Exception, e: > logging.error(e) > sys.exit("Running Reporting tool failed") > logging.info("SETUP.....Done !!!") > > def setUp(self): > if not self.ClassIsSetup: > self.__class__.ClassIsSetup = True > self.setupClass() > > def setupClass(self): > self.TestSetup() > > def test_01_inode_test(self): > """ test01: """ > logging.info("### Executing test01: inode corruption ###") > self.assertTrue(run_db_tool(self.__class__.report, > self.find_failure['test01'])) > def test_02_hardlink_test(self): > """ test02: """ > logging.info("### Executing test01: inode corruption ###") > self.assertTrue(run_db_tool(self.__class__.report, > > def tearDown(self): > if self.ClassCleanup: > self.tearDownClass() > > def tearDownClass(self): > self.cleanup() > > # Comment 2 > def cleanup(self): > """ Cleanup all the data & logs """ > logging.info("Cleaning all data") > os.system("rm -rf /tmp/data_set") > > def main(): > unittest.main() > > if __name__ == '__main__': > main() > > # Sample code ends here > > Questions : > > 1. If the setUp() fails the code still tries to run through the test > and assert's with error. How do I avoid these Error on the console , > actually test01, test02, . etc , shouldn't run if the setup Failed ? > > Example: If the mount fails i.e if not os.path.ismount("/tmp"): in > TestSetup(). we will get the below output: > > #c_t.py > EEEE > ====================================================================== > ERROR: test01: test_01_inode_test > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "c_t.py", line xx, in setUp > self.setupClass() > File "c_t.py", line xxx, in TestSetup > self.TestSetup() > File "c_t.py", line xx, in corruptSetup > sys.exit("/tmp is not mounted ...Exiting !!!") > SystemExit: /tmp is not mounted ...Exiting !!! > ====================================================================== > ERROR: test02 > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "c_t.py", line 162, in test_02_hardlink_test > self.inject_failures['test02'])) > KeyError: 'test02' > > Ran 2 tests in 0.003s > FAILED (errors=2) > > 2. The cleanup() never gets executed at the end of the test. > 3. Any better idea or suggestions to improve the above code ? > > Regards, > Ganesh From framstag at rus.uni-stuttgart.de Thu Dec 10 10:52:15 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 10 Dec 2015 15:52:15 +0000 (UTC) Subject: non-blocking getkey? References: Message-ID: Ulli Horlacher wrote: > My idea now is: instead of raw_input() I use a get_paste() function, which > reads input character for input character and after a (say) 1 s timeout it > returns the string. Pasting a string with the mouse is rather fast, there > should be no big delay between the characters. > > How can I implement such a get_paste() function? > I need a non-blocking getkey() function. I found a solution for Windows: print("\nCopy&paste a filename or drag&drop a file into this window") file = get_paste() print('\n"%s"' % file) def get_paste(): import msvcrt c = msvcrt.getch() if c == '\n' or c == '\r': return '' paste = c while msvcrt.kbhit(): c = msvcrt.getch() if c == '\n' or c == '\r': break paste += c return paste -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From torriem at gmail.com Thu Dec 10 10:55:46 2015 From: torriem at gmail.com (Michael Torrie) Date: Thu, 10 Dec 2015 08:55:46 -0700 Subject: Administrators and moderators of Python-list, please erase all the messages that I not should have posted here in python-list! In-Reply-To: References: Message-ID: <5669A082.4070901@gmail.com> On 12/10/2015 07:44 AM, fran?ai s wrote: > Administrators and moderators of Python-list, please erase all the messages > that I not should have posted here in python-list. > > I ask this because I probably be in future a good programmer famous and I > do not want to talk about the topics that I should not have posted here in > python-list. > > I decided prevent substantial harm to important relationships that probably > I will have in future with other developers. While the folks who run the python.org archive do try to respond to people's requests for removal, particularly in the case of libelous and abusive messages, be aware that this list is also connected with the large, decentralize usenet message system, and also is archived by numerous newsgroup archiving web sites, and removal from the archive hosted at python.org will not remove messages in those other places. What could you have possibly said that would cause substantial harm to future relationships? Also, how are the web masters supposed to know what you shouldn't have posted and what was okay? I have read this mailing list for years now, and I don't recall having seen anything from your email address that would be cause for concern. I'm sure potential employers and colleagues can understand that you once didn't know as much about Python and programming, and that you've learned and become a better programmer over the years. In short, I wouldn't worry about this at all if I were you (unless you are PointedEars, RR, or our resident unicode troll). I'd worry far more about social networks than the python mailing list. From torriem at gmail.com Thu Dec 10 10:57:47 2015 From: torriem at gmail.com (Michael Torrie) Date: Thu, 10 Dec 2015 08:57:47 -0700 Subject: Administrators and moderators of Python-list, please erase all the messages that I not should have posted here in python-list! In-Reply-To: References: Message-ID: <5669A0FB.1030908@gmail.com> On 12/10/2015 07:44 AM, fran?ai s wrote: > Administrators and moderators of Python-list, please erase all the messages > that I not should have posted here in python-list. > > I ask this because I probably be in future a good programmer famous and I > do not want to talk about the topics that I should not have posted here in > python-list. > > I decided prevent substantial harm to important relationships that probably > I will have in future with other developers. Just FYI again here, when I search for your email address on google, the first few entries are your posts to several other mailing lists and usenet groups making this same request. I'd say that that honestly looks far worse, from an internet search pov, than anything you might have said on the mailing lists in a technical vein. Good luck. From chris at simplistix.co.uk Thu Dec 10 13:02:49 2015 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 10 Dec 2015 18:02:49 +0000 Subject: testfixtures 4.7.0 Released! Message-ID: <5669BE49.2090007@simplistix.co.uk> Hi All, I'm pleased to announce the release of testfixtures 4.7.0. Since 4.5.1, the following have been added: - Add the ability to pass raises=False to compare() to just get the resulting message back rather than having an exception raised. - Fix a bug that mean symlinked directories would never show up when using TempDirectory.compare() and friends. - Add the `followlinks` parameter to TempDirectory.compare() to indicate that symlinked or hard linked directories should be recursed into when using `recursive=True`. The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: https://github.com/Simplistix/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 oscar.j.benjamin at gmail.com Thu Dec 10 14:55:31 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 10 Dec 2015 19:55:31 +0000 Subject: np.searchSorted over 2D array In-Reply-To: <168a11ec-dd1e-481c-827b-8f5021a315cb@googlegroups.com> References: <2b660168-3322-4bf6-bd8b-2dc846a3a874@googlegroups.com> <168a11ec-dd1e-481c-827b-8f5021a315cb@googlegroups.com> Message-ID: On 10 Dec 2015 14:46, "Heli" wrote: > > Thanks Peter, > > I will try to explain what I really need. > > I have a 3D numpy array of 100*100*100 (1M elements). Then I have another numpy array of for example 10*2*10 (200 elements). I want to know if in the bigger dataset of 100*100*100, there is anywhere, where the second numpy array of 200 elements with shape 10*2*10 appears. If it does, then I want the indices of the bigger dataset where this happens. > So you want to find N in M. First find all occurrences of N[0][0][0] in M[:90][:98][:90]. Then for each of those extract the same size subview from M and check if (Ms == N).all(). -- Oscar From ganesh1pal at gmail.com Thu Dec 10 17:35:57 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Fri, 11 Dec 2015 04:05:57 +0530 Subject: python unit test frame work In-Reply-To: References: Message-ID: +python list . sorry I accidentally did a reply to Peter. On Dec 11, 2015 3:57 AM, "Ganesh Pal" wrote: > > > > Drop the habit to sprinkle sys.exit() all over the place. A well-behaved > > application has one exit point, at the end of the main module. > I was using sys.exit() as the means to stop the execution or terminate the program. I can't think of an alternative for my case : I have multiple checks if I don't meet them continuing with the main program doesn't make sense Regards, Ganesh From ben+python at benfinney.id.au Thu Dec 10 18:02:07 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 11 Dec 2015 10:02:07 +1100 Subject: python unit test frame work References: Message-ID: <854mfp6h74.fsf@benfinney.id.au> Ganesh Pal writes: > I have multiple checks if I don't meet them continuing with the main > program doesn't make sense That means these are not unit tests (which are isolatable, independent test cases). If the tests are best characterised as a sequence of steps, then the ?unittest? model (designed for actual unit tests) will not fit well. You should instead just write a ?main? function that calls each test case in turn and exits when one of them fails. import sys from .. import foo_app def test_input_wibble_returns_lorem(frob): """ Should process 'wibble' input and result in state 'lorem'. """ frob.process("wibble") if frob.state != "lorem": raise AssertionError def test_input_warble_returns_ipsum(): """ Should process warble' input and result in state 'ipsum'. """ frob.process("warble") if frob.state != "ipsum": raise AssertionError # ? EXIT_STATUS_ERROR = 1 def main(argv): """ Mainline code for this module. """ process_args(argv) test_cases = [ test_input_wibble_returns_lorem, test_input_warble_returns_ipsum, # ? ] test_frob = foo_app.Frob() for test_case in test_cases: try: test_case(test_frob) except AssertionError as exc: sys.stderr.write("Test run failed ({exc})".format(exc=exc)) sys.exit(EXIT_STATUS_ERROR) if __name__ == "__main__": exit_status = main(sys.argv) sys.exit(exit_status) -- \ ?The greatest tragedy in mankind's entire history may be the | `\ hijacking of morality by religion.? ?Arthur C. Clarke, 1991 | _o__) | Ben Finney From cs at zip.com.au Thu Dec 10 19:40:21 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 11 Dec 2015 11:40:21 +1100 Subject: python unit test frame work In-Reply-To: References: Message-ID: <20151211004021.GA84387@cskk.homeip.net> On 11Dec2015 04:05, Ganesh Pal wrote: >On Dec 11, 2015 3:57 AM, "Ganesh Pal" wrote: >> > Drop the habit to sprinkle sys.exit() all over the place. A well-behaved >> > application has one exit point, at the end of the main module. >> >I was using sys.exit() as the means to stop the execution or terminate the >program. I can't think of an alternative for my case : >I have multiple checks if I don't meet them continuing with the main >program doesn't make sense First, as Ben remarks, if one test _depends_ on an earlier one then it isn't a real unit test. On the other hand, if you simply have some simple tests followed by more complex tests (I have several like this) you have two facilities to help you. Firstly, I have observed that unittest tends to run tests in lexical order, so I tend to name the test methods like this: def test00minimalist(self): def test01minimalPlusOneThing(self): ... def test20somethingComplex(self): and on the command line when you are hand testing things: python -m cs.venti.tcp_tests -v -f Of course, substitute your module name. The -v recites the test names and docstring first line as Peter has mentioned. The -f causes the etst suit to fail on the first test failure, and does not run the later tests. That seems to cover what you want here: abort on the simplest failing test. Cheers, Cameron Simpson From mr.eightnoteight at gmail.com Thu Dec 10 21:05:44 2015 From: mr.eightnoteight at gmail.com (srinivas devaki) Date: Fri, 11 Dec 2015 07:35:44 +0530 Subject: How to use internal python c funtions, from python code In-Reply-To: References: Message-ID: Thank you Chris, later I decided that this would be cheating and I have to think about another algorithmic approach. most of the competitive programming platforms provide python with a time limit of 5 times of c/c++ time limit. but in many cases like if the algorithms are recursive(like segment trees etc) that 5 factor is just not enough. but still I think it would be cool to be able to access internal c functions without any fuss. I can use such feature with heapq too(sift operations), From lepto.python at gmail.com Thu Dec 10 22:04:17 2015 From: lepto.python at gmail.com (oyster) Date: Fri, 11 Dec 2015 11:04:17 +0800 Subject: real usable file/directory operation module? Message-ID: there is shutil module, but I find it limits the user heavily. For example, I want to move 2 directories "a/scene" and "c/scene" to "d", but there is "scene" under d already. Then shutil.move will raise Error, "Destination path '%s' already exists" % real_dst So is there any module, which allow me move/copy like Windows does. for example useableShutil.move('a/scene', 'd', overwite=True) From ben+python at benfinney.id.au Thu Dec 10 22:09:23 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 11 Dec 2015 14:09:23 +1100 Subject: python unit test frame work References: <20151211004021.GA84387@cskk.homeip.net> Message-ID: <85zixh4r6k.fsf@benfinney.id.au> Cameron Simpson writes: > First, as Ben remarks, if one test _depends_ on an earlier one then it > isn't a real unit test. > > On the other hand, if you simply have some simple tests followed by > more complex tests (I have several like this) you have two facilities > to help you. > > Firstly, I have observed that unittest tends to run tests in lexical > order Back on the first hand again, some unit test runners will deliberately *change* the order so your test cases are tested for independence. Really, if your test cases depend on being executed in a particular sequence, the ?unittest? module is a poor fit. -- \ ?Come on, if your religion is so vulnerable that a little bit | `\ of disrespect is going to bring it down, it's not worth | _o__) believing in, frankly.? ?Terry Gilliam, 2005-01-18 | Ben Finney From cs at zip.com.au Thu Dec 10 22:34:44 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 11 Dec 2015 14:34:44 +1100 Subject: python unit test frame work In-Reply-To: <85zixh4r6k.fsf@benfinney.id.au> References: <85zixh4r6k.fsf@benfinney.id.au> Message-ID: <20151211033444.GA60876@cskk.homeip.net> On 11Dec2015 14:09, Ben Finney wrote: >Cameron Simpson writes: >> First, as Ben remarks, if one test _depends_ on an earlier one then it >> isn't a real unit test. >> >> On the other hand, if you simply have some simple tests followed by >> more complex tests (I have several like this) you have two facilities >> to help you. >> >> Firstly, I have observed that unittest tends to run tests in lexical >> order > >Back on the first hand again, some unit test runners will deliberately >*change* the order so your test cases are tested for independence. That's fine. My tests are independent. But it is _handy_ that while building the tests and adding new tests that they are issued in a predictable order. >Really, if your test cases depend on being executed in a particular >sequence, the ?unittest? module is a poor fit. Yes, but that is not the case for me, and quite possibly for the OP. Even if they aren't, he seems savvy and quick to learn and willing to adjust worse practice for better. Cheers, Cameron Simpson From cs at zip.com.au Thu Dec 10 22:43:25 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 11 Dec 2015 14:43:25 +1100 Subject: real usable file/directory operation module? In-Reply-To: References: Message-ID: <20151211034325.GA78323@cskk.homeip.net> On 11Dec2015 11:04, oyster wrote: >there is shutil module, but I find it limits the user heavily. For >example, I want to move 2 directories "a/scene" and "c/scene" to "d", >but there is "scene" under d already. Then shutil.move will raise >Error, "Destination path '%s' already exists" % real_dst > >So is there any module, which allow me move/copy like Windows does. >for example >useableShutil.move('a/scene', 'd', overwite=True) Surely the "subprocess" module, which would let you invoke the Windows copy command. The reason that the stdlib doesn't offer something like that is that there are many many decisions one might make when overlaying one directory tree on another. Consult the manual entry for rsync to get a feel for how many nuances one might want in such a situation. The Window's "copy" command makes one set of choices; they may not fit many users' needs. Instead the stdlib supports the simple "no conflicts" case (which is safe) and leaves it to others to solve harder problems, because there are many ways to "solve" those problems. It is very easy to invoke os.walk on the "copying in" tree and compute the matching paths in the target directory, and then make your own decisions (make missing intermediate directories, overwrite existing files or only if the source is newer or whatever). BTW, if you go this route (write your own) then I suggest you give it a "no action" mode to report what it will do - that way you can check first before destroying your data. Cheers, Cameron Simpson From steve at pearwood.info Fri Dec 11 03:21:22 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Dec 2015 19:21:22 +1100 Subject: SystemError in python 2.5.4 References: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Message-ID: <566a8783$0$1595$c3e8da3$5496439d@news.astraweb.com> On Thu, 10 Dec 2015 10:29 pm, Palpandi wrote: > Hi All, > > I am getting the error mentioned below in python 2.5.4. > > SystemError: \loewis\25\python\Objects\longobject.c:225: bad argument to > internal function. Sounds like your installation of Python is broken. You should never get an internal error like that. If it was working, and now isn't, I would strongly suspect the application has been corrupted, or possibly infected by a virus. I would start with a virus scan and a disk check, and after fixing any faults that come up, re-install Python 2.5 (or upgrade to 2.7, which is much better). -- Steven From dieter at handshake.de Fri Dec 11 03:38:10 2015 From: dieter at handshake.de (dieter) Date: Fri, 11 Dec 2015 09:38:10 +0100 Subject: SystemError in python 2.5.4 References: <5ad8e3de-4ebb-4d60-b106-cd12fdafc0c3@googlegroups.com> Message-ID: <87a8phmlcd.fsf@handshake.de> Palpandi writes: > I am getting the error mentioned below in python 2.5.4. > > SystemError: \loewis\25\python\Objects\longobject.c:225: bad argument to internal function. > > I also ran the same code in python 2.7. > There I am not getting this error. > > I don't know which causes this error. Any solution for this? > > Note: The error is coming from the method call findall(path). I do not have the code for Python 2.5.4 around - therefore, I looked into that for Python 2.4.6. Based on this (older) version, the "SystemError" above may come from the "PyLong_AsLong" function (converting a Python "long" into a "C" "long"). In this case, the error would be caused by provding a wrong parameter (neither Python "int" nor Python "long") to "PyLong_AsLong". At your place, I would have a look at the Python 2.5.4 code and check there where precisely the "SystemError" comes from. Then I would try to find out why it gets wrong (this might require the use of a "C" level debugger). From dieter at handshake.de Fri Dec 11 03:47:20 2015 From: dieter at handshake.de (dieter) Date: Fri, 11 Dec 2015 09:47:20 +0100 Subject: How to use internal python c funtions, from python code References: Message-ID: <876105mkx3.fsf@handshake.de> srinivas devaki writes: > but still I think it would be cool to be able to access internal c > functions without any fuss. I can use such feature with heapq too(sift > operations), Have a look at "Cython". It is a compiler which compiles a language similar to Python with special extensions for an efficient interface to "C" and "C++" into "C"/"C++" source which then can be built into a Python extension module and used from Python like any other Python module. In a "Cython" source, you can quite easily use C functions, among others C functions defined by Python itself. From frank at chagford.com Fri Dec 11 04:21:53 2015 From: frank at chagford.com (Frank Millman) Date: Fri, 11 Dec 2015 11:21:53 +0200 Subject: Problem with sqlite3 and Decimal Message-ID: Hi all I need to store Decimal objects in a sqlite3 database, using Python 3.4 on Windows 7. I followed the instructions here - http://stackoverflow.com/questions/6319409/how-to-convert-python-decimal-to-sqlite-numeric It seemed to work well, but then I hit a problem. Here is a stripped-down example - """ from decimal import Decimal as D import sqlite3 # Decimal adapter (store Decimal in database as str) sqlite3.register_adapter(D, lambda d:str(d)) # Decimal converter (convert back to Decimal on return) sqlite3.register_converter('DEC', lambda s: D(s.decode('utf-8'))) conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute("CREATE TABLE fmtemp (acno INT, bal DEC)") cur.execute("INSERT INTO fmtemp (acno, bal) VALUES (?, ?)", ('A001', D('0'))) sql1 = "SELECT bal FROM fmtemp" sql2 = "UPDATE fmtemp SET bal = bal + ?" while True: print(cur.execute(sql1).fetchone()[0]) cur.execute(sql2, (D('123.45'),)) q = input() if q == 'q': break """ It initialises a decimal value in the database, then loops adding a decimal value and displaying the result. It runs fine for a while, and then the following happens - 5802.15 5925.6 6049.05 6172.4999999999 6295.9499999999 It consistently switches to floating point at the same position. If you carry on for a while, it reverts back to two decimal places. If I initialise the value as D('6049.05'), the next value is 6172.5, so it is not the number itself that causes the problem. I tried displaying the type - even when it switches to 6172.49999999, it is still a Decimal type. I noticed one oddity - I am asking sqlite3 to store the value as a string, but then I am asking it to perform arithmetic on it. Any suggestions will be much appreciated. Frank Millman From a24061 at ducksburg.com Fri Dec 11 06:04:20 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 11 Dec 2015 11:04:20 +0000 Subject: trying to force stdout to utf-8 with errors='ignore' or 'replace' Message-ID: I'm fiddling with a program that reads articles in the news spool using email.parser (standard library) & email_reply_parser.EmailReplyParser (installed with pip). Reading is fine, & I don't get any errors writing output extracted from article bodies *until* I try to suppress invalid characters. This works: if message.is_multipart(): body = message.get_payload(0, True) else: body = message.get_payload() main_body = EmailReplyParser.parse_reply(body) # fix quoted-printable stuff if equals_regex.search(main_body): main_body = quopri.decodestring(main_body) # suppress attribution before quoted text main_body = attrib_regex.sub('>', main_body) # suppress sig main_body = sig_regex.sub('\n', main_body) main_body.strip() stdout.write(main_body + '\n\n') but the stdout includes invalid characters. I tried adding this at the beginning if stdout.encoding is None: writer = codecs.getwriter("utf-8") stdout = writer(stdout, errors='replace') and changing the output line to stdout.write(main_body.encode('utf-8', errors='replace') + '\n\n') but with either or both of those, I get the dreaded "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 562: ordinal not in range(128)". How can I force the output to be in UTF-8 & silently suppress invalid characters? -- Unit tests are like the boy who cried wolf. From __peter__ at web.de Fri Dec 11 06:37:01 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Dec 2015 12:37:01 +0100 Subject: trying to force stdout to utf-8 with errors='ignore' or 'replace' References: Message-ID: Adam Funk wrote: > I'm fiddling with a program that reads articles in the news spool > using email.parser (standard library) & > email_reply_parser.EmailReplyParser (installed with pip). Reading is > fine, & I don't get any errors writing output extracted from article > bodies *until* I try to suppress invalid characters. This works: > > if message.is_multipart(): > body = message.get_payload(0, True) > else: > body = message.get_payload() > main_body = EmailReplyParser.parse_reply(body) > # fix quoted-printable stuff > if equals_regex.search(main_body): > main_body = quopri.decodestring(main_body) > # suppress attribution before quoted text > main_body = attrib_regex.sub('>', main_body) > # suppress sig > main_body = sig_regex.sub('\n', main_body) > main_body.strip() > stdout.write(main_body + '\n\n') > > but the stdout includes invalid characters. I tried adding this at > the beginning > > if stdout.encoding is None: > writer = codecs.getwriter("utf-8") > stdout = writer(stdout, errors='replace') > > and changing the output line to > > stdout.write(main_body.encode('utf-8', errors='replace') + '\n\n') > > but with either or both of those, I get the dreaded > "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position > 562: ordinal not in range(128)". How can I force the output to be in > UTF-8 & silently suppress invalid characters? (I'm assuming you are using Python 2 and that main_body is a unicode instance) Note that you are getting a *decode* error. Either feed unicode to the modified stdout > writer = codecs.getwriter("utf-8") > stdout = writer(stdout, errors='replace') stdout.write(main_body + u'\n\n') or encode manually and write to the original sys.stdout: sys.stdout.write(main_body.encode('utf-8', errors='replace') + '\n\n') From chris at simplistix.co.uk Fri Dec 11 08:01:44 2015 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 11 Dec 2015 13:01:44 +0000 Subject: mush 2.0 released! - Type-based dependency injection for scripts Message-ID: <566AC938.1060304@simplistix.co.uk> Hi All, I'm very happy to announce a new release of Mush, a light weight dependency injection framework aimed at enabling the easy testing and re-use of chunks of code that make up scripts. This release is a re-write dropping all the heuristic callable ordering in favour of building up defined sequences of callables with labelled insertion points. For a worked example of how to use Mush to reduce the copy'n'paste in your scripts, please see here: http://mush.readthedocs.org/en/latest/examples.html Full docs are here: http://mush.readthedocs.org/ Downloads are here: https://pypi.python.org/pypi/mush Compatible with Python 2.7, 3.3+: https://travis-ci.org/Simplistix/mush Any problems, please give me a shout on the simplistix at googlegroups.com list! cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From lac at openend.se Fri Dec 11 08:45:42 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 11 Dec 2015 14:45:42 +0100 Subject: Problem with sqlite3 and Decimal (fwd) Message-ID: <201512111345.tBBDjgae025001@fido.openend.se> From python-list. Very weird. Another reason not to use sqlite3 ------- Forwarded Message To: python-list at python.org From: "Frank Millman" Subject: Problem with sqlite3 and Decimal Date: Fri, 11 Dec 2015 11:21:53 +0200 Lines: 71 Hi all I need to store Decimal objects in a sqlite3 database, using Python 3.4 on Windows 7. I followed the instructions here - http://stackoverflow.com/questions/6319409/how-to-convert-python-decimal-to-sqlite-numeric It seemed to work well, but then I hit a problem. Here is a stripped-down example - """ from decimal import Decimal as D import sqlite3 # Decimal adapter (store Decimal in database as str) sqlite3.register_adapter(D, lambda d:str(d)) # Decimal converter (convert back to Decimal on return) sqlite3.register_converter('DEC', lambda s: D(s.decode('utf-8'))) conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute("CREATE TABLE fmtemp (acno INT, bal DEC)") cur.execute("INSERT INTO fmtemp (acno, bal) VALUES (?, ?)", ('A001', D('0'))) sql1 = "SELECT bal FROM fmtemp" sql2 = "UPDATE fmtemp SET bal = bal + ?" while True: print(cur.execute(sql1).fetchone()[0]) cur.execute(sql2, (D('123.45'),)) q = input() if q == 'q': break """ It initialises a decimal value in the database, then loops adding a decimal value and displaying the result. It runs fine for a while, and then the following happens - 5802.15 5925.6 6049.05 6172.4999999999 6295.9499999999 It consistently switches to floating point at the same position. If you carry on for a while, it reverts back to two decimal places. If I initialise the value as D('6049.05'), the next value is 6172.5, so it is not the number itself that causes the problem. I tried displaying the type - even when it switches to 6172.49999999, it is still a Decimal type. I noticed one oddity - I am asking sqlite3 to store the value as a string, but then I am asking it to perform arithmetic on it. Any suggestions will be much appreciated. Frank Millman - -- https://mail.python.org/mailman/listinfo/python-list ------- End of Forwarded Message From ikorot01 at gmail.com Fri Dec 11 09:04:59 2015 From: ikorot01 at gmail.com (Igor Korot) Date: Fri, 11 Dec 2015 09:04:59 -0500 Subject: Problem with sqlite3 and Decimal (fwd) In-Reply-To: <201512111345.tBBDjgae025001@fido.openend.se> References: <201512111345.tBBDjgae025001@fido.openend.se> Message-ID: Hi, On Fri, Dec 11, 2015 at 8:45 AM, Laura Creighton wrote: > From python-list. > Very weird. > Another reason not to use sqlite3 > > ------- Forwarded Message > > To: python-list at python.org > From: "Frank Millman" > Subject: Problem with sqlite3 and Decimal > Date: Fri, 11 Dec 2015 11:21:53 +0200 > Lines: 71 > > Hi all > > I need to store Decimal objects in a sqlite3 database, using Python 3.4 on > Windows 7. > > I followed the instructions here - > > http://stackoverflow.com/questions/6319409/how-to-convert-python-decimal-to-sqlite-numeric > > It seemed to work well, but then I hit a problem. Here is a stripped-down > example - > > """ > from decimal import Decimal as D > import sqlite3 > > # Decimal adapter (store Decimal in database as str) > sqlite3.register_adapter(D, lambda d:str(d)) > > # Decimal converter (convert back to Decimal on return) > sqlite3.register_converter('DEC', lambda s: D(s.decode('utf-8'))) > > conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES) > cur = conn.cursor() > > cur.execute("CREATE TABLE fmtemp (acno INT, bal DEC)") > cur.execute("INSERT INTO fmtemp (acno, bal) VALUES (?, ?)", ('A001', > D('0'))) > > sql1 = "SELECT bal FROM fmtemp" > sql2 = "UPDATE fmtemp SET bal = bal + ?" > > while True: > print(cur.execute(sql1).fetchone()[0]) > cur.execute(sql2, (D('123.45'),)) > q = input() > if q == 'q': > break > """ > > It initialises a decimal value in the database, then loops adding a decimal > value and displaying the result. > > It runs fine for a while, and then the following happens - > > 5802.15 > > 5925.6 > > 6049.05 > > 6172.4999999999 > > 6295.9499999999 > > It consistently switches to floating point at the same position. If you > carry on for a while, it reverts back to two decimal places. > > If I initialise the value as D('6049.05'), the next value is 6172.5, so it > is not the number itself that causes the problem. > > I tried displaying the type - even when it switches to 6172.49999999, it is > still a Decimal type. > > I noticed one oddity - I am asking sqlite3 to store the value as a string, > but then I am asking it to perform arithmetic on it. Is there a reason you are saving it as the string? What happens when you save it as decimal? Thank you. > > Any suggestions will be much appreciated. > > Frank Millman > > > - -- > https://mail.python.org/mailman/listinfo/python-list > > ------- End of Forwarded Message > -- > https://mail.python.org/mailman/listinfo/python-list From frank at chagford.com Fri Dec 11 09:27:27 2015 From: frank at chagford.com (Frank Millman) Date: Fri, 11 Dec 2015 16:27:27 +0200 Subject: Problem with sqlite3 and Decimal (fwd) In-Reply-To: References: <201512111345.tBBDjgae025001@fido.openend.se> Message-ID: "Igor Korot" wrote in message news:CA+FnnTyaLLEsYGU7v2BreySDOQ1rVsMzJ=5f4iQTLW3=tn=E+Q at mail.gmail.com... > Hi, > > > To: python-list at python.org > > From: "Frank Millman" > > Subject: Problem with sqlite3 and Decimal > > Date: Fri, 11 Dec 2015 11:21:53 +0200 > > Lines: 71 > > > > Hi all > > > > I need to store Decimal objects in a sqlite3 database, using Python 3.4 > > on > > Windows 7. > > [...] > > > > > I noticed one oddity - I am asking sqlite3 to store the value as a > > string, > > but then I am asking it to perform arithmetic on it. > > Is there a reason you are saving it as the string? > What happens when you save it as decimal? > Well, maybe you know something that I don't, but my understanding is that sqlite3 has a very limited range of supported data types, and decimal is not one of them. The stackoverflow article explains how to emulate a decimal type, and it works well most of the time. I found that I could reproduce the problem using sqlite3 directly, without using Python, so I have sent a post to the sqlite3 mailing list. I will report back with any info received. Frank From hienmizu at gmail.com Fri Dec 11 09:29:33 2015 From: hienmizu at gmail.com (hienmizu at gmail.com) Date: Fri, 11 Dec 2015 06:29:33 -0800 (PST) Subject: python script for dwonload free anything? Message-ID: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> i want create script for download free 3d model from nonecg.com like https://github.com/nishad/udemy-dl-windows , this script download free udemy video lesson. Anyone can tell e, how to create script like that? From ikorot01 at gmail.com Fri Dec 11 09:41:05 2015 From: ikorot01 at gmail.com (Igor Korot) Date: Fri, 11 Dec 2015 09:41:05 -0500 Subject: Problem with sqlite3 and Decimal (fwd) In-Reply-To: References: <201512111345.tBBDjgae025001@fido.openend.se> Message-ID: Hi, Frank, On Fri, Dec 11, 2015 at 9:27 AM, Frank Millman wrote: > "Igor Korot" wrote in message > news:CA+FnnTyaLLEsYGU7v2BreySDOQ1rVsMzJ=5f4iQTLW3=tn=E+Q at mail.gmail.com... > >> Hi, >> >> > To: python-list at python.org >> > From: "Frank Millman" >> > Subject: Problem with sqlite3 and Decimal >> > Date: Fri, 11 Dec 2015 11:21:53 +0200 >> > Lines: 71 >> > >> > Hi all >> > >> > I need to store Decimal objects in a sqlite3 database, using Python 3.4 >> > > on >> > Windows 7. >> > > > [...] >> >> >> > >> > I noticed one oddity - I am asking sqlite3 to store the value as a > >> > string, >> > but then I am asking it to perform arithmetic on it. >> >> Is there a reason you are saving it as the string? >> What happens when you save it as decimal? >> > > Well, maybe you know something that I don't, but my understanding is that > sqlite3 has a very limited range of supported data types, and decimal is not > one of them. > > The stackoverflow article explains how to emulate a decimal type, and it > works well most of the time. > > I found that I could reproduce the problem using sqlite3 directly, without > using Python, so I have sent a post to the sqlite3 mailing list. I will > report back with any info received. Yes, I saw your post to sqlite3 ML. And I do know that by default sqlite3 does not have many types supported. However, all you need to do is save it as DECIMAL(10,2). It is supported is sqlite3 and it will have NUMERIC affinity (ref 1) or REAL (ref 2), which means the data will be stored as decimals and not a string. Ref.: 1) http://www.tutorialspoint.com/sqlite/sqlite_data_types.htm 2) https://www.sqlite.org/datatype3.html Thank you. > > Frank > > > -- > https://mail.python.org/mailman/listinfo/python-list From lac at openend.se Fri Dec 11 09:46:19 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 11 Dec 2015 15:46:19 +0100 Subject: python script for dwonload free anything? In-Reply-To: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> References: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> Message-ID: <201512111446.tBBEkJMB025919@fido.openend.se> In a message of Fri, 11 Dec 2015 06:29:33 -0800, hienmizu at gmail.com writes: >i want create script for download free 3d model from nonecg.com like https://github.com/nishad/udemy-dl-windows , this script download free udemy video lesson. Anyone can tell e, how to create script like that? >-- >https://mail.python.org/mailman/listinfo/python-list I think you will find this PyPi project interesting. https://github.com/rg3/youtube-dl/ Laura From breamoreboy at yahoo.co.uk Fri Dec 11 09:47:06 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 11 Dec 2015 14:47:06 +0000 Subject: python script for dwonload free anything? In-Reply-To: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> References: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> Message-ID: On 11/12/2015 14:29, hienmizu at gmail.com wrote: > i want create script for download free 3d model from nonecg.com like https://github.com/nishad/udemy-dl-windows , this script download free udemy video lesson. Anyone can tell e, how to create script like that? > Any (semi)decent IDE and/or editor should help you to create a script. Worst case if you're on Windows there's always Notepad but I would not recommend it. If you need more data you'll need a better question so I suggest you read this http://www.catb.org/esr/faqs/smart-questions.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From hienmizu at gmail.com Fri Dec 11 10:32:44 2015 From: hienmizu at gmail.com (hienmizu at gmail.com) Date: Fri, 11 Dec 2015 07:32:44 -0800 (PST) Subject: python script for dwonload free anything? In-Reply-To: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> References: <0c3625dd-6b61-4c54-a380-29da795a688e@googlegroups.com> Message-ID: <78a801eb-8b1f-40e3-9fda-b90a3212b1f2@googlegroups.com> thank you laura, but i know this paid 3d model: http://www.nonecg.com/tokyo-shibuya.html. do you know that From ictezy at gmail.com Fri Dec 11 11:10:52 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 08:10:52 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> Message-ID: <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Dear All, Very Sorry for the my mistake here. I code here with mu question ... My Question: A,B=C,D=10,11 print(A,B,C,D) #(10,11,10,11) --> This is OK! a=1; b=2 a,b=b,a print(a,b) # (1,2) --> This is OK! x,y=y,x=2,3 print(x,y) # (3,2) --> Question: How to explain it? # Not understand this process. Pl explain ... From robin.koch at t-online.de Fri Dec 11 11:24:28 2015 From: robin.koch at t-online.de (Robin Koch) Date: Fri, 11 Dec 2015 17:24:28 +0100 Subject: Python variable assigning problems... In-Reply-To: <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: Am 11.12.2015 um 17:10 schrieb ICT Ezy: > Dear All, > Very Sorry for the my mistake here. I code here with mu question ... > > My Question: > > A,B=C,D=10,11 > print(A,B,C,D) > #(10,11,10,11) --> This is OK! > > a=1; b=2 > a,b=b,a > print(a,b) > # (1,2) --> This is OK! > > x,y=y,x=2,3 > print(x,y) > # (3,2) --> Question: How to explain it? > # Not understand this process. Pl explain ... What else would you expect? Assigning goes from right to left: x,y=y,x=2,3 <=> y, x = 2, 3 x, y = y, x Otherwise the assignment x, y = y, x would not make any sense, since x and y haven't any values yet. And the execution from right to left is also a good choice, because one would like to do something like: x = y = z = 0 Again, assigning from left to right woud lead to errors. -- Robin Koch From hammj at vmware.com Fri Dec 11 11:30:32 2015 From: hammj at vmware.com (Jay Hamm) Date: Fri, 11 Dec 2015 16:30:32 +0000 Subject: python 351x64 Message-ID: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> Hi I was trying to use your windows version of python 3.5.1 x64. It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. Since about every other admin I've ever known uses notepad++, you might want to fix this. Also your installer fails to set the permissions correctly: H:\>py -m pip install requests Collecting requests Downloading requests-2.8.1-py2.py3-none-any.whl (497kB) 100% |################################| 499kB 875kB/s Installing collected packages: requests Exception: Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files isolated=self.isolated, File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 310, in clobber ensure_dir(destdir) File "C:\Program Files\Python35\lib\site-packages\pip\utils\__init__.py", line 71, in ensure_dir os.makedirs(path) File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' Once I gave myself control it started working. This is pretty shoddy for released software. Thanks, Jacob Hamm (Jay) VCP-DCV, RHCE Senior Cloud Services Engineer - VMware vCloud Air 380 Interlocken Crescent Blvd - Ste 500, Broomfield CO 80021 Office 303 942 4638 - hammj at vmware.com Want to learn more about VMware vCloud Air? Go to http://vcloud.vmware.com/tutorials [vCloudAir] From ian.g.kelly at gmail.com Fri Dec 11 11:36:45 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 11 Dec 2015 09:36:45 -0700 Subject: Python variable assigning problems... In-Reply-To: <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: On Fri, Dec 11, 2015 at 9:10 AM, ICT Ezy wrote: > Dear All, > Very Sorry for the my mistake here. I code here with mu question ... > > My Question: > > A,B=C,D=10,11 > print(A,B,C,D) > #(10,11,10,11) --> This is OK! > > a=1; b=2 > a,b=b,a > print(a,b) > # (1,2) --> This is OK! This actually results in (2, 1), which is expected; you assign 1 to a and 2 to b and then swap the values. > x,y=y,x=2,3 > print(x,y) > # (3,2) --> Question: How to explain it? > # Not understand this process. Pl explain ... The assignments happen from left to right. First, (2,3) is assigned to (x,y), which has the effect of assigning 2 to x and then 3 to y. Next, (2,3) is assigned to (y,x), whas the effect of assigning 2 to y and then 3 to x, overwriting the previous assignments. Then when you do the print, x has the value 3, and y has the value 2. From ian.g.kelly at gmail.com Fri Dec 11 11:39:17 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 11 Dec 2015 09:39:17 -0700 Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch wrote: > Assigning goes from right to left: > > x,y=y,x=2,3 > > <=> > > y, x = 2, 3 > x, y = y, x > > Otherwise the assignment x, y = y, x would not make any sense, since x and y > haven't any values yet. > > And the execution from right to left is also a good choice, because one > would like to do something like: > > x = y = z = 0 > > Again, assigning from left to right woud lead to errors. No, it actually happens left to right. "x = y = z = 0" means "assign 0 to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign 0 to z, then assign z to y, etc." This works: >>> d = d['foo'] = {} >>> d {'foo': {...}} This doesn't: >>> del d >>> d['foo'] = d = {} Traceback (most recent call last): File "", line 1, in NameError: name 'd' is not defined From a24061 at ducksburg.com Fri Dec 11 11:54:27 2015 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 11 Dec 2015 16:54:27 +0000 Subject: trying to force stdout to utf-8 with errors='ignore' or 'replace' References: Message-ID: <3nbrjcxcaf.ln2@news.ducksburg.com> On 2015-12-11, Peter Otten wrote: > Adam Funk wrote: >> but with either or both of those, I get the dreaded >> "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position >> 562: ordinal not in range(128)". How can I force the output to be in >> UTF-8 & silently suppress invalid characters? > > (I'm assuming you are using Python 2 and that main_body is a unicode > instance) The short answer turned out to be 'switch to Python 3', which I think is what I'll do from now on unless I absolutely need a library that isn't available there. (AFAICT, the email parser in 2.7 returns the body as a bytestring & doesn't actually look at the Content-Type header, & trying to decode the body with that just made it barf in different places.) -- Science is what we understand well enough to explain to a computer. Art is everything else we do. --- Donald Knuth From breamoreboy at yahoo.co.uk Fri Dec 11 12:15:19 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 11 Dec 2015 17:15:19 +0000 Subject: python 351x64 In-Reply-To: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> References: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> Message-ID: On 11/12/2015 16:30, Jay Hamm wrote: > Hi > > I was trying to use your windows version of python 3.5.1 x64. > > It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. > > This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. > > Since about every other admin I've ever known uses notepad++, you might want to fix this. > > Also your installer fails to set the permissions correctly: > > H:\>py -m pip install requests > Collecting requests > Downloading requests-2.8.1-py2.py3-none-any.whl (497kB) > 100% |################################| 499kB 875kB/s > Installing collected packages: requests > Exception: > Traceback (most recent call last): > File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) > File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files isolated=self.isolated, > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 310, in clobber ensure_dir(destdir) > File "C:\Program Files\Python35\lib\site-packages\pip\utils\__init__.py", line 71, in ensure_dir os.makedirs(path) > File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' > > Once I gave myself control it started working. > > This is pretty shoddy for released software. > Thanks, > Jacob Hamm (Jay) VCP-DCV, RHCE > Senior Cloud Services Engineer - VMware vCloud Air > > 380 Interlocken Crescent Blvd - Ste 500, Broomfield CO 80021 > Office 303 942 4638 - hammj at vmware.com > Want to learn more about VMware vCloud Air? > Go to http://vcloud.vmware.com/tutorials > [vCloudAir] > Patches are always welcome. How much did you pay for this shoddy software? -- 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 Dec 11 12:17:27 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 11 Dec 2015 11:17:27 -0600 Subject: python 351x64 In-Reply-To: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> References: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> Message-ID: On Fri, Dec 11, 2015 at 10:30 AM, Jay Hamm wrote: > Hi > > I was trying to use your windows version of python 3.5.1 x64. > > It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. > > This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. api-ms-win-crt-runtime-I1-1-0.dll is part of the Universal CRT; I don't see what the relation between Python and Notepad++ is. This sounds like an issue with Notepad++/NppFTP, not Python. > Since about every other admin I've ever known uses notepad++, you might want to fix this. > > Also your installer fails to set the permissions correctly: > > H:\>py -m pip install requests > Collecting requests > Downloading requests-2.8.1-py2.py3-none-any.whl (497kB) > 100% |################################| 499kB 875kB/s > Installing collected packages: requests > Exception: > Traceback (most recent call last): > File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) > File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files isolated=self.isolated, > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 310, in clobber ensure_dir(destdir) > File "C:\Program Files\Python35\lib\site-packages\pip\utils\__init__.py", line 71, in ensure_dir os.makedirs(path) > File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' > > Once I gave myself control it started working. The point of installing in C:\Program Files\ is that non-admin users can't write there. If you want a package installed in the global site-packages, do it as an administrator or install Python somewhere else (like C:\Python35\ as previous versions did, but be aware of the security implications). Otherwise, create a local venv (`py -3.5 -m venv path\to\venv`), install your packages there, and use it. > This is pretty shoddy for released software. That seems uncalled for. -- Zach From steve at pearwood.info Fri Dec 11 12:18:39 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Dec 2015 04:18:39 +1100 Subject: python 351x64 References: Message-ID: <566b0571$0$1601$c3e8da3$5496439d@news.astraweb.com> Hi Jay, and welcome,! On Sat, 12 Dec 2015 03:30 am, Jay Hamm wrote: > Hi > > I was trying to use your windows version of python 3.5.1 x64. > > It has a conflict with a notepad++ plugin NppFTP giving > api-ms-win-crt-runtime-I1-1-0.dll error on start up. > > This seems pretty well documented on the web. The work around is to delete > the plugin and reinstall since it borks the install. I think your definition of "well documented on the web" and mine differs greatly. I've spent ten minutes searching for various combinations of "python", "conflict", "nppftp", "api-ms-win-crt-runtime-I1-1-0.dll" etc. with absolutely no relevant hits. Would you mind telling us where you found this documentation? I did find this: https://notepad-plus-plus.org/community/topic/7282/notepad-system-error-on-startup-api-ms-win-crt-runtime-l1-1-0-dll-is-missing but there's no indication that this has anything to do with Python. > Since about every other admin I've ever known uses notepad++, you might > want to fix this. I'm not a Windows expert, but I can't imagine how installing Python would uninstall api-ms-win-crt-runtime-I1-1-0.dll. But if it does, then it probably shouldn't. > Also your installer fails to set the permissions correctly: > > H:\>py -m pip install requests [...] > File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs > mkdir(name, mode) PermissionError: [WinError 5] Access is denied: > 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' > > Once I gave myself control it started working. What do you mean, you gave yourself "control?" Do you mean write permission? I would expect that if you want to install to the system-wide site-packages directory, you should be running as Administrator or other user with permission to write to that directory. If you don't have write permission to a directory when you are trying to install software, of course the installation will fail. What makes you think that this is a failure of the installer? I'm not a Windows expert, but the behaviour looks correct to me. > This is pretty shoddy for released software. Well, some of us have used VMware in the past, and we could discuss "pretty shoddy" bugs all day *cough* ESXi backup bug *cough* vcenter remote execution exploit *cough* but since we're all friends here, how about instead of trying to be insulting, let's try to determine exactly what the alleged bug is so we can create a ticket and get it fixed? -- Steven From Dick.Ginga at PERKINELMER.COM Fri Dec 11 12:21:11 2015 From: Dick.Ginga at PERKINELMER.COM (Ginga, Dick) Date: Fri, 11 Dec 2015 17:21:11 +0000 Subject: wrappers for C/C++ Message-ID: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> I have inherited a product build that uses SWIG to product wrapper libraries for our C/C++ code. It currently builds these wrappers for 2.5, 2.6, 3.1 and 3.2. Is it necessary to have version specific wrappers? From ian.g.kelly at gmail.com Fri Dec 11 12:21:58 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 11 Dec 2015 10:21:58 -0700 Subject: python 351x64 In-Reply-To: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> References: <0999009350ee4c4f8aee367bbd89abb5@EX13-MBX-031.vmware.com> Message-ID: On Fri, Dec 11, 2015 at 9:30 AM, Jay Hamm wrote: > Hi > > I was trying to use your windows version of python 3.5.1 x64. > > It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. > > This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. > > Since about every other admin I've ever known uses notepad++, you might want to fix this. Laura Creighton has filed an issue based on your post to the Python issue tracker at http://bugs.python.org/issue25842. Would you please add some details on this issue? Googling for "python nppftp" failed to turn up anything useful for me. > Also your installer fails to set the permissions correctly: How do you expect them to be set? From robin.koch at t-online.de Fri Dec 11 12:52:48 2015 From: robin.koch at t-online.de (Robin Koch) Date: Fri, 11 Dec 2015 18:52:48 +0100 Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: Am 11.12.2015 um 17:39 schrieb Ian Kelly: > On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch wrote: >> Assigning goes from right to left: >> >> x,y=y,x=2,3 >> >> <=> >> >> y, x = 2, 3 >> x, y = y, x >> >> Otherwise the assignment x, y = y, x would not make any sense, since x and y >> haven't any values yet. >> >> And the execution from right to left is also a good choice, because one >> would like to do something like: >> >> x = y = z = 0 >> >> Again, assigning from left to right woud lead to errors. > > No, it actually happens left to right. "x = y = z = 0" means "assign 0 > to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign > 0 to z, then assign z to y, etc." Oh. Ok, then, thanks for this correction. Although it's consequent to use left-to-right precedence it's a little counter intuitive in the sense that the rightmost and leftmost objects interact. Especially with a background in mathematics. :-) > This works: > >>>> d = d['foo'] = {} >>>> d > {'foo': {...}} > > This doesn't: > >>>> del d >>>> d['foo'] = d = {} > Traceback (most recent call last): > File "", line 1, in > NameError: name 'd' is not defined Good to know! Thank you. -- Robin Koch From hammj at vmware.com Fri Dec 11 12:53:04 2015 From: hammj at vmware.com (Jay Hamm) Date: Fri, 11 Dec 2015 17:53:04 +0000 Subject: python 351x64 Message-ID: <91aa9e024c8f48d6a3212af00b1360a2@EX13-MBX-031.vmware.com> It is an issue that borks your install. That seems like your issue which involves notepad++. You might want to talk with them about it or more likely since they've not fixed it in a while - develop a work around or at least a message that pops up and asks if they want it fixed so the install succeeds. Likewise if you have an option to install for all uses, then it should work without further intervention. As for unfair, is this production software or is it a toy? If it is a toy, I withdraw my comment. -----Original Message----- From: zachary.ware at gmail.com [mailto:zachary.ware at gmail.com] On Behalf Of Zachary Ware Sent: Friday, December 11, 2015 10:17 AM To: python-list at python.org Cc: Jay Hamm Subject: Re: python 351x64 On Fri, Dec 11, 2015 at 10:30 AM, Jay Hamm wrote: > Hi > > I was trying to use your windows version of python 3.5.1 x64. > > It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. > > This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. api-ms-win-crt-runtime-I1-1-0.dll is part of the Universal CRT; I don't see what the relation between Python and Notepad++ is. This sounds like an issue with Notepad++/NppFTP, not Python. > Since about every other admin I've ever known uses notepad++, you might want to fix this. > > Also your installer fails to set the permissions correctly: > > H:\>py -m pip install requests > Collecting requests > Downloading requests-2.8.1-py2.py3-none-any.whl (497kB) > 100% |################################| 499kB 875kB/s Installing > collected packages: requests > Exception: > Traceback (most recent call last): > File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) > File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) > File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files isolated=self.isolated, > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) > File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 310, in clobber ensure_dir(destdir) > File "C:\Program Files\Python35\lib\site-packages\pip\utils\__init__.py", line 71, in ensure_dir os.makedirs(path) > File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' > > Once I gave myself control it started working. The point of installing in C:\Program Files\ is that non-admin users can't write there. If you want a package installed in the global site-packages, do it as an administrator or install Python somewhere else (like C:\Python35\ as previous versions did, but be aware of the security implications). Otherwise, create a local venv (`py -3.5 -m venv path\to\venv`), install your packages there, and use it. > This is pretty shoddy for released software. That seems uncalled for. -- Zach From ictezy at gmail.com Fri Dec 11 13:00:22 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:00:22 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: <52c10154-fa91-4f47-af9e-58c3c9aa6588@googlegroups.com> On Friday, December 11, 2015 at 8:24:45 AM UTC-8, Robin Koch wrote: > Am 11.12.2015 um 17:10 schrieb ICT Ezy: > > Dear All, > > Very Sorry for the my mistake here. I code here with mu question ... > > > > My Question: > > > > A,B=C,D=10,11 > > print(A,B,C,D) > > #(10,11,10,11) --> This is OK! > > > > a=1; b=2 > > a,b=b,a > > print(a,b) > > # (1,2) --> This is OK! > > > > x,y=y,x=2,3 > > print(x,y) > > # (3,2) --> Question: How to explain it? > > # Not understand this process. Pl explain ... > > What else would you expect? > > Assigning goes from right to left: > > x,y=y,x=2,3 > > <=> > > y, x = 2, 3 > x, y = y, x > > Otherwise the assignment x, y = y, x would not make any sense, since x > and y haven't any values yet. > > And the execution from right to left is also a good choice, because one > would like to do something like: > > x = y = z = 0 > > Again, assigning from left to right woud lead to errors. > > -- > Robin Koch Thank you very much your answer, I had not known assignment id Right2Left before. I done it. From ictezy at gmail.com Fri Dec 11 13:05:14 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:05:14 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: On Friday, December 11, 2015 at 8:40:18 AM UTC-8, Ian wrote: > On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch wrote: > > Assigning goes from right to left: > > > > x,y=y,x=2,3 > > > > <=> > > > > y, x = 2, 3 > > x, y = y, x > > > > Otherwise the assignment x, y = y, x would not make any sense, since x and y > > haven't any values yet. > > > > And the execution from right to left is also a good choice, because one > > would like to do something like: > > > > x = y = z = 0 > > > > Again, assigning from left to right woud lead to errors. > > No, it actually happens left to right. "x = y = z = 0" means "assign 0 > to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign > 0 to z, then assign z to y, etc." This works: > > >>> d = d['foo'] = {} > >>> d > {'foo': {...}} > > This doesn't: > > >>> del d > >>> d['foo'] = d = {} > Traceback (most recent call last): > File "", line 1, in > NameError: name 'd' is not defined Deat Ian, Thank you very much your answer, but above answer from Robin Koch and your answer is different. What's the actually process here? I agree with Robin Koch, but your answer is correct. Pl explain differences ? From torriem at gmail.com Fri Dec 11 13:10:22 2015 From: torriem at gmail.com (Michael Torrie) Date: Fri, 11 Dec 2015 11:10:22 -0700 Subject: Python variable assigning problems... In-Reply-To: <52c10154-fa91-4f47-af9e-58c3c9aa6588@googlegroups.com> References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> <52c10154-fa91-4f47-af9e-58c3c9aa6588@googlegroups.com> Message-ID: <566B118E.5010708@gmail.com> On 12/11/2015 11:00 AM, ICT Ezy wrote: > Thank you very much your answer, I had not known assignment id Right2Left before. I done it. Except that Robin was mistaken. Assignment is indeed left to right, though what's being assigned is on the right. > From torriem at gmail.com Fri Dec 11 13:20:07 2015 From: torriem at gmail.com (Michael Torrie) Date: Fri, 11 Dec 2015 11:20:07 -0700 Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: <566B13D7.3060506@gmail.com> On 12/11/2015 11:05 AM, ICT Ezy wrote: > Deat Ian, Thank you very much your answer, but above answer from > Robin Koch and your answer is different. What's the actually process > here? I agree with Robin Koch, but your answer is correct. Pl explain > differences ? If you go re-read the answers, you'll find Ian has explained why Robin was incorrect, and Robin acknowledged he got it wrong. From ictezy at gmail.com Fri Dec 11 13:23:59 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:23:59 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: <454d2836-4bd9-46f2-8407-6764746f8d3e@googlegroups.com> On Friday, December 11, 2015 at 9:53:10 AM UTC-8, Robin Koch wrote: > Am 11.12.2015 um 17:39 schrieb Ian Kelly: > > On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch wrote: > >> Assigning goes from right to left: > >> > >> x,y=y,x=2,3 > >> > >> <=> > >> > >> y, x = 2, 3 > >> x, y = y, x > >> > >> Otherwise the assignment x, y = y, x would not make any sense, since x and y > >> haven't any values yet. > >> > >> And the execution from right to left is also a good choice, because one > >> would like to do something like: > >> > >> x = y = z = 0 > >> > >> Again, assigning from left to right woud lead to errors. > > > > No, it actually happens left to right. "x = y = z = 0" means "assign 0 > > to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign > > 0 to z, then assign z to y, etc." > > Oh. Ok, then, thanks for this correction. > Although it's consequent to use left-to-right precedence it's a little > counter intuitive in the sense that the rightmost and leftmost objects > interact. Especially with a background in mathematics. :-) > > > This works: > > > >>>> d = d['foo'] = {} > >>>> d > > {'foo': {...}} > > > > This doesn't: > > > >>>> del d > >>>> d['foo'] = d = {} > > Traceback (most recent call last): > > File "", line 1, in > > NameError: name 'd' is not defined > > Good to know! Thank you. > > -- > Robin Koch Yeh, Your discussion is very good, really I understood correct process, Thank you very much all of you! From ictezy at gmail.com Fri Dec 11 13:25:29 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:25:29 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: <44dc2682-0c94-4b82-bf5b-ca2016cda1b5@googlegroups.com> On Friday, December 11, 2015 at 10:20:30 AM UTC-8, Michael Torrie wrote: > On 12/11/2015 11:05 AM, ICT Ezy wrote: > > Deat Ian, Thank you very much your answer, but above answer from > > Robin Koch and your answer is different. What's the actually process > > here? I agree with Robin Koch, but your answer is correct. Pl explain > > differences ? > > If you go re-read the answers, you'll find Ian has explained why Robin > was incorrect, and Robin acknowledged he got it wrong. OK. I got it!!! Yeh, Your discussion is very good, really I understood correct process, Thank you very much all of you! From harvesting at is.invalid Fri Dec 11 13:27:18 2015 From: harvesting at is.invalid (Jussi Piitulainen) Date: Fri, 11 Dec 2015 20:27:18 +0200 Subject: Python variable assigning problems... References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: ICT Ezy writes: > On Friday, December 11, 2015 at 8:40:18 AM UTC-8, Ian wrote: >> >> No, it actually happens left to right. "x = y = z = 0" means "assign >> 0 to x, then assign 0 to y, then assign 0 to z." It doesn't mean >> "assign 0 to z, then assign z to y, etc." This works: >> >> >>> d = d['foo'] = {} >> >>> d >> {'foo': {...}} >> >> This doesn't: >> >> >>> del d >> >>> d['foo'] = d = {} >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'd' is not defined > > Deat Ian, > Thank you very much your answer, but > above answer from Robin Koch and your answer is different. What's the > actually process here? I agree with Robin Koch, but your answer is > correct. Pl explain differences ? Python language reference, at 7.2 Assignment statements, says this: # An assignment statement evaluates the expression list (remember that # this can be a single expression or a comma-separated list, the latter # yielding a tuple) and assigns the single resulting object to each of # the target lists, from left to right. To simplify a bit, it's talking about a statement of this form: target_list = target_list = target_list = expression_list And it says what Ian said: the value of the expression is assigned to each target *from left to right*. From rosuav at gmail.com Fri Dec 11 13:29:08 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 05:29:08 +1100 Subject: wrappers for C/C++ In-Reply-To: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> References: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> Message-ID: On Sat, Dec 12, 2015 at 4:21 AM, Ginga, Dick wrote: > I have inherited a product build that uses SWIG to product wrapper libraries for our C/C++ code. It currently builds these wrappers for 2.5, 2.6, 3.1 and 3.2. > > Is it necessary to have version specific wrappers? Yes, it is, because of the way Python's internals work. But you can probably build them all from the same source code. I'm not sure whether you mean that those four are the _only_ versions it's building for, or if you noted them as being particularly old versions still being built for. Either way, you should be in full control of your version support; if this is an internal project, you could simply stipulate that only one version of Python is supported (or maybe two - 2.7 and one 3.x), and save yourself some build hassles. If you're posting it on PyPI, you can put the source code out there and let Unix users build their own, and then you need only worry about Windows; I haven't seen confirmation yet (as there's no official 3.6 builds), but supporting "3.5+" should be possible from a single binary. (You would still need a separate binary for 2.7, though.) ChrisA From ictezy at gmail.com Fri Dec 11 13:35:38 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:35:38 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: Message-ID: <7a25bebc-cace-4b53-9961-442e50fa9e2c@googlegroups.com> On Wednesday, December 9, 2015 at 1:45:26 PM UTC-8, Mark Lawrence wrote: > On 09/12/2015 17:51, ICT Ezy wrote: > > Pl explain me how to connect the MYSQL database to Python program? > > > > Use a search engine. Then run up an editor, write some code, run said > code. If you then have problems state your OS, Python version and > provide us with the full traceback. > > An alternative is to write a cheque for (say) GBP 1000 payable to the > Python Software Foundation and if you're lucky somebody will do your > homework for you. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence Now, I installed MYSQLDB and following code was done correctly. #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","TESTDB") # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print "Database version : %s " % data # disconnect from server db.close() Then done following SQL statements: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() Then not correctly work following SQL statements: >>> import MySQLdb >>> db = MySQLdb.connect("localhost","TESTDB" ) >>> cursor = db.cursor() >>> sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" >>> cursor.execute(sql) Traceback (most recent call last): File "", line 1, in cursor.execute(sql) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1046, "Aucune base n'a \xe9t\xe9 s\xe9lectionn\xe9e") >>> How to solve the problems. pl explain me From ictezy at gmail.com Fri Dec 11 13:36:17 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:36:17 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: Message-ID: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: > On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > > Pl explain me how to connect the MYSQL database to Python program? > > You start by looking for a module that lets you do that. You can use > your favourite web search engine, or go directly to PyPI. > > Then you learn how to use that module, including learning SQL if you > don't already know it. > > ChrisA Now, I installed MYSQLDB and following code was done correctly. #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","TESTDB") # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print "Database version : %s " % data # disconnect from server db.close() Then done following SQL statements: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() Then not correctly work following SQL statements: >>> import MySQLdb >>> db = MySQLdb.connect("localhost","TESTDB" ) >>> cursor = db.cursor() >>> sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" >>> cursor.execute(sql) Traceback (most recent call last): File "", line 1, in cursor.execute(sql) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1046, "Aucune base n'a \xe9t\xe9 s\xe9lectionn\xe9e") >>> How to solve the problems. pl explain me From ictezy at gmail.com Fri Dec 11 13:39:05 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:39:05 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: On Friday, December 11, 2015 at 10:36:33 AM UTC-8, ICT Ezy wrote: > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: > > On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > > > Pl explain me how to connect the MYSQL database to Python program? > > > > You start by looking for a module that lets you do that. You can use > > your favourite web search engine, or go directly to PyPI. > > > > Then you learn how to use that module, including learning SQL if you > > don't already know it. > > > > ChrisA > > Now, I installed MYSQLDB and following code was done correctly. > > #!/usr/bin/python > > import MySQLdb > > # Open database connection > db = MySQLdb.connect("localhost","TESTDB") > > # prepare a cursor object using cursor() method > cursor = db.cursor() > > # execute SQL query using execute() method. > cursor.execute("SELECT VERSION()") > > # Fetch a single row using fetchone() method. > data = cursor.fetchone() > > print "Database version : %s " % data > > # disconnect from server > db.close() > > > Then done following SQL statements: > > #!/usr/bin/python > > import MySQLdb > > # Open database connection > db = MySQLdb.connect("localhost","TESTDB" ) > > # prepare a cursor object using cursor() method > cursor = db.cursor() > > > Then not correctly work following SQL statements: > > >>> import MySQLdb > >>> db = MySQLdb.connect("localhost","TESTDB" ) > >>> cursor = db.cursor() > >>> sql = """CREATE TABLE EMPLOYEE ( > FIRST_NAME CHAR(20) NOT NULL, > LAST_NAME CHAR(20), > AGE INT, > SEX CHAR(1), > INCOME FLOAT )""" > >>> cursor.execute(sql) > > Traceback (most recent call last): > File "", line 1, in > cursor.execute(sql) > File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 205, in execute > self.errorhandler(self, exc, value) > File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler > raise errorclass, errorvalue > OperationalError: (1046, "Aucune base n'a \xe9t\xe9 s\xe9lectionn\xe9e") > >>> > > How to solve the problems. pl explain me I follow this link: http://www.tutorialspoint.com/python/python_database_access.htm From ictezy at gmail.com Fri Dec 11 13:39:37 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:39:37 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: Message-ID: <962016f7-71ae-4bf0-8942-43ac8a769a89@googlegroups.com> On Wednesday, December 9, 2015 at 1:45:26 PM UTC-8, Mark Lawrence wrote: > On 09/12/2015 17:51, ICT Ezy wrote: > > Pl explain me how to connect the MYSQL database to Python program? > > > > Use a search engine. Then run up an editor, write some code, run said > code. If you then have problems state your OS, Python version and > provide us with the full traceback. > > An alternative is to write a cheque for (say) GBP 1000 payable to the > Python Software Foundation and if you're lucky somebody will do your > homework for you. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence I follow this link: http://www.tutorialspoint.com/python/python_database_access.htm From Dick.Ginga at PERKINELMER.COM Fri Dec 11 13:40:24 2015 From: Dick.Ginga at PERKINELMER.COM (Ginga, Dick) Date: Fri, 11 Dec 2015 18:40:24 +0000 Subject: wrappers for C/C++ In-Reply-To: References: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> Message-ID: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869BA61@AMERMBX02.PERKINELMER.NET> Thank you Chris for this answer. These are the _only_ versions the build creates. Are you saying that wrappers for 3.5 "may" continue to support future versions? -----Original Message----- From: Python-list [mailto:python-list-bounces+dick.ginga=perkinelmer.com at python.org] On Behalf Of Chris Angelico Sent: Friday, December 11, 2015 1:29 PM Cc: python-list at python.org Subject: Re: wrappers for C/C++ On Sat, Dec 12, 2015 at 4:21 AM, Ginga, Dick wrote: > I have inherited a product build that uses SWIG to product wrapper libraries for our C/C++ code. It currently builds these wrappers for 2.5, 2.6, 3.1 and 3.2. > > Is it necessary to have version specific wrappers? Yes, it is, because of the way Python's internals work. But you can probably build them all from the same source code. I'm not sure whether you mean that those four are the _only_ versions it's building for, or if you noted them as being particularly old versions still being built for. Either way, you should be in full control of your version support; if this is an internal project, you could simply stipulate that only one version of Python is supported (or maybe two - 2.7 and one 3.x), and save yourself some build hassles. If you're posting it on PyPI, you can put the source code out there and let Unix users build their own, and then you need only worry about Windows; I haven't seen confirmation yet (as there's no official 3.6 builds), but supporting "3.5+" should be possible from a single binary. (You would still need a separate binary for 2.7, though.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list From seung.kim at gallaudet.edu Fri Dec 11 13:43:24 2015 From: seung.kim at gallaudet.edu (Seung Kim) Date: Fri, 11 Dec 2015 13:43:24 -0500 Subject: Hello In-Reply-To: References: Message-ID: See message below. On Fri, Dec 11, 2015 at 1:13 PM, Seung Kim wrote: > I would like to have Python 3.5.1 MSI installer files for both 32-bit and > 64-bit so that I can deploy the software on managed computers on campus. > > When I ran the silent install command line on python-3.5.1.exe, the > registry key of QuietUninstallString showed me that the installer file was > located under the following C:\Users\css.kim\AppData\Local\Package > Cache\{b8440650-9dbe-4b7d-8167-6e0e3dcdf5d0}\python-3.5.1-amd64.exe" > /uninstall /quiet. > > If I deploy the latest version of Python 3.5.1, the source location will > be differently installed among managed computers. That is why I won't use > the exe installer file. I wanted to have MSI installer files. > > Please, advise. > > -- > > > Seung Kim > Software Systems Deployment Engineer > Gallaudet Technology Services, Hall Memorial Building (HMB) W122 > Gallaudet University > 800 Florida Avenue, NE > Washington, D.C. 20002-3695 > -- Seung Kim Software Systems Deployment Engineer Gallaudet Technology Services, Hall Memorial Building (HMB) W122 Gallaudet University 800 Florida Avenue, NE Washington, D.C. 20002-3695 From rosuav at gmail.com Fri Dec 11 13:45:46 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 05:45:46 +1100 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: On Fri, Dec 11, 2015 at 8:21 PM, Frank Millman wrote: > I noticed one oddity - I am asking sqlite3 to store the value as a string, > but then I am asking it to perform arithmetic on it. It's an SQLite3 issue, not a Python one. I used the sqlite3 stand-alone tool to do the same thing: sqlite> update fmtemp set bal = bal + cast('123.45' as numeric); sqlite> select bal from fmtemp; ... 5678.7 5802.15 5925.59999999999 And this might be why: https://www.sqlite.org/datatype3.html SQLite doesn't *have* all the SQL data types, and NUMERIC is one of the ones that isn't available. If you recreate your example using PostgreSQL, it should work fine. ChrisA From larry.martell at gmail.com Fri Dec 11 13:51:46 2015 From: larry.martell at gmail.com (Larry Martell) Date: Fri, 11 Dec 2015 13:51:46 -0500 Subject: How to connect the MYSQL database to Python program? In-Reply-To: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: On Fri, Dec 11, 2015 at 1:36 PM, ICT Ezy wrote: > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: >> On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: >> > Pl explain me how to connect the MYSQL database to Python program? >> >> You start by looking for a module that lets you do that. You can use >> your favourite web search engine, or go directly to PyPI. >> >> Then you learn how to use that module, including learning SQL if you >> don't already know it. >> >> ChrisA > > Now, I installed MYSQLDB and following code was done correctly. > > #!/usr/bin/python > > import MySQLdb > > # Open database connection > db = MySQLdb.connect("localhost","TESTDB") The connect should look like this: db= MySQLdb.connect(host, user, passwd, db) Or to be clearer: db= MySQLdb.connect(host="localhost", user="user", passwd="password", db="TESTDB") From rosuav at gmail.com Fri Dec 11 13:53:20 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 05:53:20 +1100 Subject: wrappers for C/C++ In-Reply-To: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869BA61@AMERMBX02.PERKINELMER.NET> References: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869BA61@AMERMBX02.PERKINELMER.NET> Message-ID: On Sat, Dec 12, 2015 at 5:40 AM, Ginga, Dick wrote: > Thank you Chris for this answer. These are the _only_ versions the build creates. Are you saying that wrappers for 3.5 "may" continue to support future versions? That's a Windows-specific concern; there've been changes made to how the Windows build process works, starting with 3.5. It's usually easiest to build against the exact Python that you want to run against; in the case of binaries downloaded from python.org, that basically means having one build for each version (major.minor) you want to support. (I'm not sure about other build concerns - you possibly need 32-bit and 64-bit builds for each version. Others will know more than I do on that.) For non-Windows platforms, it's usually easiest to punt on the whole build process and just distribute source code. C compilers are more generally available on people's Linux systems than on their Windowses. ChrisA From ictezy at gmail.com Fri Dec 11 13:54:04 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:54:04 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: <1b4b5564-3e1f-4216-9497-455997384bcf@googlegroups.com> On Friday, December 11, 2015 at 10:27:29 AM UTC-8, Jussi Piitulainen wrote: > ICT Ezy writes: > > On Friday, December 11, 2015 at 8:40:18 AM UTC-8, Ian wrote: > >> > >> No, it actually happens left to right. "x = y = z = 0" means "assign > >> 0 to x, then assign 0 to y, then assign 0 to z." It doesn't mean > >> "assign 0 to z, then assign z to y, etc." This works: > >> > >> >>> d = d['foo'] = {} > >> >>> d > >> {'foo': {...}} > >> > >> This doesn't: > >> > >> >>> del d > >> >>> d['foo'] = d = {} > >> Traceback (most recent call last): > >> File "", line 1, in > >> NameError: name 'd' is not defined > > > > Deat Ian, > > Thank you very much your answer, but > > above answer from Robin Koch and your answer is different. What's the > > actually process here? I agree with Robin Koch, but your answer is > > correct. Pl explain differences ? > > Python language reference, at 7.2 Assignment statements, says this: > > # An assignment statement evaluates the expression list (remember that > # this can be a single expression or a comma-separated list, the latter > # yielding a tuple) and assigns the single resulting object to each of > # the target lists, from left to right. > > To simplify a bit, it's talking about a statement of this form: > > target_list = target_list = target_list = expression_list > > And it says what Ian said: the value of the expression is assigned to > each target *from left to right*. > > Yes you correct! From ictezy at gmail.com Fri Dec 11 13:55:42 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 10:55:42 -0800 (PST) Subject: Python variable assigning problems... In-Reply-To: References: <4b28ee3d-47b3-40ef-b48e-abff720635ed@googlegroups.com> <0098ce4a-966b-41df-bf06-352ad451134f@googlegroups.com> Message-ID: On Friday, December 11, 2015 at 10:27:29 AM UTC-8, Jussi Piitulainen wrote: > ICT Ezy writes: > > On Friday, December 11, 2015 at 8:40:18 AM UTC-8, Ian wrote: > >> > >> No, it actually happens left to right. "x = y = z = 0" means "assign > >> 0 to x, then assign 0 to y, then assign 0 to z." It doesn't mean > >> "assign 0 to z, then assign z to y, etc." This works: > >> > >> >>> d = d['foo'] = {} > >> >>> d > >> {'foo': {...}} > >> > >> This doesn't: > >> > >> >>> del d > >> >>> d['foo'] = d = {} > >> Traceback (most recent call last): > >> File "", line 1, in > >> NameError: name 'd' is not defined > > > > Deat Ian, > > Thank you very much your answer, but > > above answer from Robin Koch and your answer is different. What's the > > actually process here? I agree with Robin Koch, but your answer is > > correct. Pl explain differences ? > > Python language reference, at 7.2 Assignment statements, says this: > > # An assignment statement evaluates the expression list (remember that > # this can be a single expression or a comma-separated list, the latter > # yielding a tuple) and assigns the single resulting object to each of > # the target lists, from left to right. > > To simplify a bit, it's talking about a statement of this form: > > target_list = target_list = target_list = expression_list > > And it says what Ian said: the value of the expression is assigned to > each target *from left to right*. > > See also: >>> x = [5, 6] >>> x[i],x[j] (5, 6) >>> i,j=0,1 >>> x[i],x[j]=x[j],x[i]=2,3 >>> x[i],x[j] (3, 2) From ictezy at gmail.com Fri Dec 11 14:00:13 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 11:00:13 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: On Friday, December 11, 2015 at 10:52:49 AM UTC-8, Larry.... at gmail.com wrote: > On Fri, Dec 11, 2015 at 1:36 PM, ICT Ezy wrote: > > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: > >> On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > >> > Pl explain me how to connect the MYSQL database to Python program? > >> > >> You start by looking for a module that lets you do that. You can use > >> your favourite web search engine, or go directly to PyPI. > >> > >> Then you learn how to use that module, including learning SQL if you > >> don't already know it. > >> > >> ChrisA > > > > Now, I installed MYSQLDB and following code was done correctly. > > > > #!/usr/bin/python > > > > import MySQLdb > > > > # Open database connection > > db = MySQLdb.connect("localhost","TESTDB") > > The connect should look like this: > > db= MySQLdb.connect(host, user, passwd, db) > > Or to be clearer: > > db= MySQLdb.connect(host="localhost", user="user", passwd="password", > db="TESTDB") if there was error generated, i remove password and user >>> db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") Traceback (most recent call last): File "", line 1, in db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 193, in __init__ super(Connection, self).__init__(*args, **kwargs2) OperationalError: (1045, "Acc\xe8s refus\xe9 pour l'utilisateur: 'testuser'@'@localhost' (mot de passe: OUI)") >>> pl check it From ikorot01 at gmail.com Fri Dec 11 14:11:04 2015 From: ikorot01 at gmail.com (Igor Korot) Date: Fri, 11 Dec 2015 14:11:04 -0500 Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: Hi, On Fri, Dec 11, 2015 at 2:00 PM, ICT Ezy wrote: > On Friday, December 11, 2015 at 10:52:49 AM UTC-8, Larry.... at gmail.com wrote: >> On Fri, Dec 11, 2015 at 1:36 PM, ICT Ezy wrote: >> > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: >> >> On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: >> >> > Pl explain me how to connect the MYSQL database to Python program? >> >> >> >> You start by looking for a module that lets you do that. You can use >> >> your favourite web search engine, or go directly to PyPI. >> >> >> >> Then you learn how to use that module, including learning SQL if you >> >> don't already know it. >> >> >> >> ChrisA >> > >> > Now, I installed MYSQLDB and following code was done correctly. >> > >> > #!/usr/bin/python >> > >> > import MySQLdb >> > >> > # Open database connection >> > db = MySQLdb.connect("localhost","TESTDB") >> >> The connect should look like this: >> >> db= MySQLdb.connect(host, user, passwd, db) >> >> Or to be clearer: >> >> db= MySQLdb.connect(host="localhost", user="user", passwd="password", >> db="TESTDB") > > if there was error generated, i remove password and user > >>>> db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") > > Traceback (most recent call last): > File "", line 1, in > db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") > File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect > return Connection(*args, **kwargs) > File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 193, in __init__ > super(Connection, self).__init__(*args, **kwargs2) > OperationalError: (1045, "Acc\xe8s refus\xe9 pour l'utilisateur: 'testuser'@'@localhost' (mot de passe: OUI)") >>>> Is the account testuser exist? Does it have a password "test123"? But more imp[ortantly - this does not have anything to do with Python. Start by trying to connect from mySQL and try to execute some insert/update/delete statement. Then when you succeed, start writing python code. Thank you. > pl check it > -- > https://mail.python.org/mailman/listinfo/python-list From ictezy at gmail.com Fri Dec 11 14:11:27 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 11:11:27 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: <5882883a-cce3-4021-ab5b-888e87a6e2b4@googlegroups.com> On Friday, December 11, 2015 at 10:52:49 AM UTC-8, Larry.... at gmail.com wrote: > On Fri, Dec 11, 2015 at 1:36 PM, ICT Ezy wrote: > > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: > >> On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > >> > Pl explain me how to connect the MYSQL database to Python program? > >> > >> You start by looking for a module that lets you do that. You can use > >> your favourite web search engine, or go directly to PyPI. > >> > >> Then you learn how to use that module, including learning SQL if you > >> don't already know it. > >> > >> ChrisA > > > > Now, I installed MYSQLDB and following code was done correctly. > > > > #!/usr/bin/python > > > > import MySQLdb > > > > # Open database connection > > db = MySQLdb.connect("localhost","TESTDB") > > The connect should look like this: > > db= MySQLdb.connect(host, user, passwd, db) > > Or to be clearer: > > db= MySQLdb.connect(host="localhost", user="user", passwd="password", > db="TESTDB") Ok Larry, I have success now, my names are misspelling. work well From ictezy at gmail.com Fri Dec 11 14:13:39 2015 From: ictezy at gmail.com (ICT Ezy) Date: Fri, 11 Dec 2015 11:13:39 -0800 (PST) Subject: How to connect the MYSQL database to Python program? In-Reply-To: References: <9261e7b4-48ad-45f2-ba65-066177d21f6b@googlegroups.com> Message-ID: On Friday, December 11, 2015 at 11:11:22 AM UTC-8, Igor Korot wrote: > Hi, > > On Fri, Dec 11, 2015 at 2:00 PM, ICT Ezy wrote: > > On Friday, December 11, 2015 at 10:52:49 AM UTC-8, Larry.... at gmail.com wrote: > >> On Fri, Dec 11, 2015 at 1:36 PM, ICT Ezy wrote: > >> > On Wednesday, December 9, 2015 at 9:58:02 AM UTC-8, Chris Angelico wrote: > >> >> On Thu, Dec 10, 2015 at 4:51 AM, ICT Ezy wrote: > >> >> > Pl explain me how to connect the MYSQL database to Python program? > >> >> > >> >> You start by looking for a module that lets you do that. You can use > >> >> your favourite web search engine, or go directly to PyPI. > >> >> > >> >> Then you learn how to use that module, including learning SQL if you > >> >> don't already know it. > >> >> > >> >> ChrisA > >> > > >> > Now, I installed MYSQLDB and following code was done correctly. > >> > > >> > #!/usr/bin/python > >> > > >> > import MySQLdb > >> > > >> > # Open database connection > >> > db = MySQLdb.connect("localhost","TESTDB") > >> > >> The connect should look like this: > >> > >> db= MySQLdb.connect(host, user, passwd, db) > >> > >> Or to be clearer: > >> > >> db= MySQLdb.connect(host="localhost", user="user", passwd="password", > >> db="TESTDB") > > > > if there was error generated, i remove password and user > > > >>>> db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") > > > > Traceback (most recent call last): > > File "", line 1, in > > db= MySQLdb.connect(host="localhost", user="testuser", passwd="test123",db="TESTDB") > > File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect > > return Connection(*args, **kwargs) > > File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 193, in __init__ > > super(Connection, self).__init__(*args, **kwargs2) > > OperationalError: (1045, "Acc\xe8s refus\xe9 pour l'utilisateur: 'testuser'@'@localhost' (mot de passe: OUI)") > >>>> > > Is the account testuser exist? Does it have a password "test123"? > But more imp[ortantly - this does not have anything to do with Python. > > Start by trying to connect from mySQL and try to execute some > insert/update/delete statement. > > Then when you succeed, start writing python code. > > Thank you. > > > pl check it > > -- > > https://mail.python.org/mailman/listinfo/python-list OK, I have done well now, misspelling occurred. Thanks From Dick.Ginga at PERKINELMER.COM Fri Dec 11 14:24:07 2015 From: Dick.Ginga at PERKINELMER.COM (Ginga, Dick) Date: Fri, 11 Dec 2015 19:24:07 +0000 Subject: wrappers for C/C++ In-Reply-To: References: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869B96D@AMERMBX02.PERKINELMER.NET> <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869BA61@AMERMBX02.PERKINELMER.NET> Message-ID: <6C6EE445A6F6CE4E8A0FFB51B071A4E2D869BAD3@AMERMBX02.PERKINELMER.NET> Thanks again for a very informative answer and these are windows wrappers. -----Original Message----- From: Python-list [mailto:python-list-bounces+dick.ginga=perkinelmer.com at python.org] On Behalf Of Chris Angelico Sent: Friday, December 11, 2015 1:53 PM Cc: python-list at python.org Subject: Re: wrappers for C/C++ On Sat, Dec 12, 2015 at 5:40 AM, Ginga, Dick wrote: > Thank you Chris for this answer. These are the _only_ versions the build creates. Are you saying that wrappers for 3.5 "may" continue to support future versions? That's a Windows-specific concern; there've been changes made to how the Windows build process works, starting with 3.5. It's usually easiest to build against the exact Python that you want to run against; in the case of binaries downloaded from python.org, that basically means having one build for each version (major.minor) you want to support. (I'm not sure about other build concerns - you possibly need 32-bit and 64-bit builds for each version. Others will know more than I do on that.) For non-Windows platforms, it's usually easiest to punt on the whole build process and just distribute source code. C compilers are more generally available on people's Linux systems than on their Windowses. ChrisA -- https://mail.python.org/mailman/listinfo/python-list From zachary.ware+pylist at gmail.com Fri Dec 11 15:18:51 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 11 Dec 2015 14:18:51 -0600 Subject: python 351x64 In-Reply-To: <91aa9e024c8f48d6a3212af00b1360a2@EX13-MBX-031.vmware.com> References: <91aa9e024c8f48d6a3212af00b1360a2@EX13-MBX-031.vmware.com> Message-ID: On Fri, Dec 11, 2015 at 11:53 AM, Jay Hamm wrote: > It is an issue that borks your install. That seems like your issue which involves notepad++. You might want to talk with them about it or more likely since they've not fixed it in a while - develop a work around or at least a message that pops up and asks if they want it fixed so the install succeeds. Could you describe the steps you took, the results you got, and the result you expected? It's not clear from your description what is broken by what, and not at all clear that there is any interaction whatsoever between Python and Notepad++. Also, we're not in the habit of including workarounds for bugs in software that may or may not be installed on some fraction of systems of one particular platform. > Likewise if you have an option to install for all uses, then it should work without further intervention. "Install for all users" means "make it readable by all users" rather than "make it writable by all users." As I stated previously, install your package as an administrator if you need it in the global site packages, or use a virtual environment that you have write access to as a non-admin. Or install Python elsewhere (which could be as simple as choosing "install for just me"). Or adjust the permissions you want adjusted yourself, as you apparently did. The installer cannot do everything for everyone, so it does what we believe to be best for most use cases and errs on the side of security. > As for unfair, is this production software or is it a toy? If it is a toy, I withdraw my comment. It seems to me there is even less call for that. Civility breeds civility, incivility breeds contempt. Python is a volunteer-driven open source project, available to you at no cost and with free community support. If there is a bug to fix, we're happy to fix it, but at bare minimum we need clear steps to reproduce the problem. Being open source, you're also more than welcome to provide a patch that fixes your issues. -- Zach From ian.g.kelly at gmail.com Fri Dec 11 15:57:55 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 11 Dec 2015 13:57:55 -0700 Subject: Hello In-Reply-To: References: Message-ID: On Fri, Dec 11, 2015 at 11:43 AM, Seung Kim wrote: > See message below. > > On Fri, Dec 11, 2015 at 1:13 PM, Seung Kim wrote: > >> I would like to have Python 3.5.1 MSI installer files for both 32-bit and >> 64-bit so that I can deploy the software on managed computers on campus. >> >> When I ran the silent install command line on python-3.5.1.exe, the >> registry key of QuietUninstallString showed me that the installer file was >> located under the following C:\Users\css.kim\AppData\Local\Package >> Cache\{b8440650-9dbe-4b7d-8167-6e0e3dcdf5d0}\python-3.5.1-amd64.exe" >> /uninstall /quiet. >> >> If I deploy the latest version of Python 3.5.1, the source location will >> be differently installed among managed computers. That is why I won't use >> the exe installer file. I wanted to have MSI installer files. >> >> Please, advise. You probably want to install for all users using the InstallAllUsers=1 option. See https://docs.python.org/3/using/windows.html#installing-without-ui From breamoreboy at yahoo.co.uk Fri Dec 11 16:02:00 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 11 Dec 2015 21:02:00 +0000 Subject: python 351x64 In-Reply-To: <91aa9e024c8f48d6a3212af00b1360a2@EX13-MBX-031.vmware.com> References: <91aa9e024c8f48d6a3212af00b1360a2@EX13-MBX-031.vmware.com> Message-ID: On 11/12/2015 17:53, Jay Hamm wrote: > It is an issue that borks your install. That seems like your issue which involves notepad++. You might want to talk with them about it or more likely since they've not fixed it in a while - develop a work around or at least a message that pops up and asks if they want it fixed so the install succeeds. > > Likewise if you have an option to install for all uses, then it should work without further intervention. > > As for unfair, is this production software or is it a toy? If it is a toy, I withdraw my comment. > > -----Original Message----- > From: zachary.ware at gmail.com [mailto:zachary.ware at gmail.com] On Behalf Of Zachary Ware > Sent: Friday, December 11, 2015 10:17 AM > To: python-list at python.org > Cc: Jay Hamm > Subject: Re: python 351x64 > > On Fri, Dec 11, 2015 at 10:30 AM, Jay Hamm wrote: >> Hi >> >> I was trying to use your windows version of python 3.5.1 x64. >> >> It has a conflict with a notepad++ plugin NppFTP giving api-ms-win-crt-runtime-I1-1-0.dll error on start up. >> >> This seems pretty well documented on the web. The work around is to delete the plugin and reinstall since it borks the install. > > api-ms-win-crt-runtime-I1-1-0.dll is part of the Universal CRT; I don't see what the relation between Python and Notepad++ is. This sounds like an issue with Notepad++/NppFTP, not Python. > >> Since about every other admin I've ever known uses notepad++, you might want to fix this. >> >> Also your installer fails to set the permissions correctly: >> >> H:\>py -m pip install requests >> Collecting requests >> Downloading requests-2.8.1-py2.py3-none-any.whl (497kB) >> 100% |################################| 499kB 875kB/s Installing >> collected packages: requests >> Exception: >> Traceback (most recent call last): >> File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 211, in main status = self.run(options, args) >> File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 311, in run root=options.root_path, >> File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs >> File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 803, in install self.move_wheel_files(self.source_dir, root=root) >> File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 998, in move_wheel_files isolated=self.isolated, >> File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 339, in move_wheel_files clobber(source, lib_dir, True) >> File "C:\Program Files\Python35\lib\site-packages\pip\wheel.py", line 310, in clobber ensure_dir(destdir) >> File "C:\Program Files\Python35\lib\site-packages\pip\utils\__init__.py", line 71, in ensure_dir os.makedirs(path) >> File "C:\Program Files\Python35\lib\os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Python35\\Lib\\site-packages\\requests' >> >> Once I gave myself control it started working. > > The point of installing in C:\Program Files\ is that non-admin users can't write there. If you want a package installed in the global site-packages, do it as an administrator or install Python somewhere else (like C:\Python35\ as previous versions did, but be aware of the security implications). Otherwise, create a local venv (`py -3.5 -m venv path\to\venv`), install your packages there, and use it. > >> This is pretty shoddy for released software. > > That seems uncalled for. > > -- > Zach > Besides the fact that you don't appear to have the faintest idea what you're talking about, which is why the issue is all ready closed, please don't top post, that is not the standard on this list. As a slight aside, just how bug ridden is your software, as I believe has been hinted at by other well respected members of this list? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rantingrickjohnson at gmail.com Fri Dec 11 16:06:41 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Fri, 11 Dec 2015 13:06:41 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <87si3md3l9.fsf@elektro.pacujo.net> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <87si3md3l9.fsf@elektro.pacujo.net> Message-ID: <9906a28c-abc4-4cea-93df-6742519cd636@googlegroups.com> On Tuesday, December 1, 2015 at 1:34:54 AM UTC-6, Marko Rauhamaa wrote: > Rick Johnson : > > > python was originally created to be an easy language for noobs to > > learn > > Really? That's would be a silly objective for a programming language. > > > many a noob has been stumped > > So? > > You have to first placate the experts and the "noobs" will follow. Okay i get it. So in your opinion, a technology is *ONLY* worthy if it requires a large amount of special training to wield it? Well, in that case you'd better start organizing a revived Luddite movement, because i can assure you that as we progress into the future, more and more of the processes that required "human specialist" will be replaced with computational devices that are purposefully designed to expose the most intuitive interface possible. PSST: THIS IS THE FUTURE! AND IT'S ALREADY STEAMROLLING AHEAD WITHOUT YOU! Just about anything a human specialist can do, a machine can already, or will in a short time, do better, faster, and more consistently. This is a fact! We humans are terrible at solving problems that require extreme precision, repetition, data mining, memory recall, and many other processes that computational machines do with great ease. Any problem solving process can be broken down into it's atomic components, and reassembled as a logical algorithm. Even doctors will soon be replaced with machines, which will raise the quality of health care to a level never seen. There is almost no skill that is beyond the clutches of the algorithm. In fact, the only skill that we humans posses which cannot yet be emulated, is the power of our imagination. Therefor, our goal should not be to create more "specialist", who toil away doing menial tasks like slaves, no, but to foster the creative potential of the human mind. By first *understanding* algorithmic processes, and then *abstracting* those processes in logic form, and finally *relegating* those abstractions to computational machines (that expose intuitive interfaces), we will enter an age of creative enlightenment such as this world has never seen. Just as the information age brought all the worlds knowledge to our fingertips, the relegation of menial tasks will free our bodies so that our minds can utilize that vast trove of knowledge to drive our technological evolution into overdrive. And as far as i'm concerned, we can't get there fast enough! So if you want to cling to a world where your "special skills" are nothing more than "job security", well then, go ahead. As for myself, and the vast majority of humanity, we will forge on with or without you! SO GOODBYE, AND GOOD RIDDANCE!!! From rantingrickjohnson at gmail.com Fri Dec 11 17:13:16 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Fri, 11 Dec 2015 14:13:16 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> Message-ID: On Tuesday, December 1, 2015 at 10:49:19 PM UTC-6, Ian wrote: > > It's a well know fact that GvR was inspired to create > > Python from his experiences working with a language > > called ABC -- and ABC was designed *EXCLUSIVELY* to be a > > beginners language. > Which is exactly what made ABC itself unsuitable for Guido's purpose, which > was to create an *applications* language with better productivity than C to > support users of Amoeba, the OS that he was working on at the time. The key word here is "productivity". Intuitiveness and productivity have a synergy like peas and carrots! One cannot be productive if one is fighting an unintuitive interface. Could you drive with your toes? How about your tongue? Sure, even the most atrocious interface can be "learned", but what i cannot understand, except in the case of you being a contrarian, is why you would argue *AGAINST* intuitive interfaces? And believe it or not, *SYNTAX* is an interface! As are paradigms! > > Even a noob can intuit what is going on here. First we > > have an *OBJECT* named "stdout, and we can extrapolate > > that stdout is an abbreviation for StandardOutput. Next, > > we see a method called "write", and, if our IQ is above > > room temperature, then we can extrapolate what that > > method will do. > > This is absurd. You postulate a beginner so rank that they can't understand > what "print" means, yet you expect them to intuitively know: > > 1) what an object is; > > 2) what a method is; > > 3) that a method is identified by placing a period between the object and > the name of the method; > > 4) what "output" is in the context of programming; > > 5) and not be confused about what makes the output "standard". You accuse me of Reductio Ad Adsurdium, yet you commit the same offense, and then put words in my mouth? Of course i don't expect a "rank noob" to understand these concepts *immediately*, however, the learning curve will be greatly reduced, and the depth of knowledge greatly expanded, when a clear path of consistent intuitiveness is baked-into the learning process -- it's all about breadcrumbs my dear boy, breadcrumbs! THE PRINT FUNCTION HAS TWO MAJOR ISSUES IN THE CONTEXT OF INTUITIVENESS: (1) When laymen consider the word "print" (in the context of computing), they first think of "sending a document to a printing device". LIKE IT NOT, "PRINT" IS A CONCEPTUAL CHAMELEON! It does the worst thing it can do, it distracts! (2) The path to the underlying process is not even remotely clear. LIKE IT NOT, PRINT IS "MAGIC SYNTAX". Of course the noob is not going to immediately intuit every atomic component of `stdout.write("blah")`, however, the road signs are there, and all he need to do is follow them. In fact, by learning from my example, not only will the noob learn the "magic" that exists under the hood, he will also learn a vital lesson (while dissecting the components) about the power of "divide and conquer". If we were to create a thought exercise that juxtaposes your argument with mine, we would find a great example in the "search for hidden treasure". You expect the noob to go into a dessert without a map and dig holes until he locates the treasure or dies of exhaustion. Whereas i will not only give the noob a map, i will draw a clear path on the map to the destination -- all he need to do is navigate! I don't know what's more absurd: your argument, or your ego? > You're describing this as if your hypothetical beginner were learning > Python in a vacuum. In reality, people learn from a teacher, or a book, or > at minimum a tutorial. Hmm. I'll bet you create teeny tiny variable names and then write a paragraph to describe them. Does the concept of "Self Documentation" mean anything to you? And, when correctly designed, the only tutorial that is needed is the the syntax! Heck, we are not writing assembly code here man, we're writing Python code for Guido's sake! > Here's how you teach somebody what "print" does: instruct them to type > print("hello world") at the interactive prompt. Note that Python writes > "hello world" as a result. If they really want, they can check their > printer and see that nothing came out. That's it. The student now > understands what "print" means. Yes, the timeless method of "trial and error" is expected if you're a trail blazer and there exists no previous knowledge, however, when this sort of teaching paradigm is used in areas where the processes have been previously dissected, it reflects a sadistic nature within the teacher. I'm of the opinion that learning "old tech" should be as intuitive as possible, and that, as knowledge spreads, we all prosper. However, you seem to adopt the teaching methods of a drunken and disorderly college sorority house captain. Students are not pledges to be tortured. They are our the future. And when we undermine them, we undermine our ourselves. PUT THAT IN YOUR INTERPRETER AND RUN IT! From w.abdo at ntta.com Fri Dec 11 17:27:25 2015 From: w.abdo at ntta.com (William Abdo) Date: Fri, 11 Dec 2015 22:27:25 +0000 Subject: Windows 10 and PYODBC Message-ID: Problem Resolved. I have fixed the Oracle connection issue under Windows 10 with cx_Oracle . PYODBC was only failing on the Oracle connection and worked fine on MS SQL under Windows 10. Thank You for your time in this matter. Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] **************************************************************** This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. **************************************************************** From phamtony33 at gmail.com Fri Dec 11 18:19:26 2015 From: phamtony33 at gmail.com (phamtony33 at gmail.com) Date: Fri, 11 Dec 2015 15:19:26 -0800 (PST) Subject: Can anyone help me modify the code so the ball starts in random directions Message-ID: Can anyone direct me in the direction where to start the code for the randomized of the ball to start. from Tkinter import * window = Tk() canvas = Canvas(window, width=500, height=500, background="green") canvas.pack() def mouse_paddle_move(event): mouseY = event.y current_coords = canvas.coords("paddle") x1 = current_coords[0] y1 = current_coords[1] x2 = current_coords[2] y2 = current_coords[3] height = (y2 - y1) canvas.coords("paddle", x1, mouseY - (height/2), x2, mouseY + (height/2)) def move_ball(speed_x, speed_y, score): box = canvas.bbox("ball") x1 = box[0] y1 = box[1] x2 = box[2] y2 = box[3] if x2 >= 500: canvas.create_text(250, 250, text="Game Over!") return box = canvas.bbox("paddle") px1 = box[0] py1 = box[1] px2 = box[2] py2 = box[3] if x2 > px1 and y2 > py1 and y1 < py2: speed_x = -1.2 * (abs(speed_x)) speed_y = 1.2 * speed_y score = score + 1 canvas.itemconfig("score_text", text="Score: " + str(score)) if x1 <= 0: speed_x = -1 * speed_x if y2 >= 500 or y1 <= 0: speed_y = -1 * speed_y canvas.move("ball", speed_x, speed_y) canvas.after(30, move_ball, speed_x, speed_y, score) canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball") canvas.create_rectangle(450, 200, 455, 300, fill="red", tags="paddle") canvas.create_text(250, 10, tags = "score_text", text="Score: 0") move_ball(-10, 7, 0) canvas.bind('', mouse_paddle_move) mainloop() From phamtony33 at gmail.com Fri Dec 11 19:51:11 2015 From: phamtony33 at gmail.com (phamtony33 at gmail.com) Date: Fri, 11 Dec 2015 16:51:11 -0800 (PST) Subject: Can anyone help me modify the code so the ball starts in random directions In-Reply-To: References: Message-ID: <4b2cb21b-68f3-4fd3-b155-50df7678020e@googlegroups.com> from Tkinter import * window = Tk() canvas = Canvas(window, width=500, height=500, background="green") canvas.pack() def mouse_paddle_move(event): mouseY = event.y current_coords = canvas.coords("paddle") x1 = current_coords[0] y1 = current_coords[1] x2 = current_coords[2] y2 = current_coords[3] height = (y2 - y1) canvas.coords("paddle", x1, mouseY - (height/2), x2, mouseY + (height/2)) def move_ball(speed_x, speed_y, score): box = canvas.bbox("ball") x1 = box[0] y1 = box[1] x2 = box[2] y2 = box[3] #if ball hits right wall, you lose if x2 >= 500: canvas.create_text(250, 250, text="Game Over!") return # exit function # if ball hits paddle... box = canvas.bbox("paddle") px1 = box[0] py1 = box[1] px2 = box[2] py2 = box[3] if x2 > px1 and y2 > py1 and y1 < py2: # bounce with 20% more speed speed_x = -1.2 * (abs(speed_x)) speed_y = 1.2 * speed_y # update score score = score + 1 canvas.itemconfig("score_text", text="Score: " + str(score)) # if ball hits left wall it bounces if x1 <= 0: speed_x = -1 * speed_x # if ball hits top or bottom walls it bounces if y2 >= 500 or y1 <= 0: speed_y = -1 * speed_y canvas.move("ball", speed_x, speed_y) canvas.after(30, move_ball, speed_x, speed_y, score) # repeat in 30 ms # create ball, paddle, and score text. canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball") canvas.create_rectangle(450, 200, 455, 300, fill="red", tags="paddle") canvas.create_text(250, 10, tags = "score_text", text="Score: 0") # make the ball move 10 pixels left, 7 down, with initial score at 0 move_ball(-10, 7, 0) # setup mouse handler canvas.bind('', mouse_paddle_move) mainloop() From rantingrickjohnson at gmail.com Fri Dec 11 19:51:38 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Fri, 11 Dec 2015 16:51:38 -0800 (PST) Subject: Can anyone help me modify the code so the ball starts in random directions In-Reply-To: References: Message-ID: On Friday, December 11, 2015 at 5:20:13 PM UTC-6, phamt... at gmail.com wrote: > Can anyone direct me in the direction where to start the code for the randomized of the ball to start. No, because your problem needs to be simplified first. A good first step would be to create a new script that only displays a canvas and draws an oval at a random spot when a button is pressed (or some other easy interface method) Once you can reliably create random ovals on command, only then do you want to work that code into the larger program. The stdlib has a module for creating random numbers and ranges. From steve at pearwood.info Fri Dec 11 19:55:47 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Dec 2015 11:55:47 +1100 Subject: Can anyone help me modify the code so the ball starts in random directions References: Message-ID: <566b7094$0$1594$c3e8da3$5496439d@news.astraweb.com> On Sat, 12 Dec 2015 10:19 am, phamtony33 at gmail.com wrote: > Can anyone direct me in the direction where to start the code for the > randomized of the ball to start. [...] > move_ball(-10, 7, 0) That starts the ball moving, with x-speed of -10 and y-speed of 7. Instead use something similar to this: import random xspeed = random.randint(-20, 20) yspeed = random.randint(-10, 10) move_ball(xspeed, yspeed, 0) -- Steven From phamtony33 at gmail.com Fri Dec 11 20:04:30 2015 From: phamtony33 at gmail.com (phamtony33 at gmail.com) Date: Fri, 11 Dec 2015 17:04:30 -0800 (PST) Subject: Can anyone help me modify the code so the ball starts in random directions In-Reply-To: <566b7094$0$1594$c3e8da3$5496439d@news.astraweb.com> References: <566b7094$0$1594$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, December 11, 2015 at 7:55:59 PM UTC-5, Steven D'Aprano wrote: > On Sat, 12 Dec 2015 10:19 am, phamtony33 at gmail.com wrote: > > > Can anyone direct me in the direction where to start the code for the > > randomized of the ball to start. > > [...] > > move_ball(-10, 7, 0) > > > That starts the ball moving, with x-speed of -10 and y-speed of 7. Instead > use something similar to this: > > > import random > xspeed = random.randint(-20, 20) > yspeed = random.randint(-10, 10) > > move_ball(xspeed, yspeed, 0) > > > > > -- > Steven Oh yes! Thank you so much! From python at lucidity.plus.com Fri Dec 11 20:05:25 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 12 Dec 2015 01:05:25 +0000 Subject: Can anyone help me modify the code so the ball starts in random directions In-Reply-To: References: Message-ID: <566B72D5.1000407@lucidity.plus.com> Hi, On 11/12/15 23:19, phamtony33 at gmail.com wrote: > Can anyone direct me in the direction where to start the code for the randomized of the ball to start. Your questions over the last week or so appear to be homework assignments. However, I'll give you a hint: in the interactive interpreter shell, try: >>> import random >>> help(random) Read that and try to work out how you might apply one of the functions to your problem. E. From python at lucidity.plus.com Fri Dec 11 20:05:42 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 12 Dec 2015 01:05:42 +0000 Subject: Can anyone help me modify the code so the ball starts in random directions In-Reply-To: References: Message-ID: <566B72E6.5080909@lucidity.plus.com> Hi, On 11/12/15 23:19, phamtony33 at gmail.com wrote: > Can anyone direct me in the direction where to start the code for the randomized of the ball to start. Your questions over the last week or so appear to be homework assignments. However, I'll give you a hint: in the interactive interpreter shell, try: >>> import random >>> help(random) Read that and try to work out how you might apply one of the functions to your problem. E. From steve at pearwood.info Fri Dec 11 23:44:36 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Dec 2015 15:44:36 +1100 Subject: Is vars() the most useless Python built-in ever? References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> Message-ID: <566ba636$0$1589$c3e8da3$5496439d@news.astraweb.com> On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote: > Intuitiveness and productivity have a > synergy like peas and carrots! One cannot be productive if one is fighting > an unintuitive interface. Could you drive with your toes? How about your > tongue? Drive a car with my tongue? Perhaps not, but I could drive a car with my mouth if it were equipped with a sufficiently powerful interface. "Driver, please take me to the airport." > Sure, even the most atrocious interface can be "learned", but what i > cannot understand, except in the case of you being a contrarian, is why > you would argue *AGAINST* intuitive interfaces? And believe it or not, > *SYNTAX* is an interface! As are paradigms! I do believe that you are arguing against a strawman. I don't think that anyone here has argued *against* "intuitiveness", all else being equal. But you are glossing over a whole lot of real complexity: - what makes you think all else actually is equal? - who decides what is intuitive and what isn't? why should we take your word over what's intuitive and what isn't? - intuitive for who? my dad, who has never used a computer? my mum, who has used a computer but only for word processing and web browsing? a ten year old maths prodigy? a thirty year veteran of C programming? a beginner to programming with a month's experience in PHP? - what level of power are we willing to forgo in order to keep the language "intuitive"? - what the hell does "intuitive" mean anyway? I know what the definition of the word is, but it doesn't apply to programming language interfaces. As has been pointed out many times, the only truly intuitive interface is the nipple. Everything else has to be learned. In practice, "intuitive interface" gets bandied about in two ways: (1) Some people use it as a thought-terminating clich?. What they really mean is that they want this interface feature, for reasons of their own, and by calling it 'intuitive', they hope to bamboozle or intimidate others into backing down and accepting the feature. Who could possibly be against "intuitive" interfaces? That's like being against "usefulness", or "flexibility". When people start protesting about others being "against intuitive interfaces" (especially if they SHOUT the word "against", that's an good sign that they're using it as a thought-terminating clich?. To these people, "intuitive" is like "New And Improved!!!" to advertisers. (2) Others use it to mean an interface which is: * predictable; * consistent; * easy to explore and learn; * and "easy to use" in some vague sense. They recognise that what seems unpredictable to one person may be perfectly predictable to a more experienced user. They recognise that consistency is partly a function of the user's own understanding, not just they language alone. Even if the language is designed with a single, consistent model (e.g. "everything is an object"), if the user's mental model is wrong, they will fail to recognise the consistency, or look for it in the wrong places. And most importantly, they recognise that programmers are beginners for perhaps 1% of their programming life: you might be completely new to programming for three months out of a 30 year span of programming. Why optimize the language for something that you will use for less than 1% of your productive lifespan? Apart from intentional beginner's languages like Scratch, for most languages it makes sense to add power even if it increases the learning curve. https://scratch.mit.edu/about/ [...] > THE PRINT FUNCTION HAS TWO MAJOR ISSUES IN THE CONTEXT OF INTUITIVENESS: > > (1) When laymen consider the word "print" (in the context of computing), > they first think of "sending a document to a printing device". No they don't. They think of printing to the screen, not printing to paper. Even if they think of printing to paper, it takes them less than a second to learn otherwise. That's a fantastic user interface: you can learn and explore the functionality of the language very easily. (One of the weaknesses of Python, and nearly all mainstream programming languages, is that there is nothing even remotely like an easy-to-explore UI for programming GUI applications.) > (2) The path to the underlying process is not even remotely clear. LIKE IT > NOT, PRINT IS "MAGIC SYNTAX". print does what it says of the tin: it prints (to the screen). You don't have to understand how it manages that to use it effectively, just as you don't have to understand calculus in order to use math.sqrt(). -- Steven From frank at chagford.com Sat Dec 12 00:10:14 2015 From: frank at chagford.com (Frank Millman) Date: Sat, 12 Dec 2015 07:10:14 +0200 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: "Chris Angelico" wrote in message news:CAPTjJmor6NewucCo7XTSSwyyfbgwCWZ8Jt-MjjkYSjOCFu78_A at mail.gmail.com... On Fri, Dec 11, 2015 at 8:21 PM, Frank Millman wrote: > > I noticed one oddity - I am asking sqlite3 to store the value as a > > string, > > but then I am asking it to perform arithmetic on it. > It's an SQLite3 issue, not a Python one. I used the sqlite3 > stand-alone tool to do the same thing: > sqlite> update fmtemp set bal = bal + cast('123.45' as numeric); > sqlite> select bal from fmtemp; > ... > 5678.7 > 5802.15 > 5925.59999999999 > You are right. I am still investigating alternatives, and will report back, but here is a quick question. I can reproduce your example above. However, if I set the initial value to 5678.7, then the sequence goes 5678.7 5802.15 5925.6 6049.05 6172.5 I would have thought that adding 123.45 to 5802.15 would always produce the same result, but here it seems to depend on prior events. Any idea why? Academic interest only, but I am curious. Frank From frank at chagford.com Sat Dec 12 00:22:42 2015 From: frank at chagford.com (Frank Millman) Date: Sat, 12 Dec 2015 07:22:42 +0200 Subject: Problem with sqlite3 and Decimal (fwd) In-Reply-To: References: <201512111345.tBBDjgae025001@fido.openend.se> Message-ID: "Igor Korot" wrote in message news:CA+FnnTyZY_1=62Rbk_kKZ39tkeoA6JVmFn9qs17aS-2YD4dVnA at mail.gmail.com... > > Yes, I saw your post to sqlite3 ML. > And I do know that by default sqlite3 does not have many types supported. > > However, all you need to do is save it as DECIMAL(10,2). > It is supported is sqlite3 and it will have NUMERIC affinity (ref 1) > or REAL (ref 2), which means the data will > be stored as decimals and not a string. > Do you mean CREATE TABLE fmtemp (acno INT, balance DECIMAL(10,2)); ? I tried that, but I got exactly the same result. The answer, as explained by several people on the sqlite3 ML, is that sqlite3 does not have a true decimal type and therefore uses floating point internally. As we all know from many questions asked on this forum, floating point and exact decimal representation are incompatible. Frank From rosuav at gmail.com Sat Dec 12 00:56:15 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 16:56:15 +1100 Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <566ba636$0$1589$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> <566ba636$0$1589$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Dec 12, 2015 at 3:44 PM, Steven D'Aprano wrote: > On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote: > >> Intuitiveness and productivity have a >> synergy like peas and carrots! One cannot be productive if one is fighting >> an unintuitive interface. Could you drive with your toes? How about your >> tongue? > > Drive a car with my tongue? Perhaps not, but I could drive a car with my > mouth if it were equipped with a sufficiently powerful interface. > > "Driver, please take me to the airport." Bring on the self-driving cars! They're already comparable to human drivers in skill. Instead of getting my sister to chauffeur me around, I could just hop in my automatic car, tell it my destination, and sit back with my laptop. All I need is for them to become more affordable. > In practice, "intuitive interface" gets bandied about in two ways: > > (2) Others use it to mean an interface which is: > > * predictable; > * consistent; > * easy to explore and learn; > * and "easy to use" in some vague sense. > > > They recognise that what seems unpredictable to one person may be perfectly > predictable to a more experienced user. Which really means that "intuitive" is a feature of skill/comprehension transference. This is the exact reason for the extensive use of metaphors in design - even though those metaphors often get orphanned, they are useful. How many people have actually carried around a folder full of documents? A few of you, maybe? How many of you instantly understand what a folder is, and that you can drag documents into it? Everyone. It makes perfect sense that you should be able to put stuff inside other stuff, so we can extend that to "compressed folders" or "shared folders" or "backed-up folders" or any other adjective you care to use. These are then touted as "intuitive" - eg I can use Dropbox by just sticking something into the Dropbox folder, ergo this interface is intuitive. Most modern languages seem to assume at least some knowledge of mathematics (maybe as far as algebra). It's considered intuitive that (1.0 + 2.0 / 6.0) should be equal to 1.333, because the fraction bar translates fairly readily into the slash. (And it doesn't equal 0.5, because the order of operations demands it.) Learning that you need the asterisk for multiplication is usually not a problem - at worst, it's the price you pay for multi-letter names (xy is distinct from x*y). Give people a staircase of small comprehensions and they'll master it; shove them up against a wall of new knowledge and they can't mantle up. >> (1) When laymen consider the word "print" (in the context of computing), >> they first think of "sending a document to a printing device". > > No they don't. They think of printing to the screen, not printing to paper. > > Even if they think of printing to paper, it takes them less than a second to > learn otherwise. That's a fantastic user interface: you can learn and > explore the functionality of the language very easily. Maybe if you had people entering code on a typewriter and seeing the output two hours later on parchment, then they'd assume it meant print to paper. Does anyone these days even print out listings? There are two broad types of code: Simple and complex. There are two broad types of job: Common and unusual. If you see a very simple piece of code, you will generally expect that it's doing something common. Let's posit a domain-specific language for building objects for a MMORPG. Here's a piece of code, with all crucial keywords replaced with names from my current D&D campaign: soyutlanma on_wield(player) [[[ parildiyor player#level >> 72 [[[ dogmakta ?You cannot wield this weapon.? uzakta ]]] parildiyor player#classes << {?bard?} [[[ dogmakta ?You can ne'er wield this weapon.? uzakta ]]] dogmakta ?It feels strong and sturdy in your hand.? taneleri item, inventory [[[ parildiyor kaylee<->item [[[ dogmakta ?Your helmet glows brightly with increased magic!? ]]] ]]] ]]] So, what operations do you think would be sufficiently common to justify language keywords? I've deliberately made them nonsense so there's no clues from the words themselves, but I expect that anyone here should have a reasonable shot at figuring out what things might mean. Voila! I've made an intuitive language. Right? Sending content to a printer is at least as complicated as writing to a file on disk. I would expect that any language keyword or built-in function for generating paper output should, at a minimum, stipulate which printer it's going to, and have a means of saying "I'm done with that page now". We don't tend tto "log to prn" these days, so you wouldn't expect to see a command/function to "write this line to the printer, and if there are 66 lines written, push that page out and bring the next one in". > (One of the weaknesses of Python, and nearly all mainstream programming > languages, is that there is nothing even remotely like an easy-to-explore > UI for programming GUI applications.) That might change without any change to Python. All you need is to start by introducing a GUI builder, and then have a way to pop out an "event editor" where you enter the code to be run when a button gets clicked (and that code would then be Python). But I'm not sure we need that. In my experience, those kinds of "hey, don't write code yet" tools tend to be either very limiting, or just as complicated as writing actual code. >> (2) The path to the underlying process is not even remotely clear. LIKE IT >> NOT, PRINT IS "MAGIC SYNTAX". > > print does what it says of the tin: it prints (to the screen). You don't > have to understand how it manages that to use it effectively, just as you > don't have to understand calculus in order to use math.sqrt(). More specifically, it prints to the standard output stream. Understanding how info gets from that stream to an actual screen is another huge mess. Back when I first learned 80x86 assembly language programming under DOS, I could write a tiny program like this: B4 09 BA 09 01 CD 21 CD 20 and then append whatever text I want to write (terminated by 24, dollar sign). That would write the specified content to stdout, which first goes through a whole lot of DOS checks to see if there's redirection or anything, and maybe parses ANSI.SYS codes, and then hands the characters off to the BIOS, which does another bunch of checks, then stuffs the bytes into video memory, where they get picked up by the video card, transformed into pixels, and then encoded into the appropriate signal, which goes to the actual monitor, which renders 720x348 pixels (we had a Hercules Graphics Card and a monochrome monitor) by pitching quantum particles at incredible speeds through powerful magnets at phosphors that get so excited they positively glow, which then stimulates my optic nerve... you know, we could go on like this ad infinitum, but the fact is, that program *wrote to the screen*. And I felt great accomplishment for doing so. ChrisA From rosuav at gmail.com Sat Dec 12 01:09:02 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 17:09:02 +1100 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: On Sat, Dec 12, 2015 at 4:10 PM, Frank Millman wrote: > I can reproduce your example above. However, if I set the initial value to > 5678.7, then the sequence goes > > 5678.7 > 5802.15 > 5925.6 > 6049.05 > 6172.5 > > I would have thought that adding 123.45 to 5802.15 would always produce the > same result, but here it seems to depend on prior events. > > Any idea why? Academic interest only, but I am curious. You weren't adding 123.45 to 5802.15. Here's why. The number 123.45 is actually represented as: >>> 123.45.as_integer_ratio() (8687021468732621, 70368744177664) that is, 8687021468732621/2**46. The exact value you want is actually a repeating binary fraction: 0b1111011.0111001100110011001100... with the 1100 part repeating. Python rounds this up to 0b11110110111001100110011001100110011001100110011001101, with a notation that this has an exponent of -46. (Presumably SQLite3 is doing the same, but I'm using Python's introspection here. This is all IEEE 754 floating point.) So when you set the initial value to 0 and then add 123.45 fifty times, you're adding that tiny bit of rounding error fifty times, too. When you set your initial value to 5678.7, you're skipping most of the accumulated error, and so the result still looks the same. When you printed out something that looked fine, it's because it actually rounded to the value you started with; that is to say, you weren't working with 5802.15, but with something really REALLY close to it. When you added one more of that rounding error, you tipped the sum across a boundary mark, and suddenly it didn't look like the decimal number you were expecting; but in reality, it never was. There's a lot of academic interest to be found in this, and a lot of fun to be had playing around. If you want to learn more, separate this from SQLite3 and just play around in Python - you'll find it easier. ChrisA From frank at chagford.com Sat Dec 12 01:22:40 2015 From: frank at chagford.com (Frank Millman) Date: Sat, 12 Dec 2015 08:22:40 +0200 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: "Chris Angelico" wrote in message news:CAPTjJmoPXFSnXe1QA8MjjncBZBpqNkztha8YHJv=MBm--ZE8jg at mail.gmail.com... > On Sat, Dec 12, 2015 at 4:10 PM, Frank Millman wrote: > > I can reproduce your example above. However, if I set the initial value > > to > > 5678.7, then the sequence goes > > > > 5678.7 > > 5802.15 > > 5925.6 > > 6049.05 > > 6172.5 > > > > I would have thought that adding 123.45 to 5802.15 would always produce > > the > > same result, but here it seems to depend on prior events. > > > > Any idea why? Academic interest only, but I am curious. > > You weren't adding 123.45 to 5802.15. Here's why. [snip really interesting explanation] Wow, thanks for that, Chris. Consider my academic curiosity well and truly satisfied :-) I have found a workaround for my problem, but I will post that in a separate message - still testing to make sure it is 100%. Frank From frank at chagford.com Sat Dec 12 02:31:33 2015 From: frank at chagford.com (Frank Millman) Date: Sat, 12 Dec 2015 09:31:33 +0200 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: "Frank Millman" wrote in message news:n4ei3l$b98$1 at ger.gmane.org... > I need to store Decimal objects in a sqlite3 database, using Python 3.4 on > Windows 7. > > I followed the instructions here - > > > http://stackoverflow.com/questions/6319409/how-to-convert-python-decimal-to-sqlite-numeric > > It seemed to work well, but then I hit a problem. > [...] I have found a workaround for my problem, but first I needed to understand what was going on more clearly. This is what I have figured out. 1. The solution in the SO article is a bit of sleight of hand, though very effective. It does not create a Decimal type in sqlite3. It simply provides a way of converting Decimal objects to strings when you pass them into the database, and converting them back to Decimal types when you read them back. 2. This works if you only use sqlite3 as a storage mechanism, and use Python to perform any arithmetic required. It fails when you try to use sqlite3 to perform arithmetic, as it uses floating point internally and suffers from the same problem that Python does when trying to mix floating point and precise decimal representation. 3. Normally I do use Python to perform the arithmetic, but in this situation I wanted to do the following - UPDATE table SET balance = balance + ? WHERE date > ? It would be very inefficient to read every row into Python, perform the addition, and write it back again. 4. The Python sqlite3 module allows you to create a user-defined function that you can use from within SQL statements. I realised I could use this to get the best of both worlds. I wrote the following function - def aggregate(curr_value, aggr_value): return '#{}'.format(D(curr_value[1:]) + D(aggr_value[1:])) and added this to the connection - conn.create_function('aggregate', 2, aggregate) I could then rewrite my statement as - UPDATE table SET balance = aggregate(balance, ?) WHERE date > ? 5. The reason for the '#' in the above function is that sqlite3 passes the current value of 'balance' into my function, and it has a bad habit of trying to second-guess the data-type to use. Even though I store it as a string, it passes in an integer or float. Prefixing it with a '#' forces it to remain as a string. My adapters therefore now look like this - # Decimal adapter (store Decimal in database as str) sqlite3.register_adapter(D, lambda d:'#'+str(d)) # Decimal converter (convert back to Decimal on return) sqlite3.register_converter('DEC', lambda s: D(s.decode('utf-8')[1:])) 6. Putting it all together, I can now run my test program - while True: print(cur.execute("SELECT bal FROM fmtemp").fetchone()[0]) cur.execute("UPDATE fmtemp SET bal = aggregate(bal, ?)", (D('123.45'),)) q = input() if q == 'q': break and it runs up to 123450.00 without misbehaving. Hope this is of interest. Frank From rosuav at gmail.com Sat Dec 12 02:45:53 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 18:45:53 +1100 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: IOn Sat, Dec 12, 2015 at 6:31 PM, Frank Millman wrote: > I have found a workaround for my problem, but first I needed to understand > what was going on more clearly. This is what I have figured out. > > 1. The solution in the SO article is a bit of sleight of hand, though very > effective. It does not create a Decimal type in sqlite3. It simply provides > a way of converting Decimal objects to strings when you pass them into the > database, and converting them back to Decimal types when you read them back. > > 2. This works if you only use sqlite3 as a storage mechanism, and use Python > to perform any arithmetic required. It fails when you try to use sqlite3 to > perform arithmetic, as it uses floating point internally and suffers from > the same problem that Python does when trying to mix floating point and > precise decimal representation. There's another possibility, and that's fixed-point arithmetic. You store the numbers as integers - probably cents, if you're talking about dollar amounts - and as long as the scaled values fit inside the available integer type (probably 64-bit), you'll be fine. Or, of course, you could switch to a database back end that actually supports NUMERIC data. ChrisA From idowuolawale at gmail.com Sat Dec 12 04:05:01 2015 From: idowuolawale at gmail.com (Harbey Leke) Date: Sat, 12 Dec 2015 01:05:01 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " Message-ID: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Create a class called BankAccount .Create a constructor that takes in an integer and assigns this to a `balance` property. .Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly. .Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` .Create a subclass MinimumBalanceAccount of the BankAccount class Please i need help on this i am a beginer into python programming. Also below is a test case given for this project import unittest class AccountBalanceTestCases(unittest.TestCase): def setUp(self): self.my_account = BankAccount(90) def test_balance(self): self.assertEqual(self.my_account.balance, 90, msg='Account Balance Invalid') def test_deposit(self): self.my_account.deposit(90) self.assertEqual(self.my_account.balance, 180, msg='Deposit method inaccurate') def test_withdraw(self): self.my_account.withdraw(40) self.assertEqual(self.my_account.balance, 50, msg='Withdraw method inaccurate') def test_invalid_operation(self): self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", msg='Invalid transaction') def test_sub_class(self): self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No true subclass of BankAccount') From rosuav at gmail.com Sat Dec 12 04:21:28 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 20:21:28 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Sat, Dec 12, 2015 at 8:05 PM, Harbey Leke wrote: > Create a class called BankAccount > > .Create a constructor that takes in an integer and assigns this to a `balance` property. > > .Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly. > > .Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` > > .Create a subclass MinimumBalanceAccount of the BankAccount class > > Please i need help on this i am a beginer into python programming. Start by creating a text file in which you will store your code. Then create a class called BankAccount, and start adding methods to it. Which part of this do you need help with? If you're taking a course on Python programming, you should have met these concepts. Go and read the course text and see if you can find the information you need. ChrisA From idowuolawale at gmail.com Sat Dec 12 05:09:01 2015 From: idowuolawale at gmail.com (Harbey Leke) Date: Sat, 12 Dec 2015 02:09:01 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: i need help with every part of the project, like a complete text of scripts for it, thrn i can practise with it on my own and then u can give me assignments to improve on thanks From rosuav at gmail.com Sat Dec 12 05:17:42 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Dec 2015 21:17:42 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Sat, Dec 12, 2015 at 9:09 PM, Harbey Leke wrote: > i need help with every part of the project, like a complete text of scripts for it, thrn i can practise with it on my own and then u can give me assignments to improve on > thanks No. You're the one taking the course; you write the code. If you get to the point of having code that ought to do everything but, for reasons you don't understand, doesn't, then you can post it here and ask for help figuring things out. But we're not going to do your homework for you. ChrisA From idowuolawale at gmail.com Sat Dec 12 05:27:04 2015 From: idowuolawale at gmail.com (Harbey Leke) Date: Sat, 12 Dec 2015 02:27:04 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <6f852b8c-5902-4639-a393-d3e5f3b1de88@googlegroups.com> oh oh okay start it for me please thanks or guide me about it then. From idowuolawale at gmail.com Sat Dec 12 05:29:48 2015 From: idowuolawale at gmail.com (Harbey Leke) Date: Sat, 12 Dec 2015 02:29:48 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: oh oh okay start it for me please thanks or guide me about it then. From kwpolska at gmail.com Sat Dec 12 05:37:58 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Sat, 12 Dec 2015 11:37:58 +0100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On 12 December 2015 at 11:29, Harbey Leke wrote: > oh oh okay start it for me please > thanks or guide me about it then. > -- > https://mail.python.org/mailman/listinfo/python-list class BankAccount(object): # your code goes here Seriously: read the materials you got with your course, or the Python tutorial and documentation at https://docs.python.org/ . -- Chris Warrick PGP: 5EAAEA16 From steve at pearwood.info Sat Dec 12 07:32:39 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Dec 2015 23:32:39 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <566c13e9$0$1583$c3e8da3$5496439d@news.astraweb.com> On Sat, 12 Dec 2015 08:05 pm, Harbey Leke wrote: > Create a class called BankAccount class BankAccount: pass That's easy. Unfortunately, that class does nothing, but at least it exists! Now all you have to do is create *methods* of the class that do the work. Here I give it a method called "display_balance" which prints the balance of the account: class BankAccount: def display_balance(self): bal = self.balance print(bal) Notice that the method is indented inside the class. Unfortunately, that method doesn't work yet. The problem is, the account doesn't yet have a balance, so obviously trying to print it will fail. First you need to do the next part of the assignment: > .Create a constructor that takes in an integer and assigns this to a > `balance` property. A "constructor" is a special method that Python automatically used to create new instances. (I hope you understand what instances are!) Python classes have two constructor methods: __new__ __init__ Notice that they both start and end with TWO underscores. Chances are, you won't need to use __new__, you will probably use __init__ instead. (Technically, __init__ is an initializer method, not a constructor, but most people don't care about the difference.) So you have to write a method called "__init__" that takes an integer argument (don't forget the "self" argument as well!) and assigns that to a balance property. Here is how you assign a value to a attribute called "name": self.name = "Harbey" And an attribute called "number": self.number = 23 And an attribute called "address": self.address = "742 Evergreen Terrace Springfield" See the pattern? How would you assign to an attribute called "balance"? Put that *inside* the constructor method inside the class. > .Create a method called `deposit` that takes in cash deposit amount and > updates the balance accordingly. > > .Create a method called `withdraw` that takes in cash withdrawal amount > and updates the balance accordingly. if amount is greater than balance > return `"invalid transaction"` Again, you need to create two new methods. Remember, you create a method with "def ..." and indent it inside the class. They must have a "self" argument, plus whatever extra arguments the instructions above demand. Here is how you would triple an attribute called "total": self.total = 3 * self.total How would you add or subtract from "balance" instead? I've given you most of the pieces you need to solve this problem. You just need to assemble them into working code. Off you go, write some code, and if you have any problems, show us what code you have written and ask for help. Just don't ask us to do your assignment for you. -- Steven From ganesh1pal at gmail.com Sat Dec 12 08:01:58 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Sat, 12 Dec 2015 18:31:58 +0530 Subject: python unit test frame work In-Reply-To: References: Message-ID: On Thu, Dec 10, 2015 at 9:20 PM, Peter Otten <__peter__ at web.de> wrote: > Ganesh Pal wrote: > > I recommend that you reread the unittest documentation. > > setUpClass() should be a class method, and if it succeeds you can release > the ressources it required in the corresponding tearDownClass() method. As > written the flags and the setUp()/tearDown() seem unnecessary. > Thanks to peter , Cameron and Ben Finney , for replying to my various question post . I needed a hint on the below 1. If there is a setUpClass exception or failure , I don't want the unittest to run ( I don't have teardown ) how do I handle this ? The traceback on the console looks very bad it repeats for all the test cases , that means if I have 100 testcases if setup fails . I will get the failure for all the test cases #c_t.py EEEE ====================================================================== ERROR: test01: test_01_inode_test ---------------------------------------------------------------------- Traceback (most recent call last): File "c_t.py", line xx, in setUp self.setupClass() File "c_t.py", line xxx, in TestSetup self.TestSetup() File "c_t.py", line xx, in corruptSetup sys.exit("/tmp is not mounted ...Exiting !!!") SystemExit: /tmp is not mounted ...Exiting !!! ====================================================================== ERROR: test02 ---------------------------------------------------------------------- Traceback (most recent call last): File "c_t.py", line 162, in test_02_hardlink_test self.inject_failures['test02'])) KeyError: 'test02' Ran 2 tests in 0.003s FAILED (errors=2) From satish at driveu.in Sat Dec 12 08:09:04 2015 From: satish at driveu.in (satish at driveu.in) Date: Sat, 12 Dec 2015 05:09:04 -0800 (PST) Subject: XMPP pub sub setup and working Message-ID: <2745ea24-d06f-41e9-99a7-1516b3a2bbc3@googlegroups.com> I am using xmpppy python library to connect with XMPP server(ejabberd2) but unable to connect and actually don't have clarity on how to connect, authenticate and send a message to the server. Please help me to make it working If possible please provide some code snippet using XMPPPY. This is what I have tried: In [1]: from xmpp import Client In [2]: cl = Client(server='176.9.18.111', 5280) File "", line 1 cl = Client(server='176.9.18.111', 5280) SyntaxError: non-keyword arg after keyword arg In [3]: cl = Client(server='176.9.18.111', port =5280) Invalid debugflag given: always Invalid debugflag given: nodebuilder DEBUG: DEBUG: Debug created for /Users/gathole/.virtualenvs/driveu/lib/python2.7/site-packages/xmpp/client.py DEBUG: flags defined: always,nodebuilder In [4]: cl.connect() DEBUG: socket start Plugging into DEBUG: socket warn An error occurred while looking up _xmpp-client._tcp.176.9.18.111 DEBUG: socket start Successfully connected to remote host ('176.9.18.111', 5280) DEBUG: dispatcher start Plugging into DEBUG: dispatcher info Registering namespace "unknown" DEBUG: dispatcher info Registering protocol "unknown" as (unknown) DEBUG: dispatcher info Registering protocol "default" as (unknown) DEBUG: dispatcher info Registering namespace "http://etherx.jabber.org/streams" DEBUG: dispatcher info Registering protocol "unknown" as (http://etherx.jabber.org/streams) DEBUG: dispatcher info Registering protocol "default" as (http://etherx.jabber.org/streams) DEBUG: dispatcher info Registering namespace "jabber:client" DEBUG: dispatcher info Registering protocol "unknown" as (jabber:client) DEBUG: dispatcher info Registering protocol "default" as (jabber:client) DEBUG: dispatcher info Registering protocol "iq" as (jabber:client) DEBUG: dispatcher info Registering protocol "presence" as (jabber:client) DEBUG: dispatcher info Registering protocol "message" as (jabber:client) DEBUG: dispatcher info Registering handler > for "error" type-> ns->(http://etherx.jabber.org/streams) DEBUG: dispatcher warn Registering protocol "error" as (http://etherx.jabber.org/streams) DEBUG: socket sent DEBUG: socket error Socket error while receiving data DEBUG: client stop Disconnect detected DEBUG: socket error Socket operation failed Out[4]: '' From __peter__ at web.de Sat Dec 12 08:49:43 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Dec 2015 14:49:43 +0100 Subject: python unit test frame work References: Message-ID: Ganesh Pal wrote: > On Thu, Dec 10, 2015 at 9:20 PM, Peter Otten <__peter__ at web.de> wrote: >> Ganesh Pal wrote: >> > >> I recommend that you reread the unittest documentation. >> >> setUpClass() should be a class method, and if it succeeds you can release >> the ressources it required in the corresponding tearDownClass() method. >> As written the flags and the setUp()/tearDown() seem unnecessary. >> > > Thanks to peter , Cameron and Ben Finney , for replying to my various > question post . I needed a hint on the below > > > 1. If there is a setUpClass exception or failure , I don't want the > unittest to run ( I don't have teardown ) how do I handle this ? > The traceback on the console looks very bad it repeats for all > the test cases , that means if I have 100 testcases if setup fails . > I will get the failure for all the test cases > > #c_t.py > EEEE > ====================================================================== > ERROR: test01: test_01_inode_test > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "c_t.py", line xx, in setUp > self.setupClass() > File "c_t.py", line xxx, in TestSetup > self.TestSetup() > File "c_t.py", line xx, in corruptSetup > sys.exit("/tmp is not mounted ...Exiting !!!") > SystemExit: /tmp is not mounted ...Exiting !!! > ====================================================================== > ERROR: test02 > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "c_t.py", line 162, in test_02_hardlink_test > self.inject_failures['test02'])) > KeyError: 'test02' > > Ran 2 tests in 0.003s > FAILED (errors=2) Don't invoke sys.exit(), raise a meaningful exception instead. Then in setUpClass() you can catch the expected exceptions and raise a SkipTest. Example: $ cat mayfail.py import os import unittest def setup_that_may_fail(): if "FAIL" in os.environ: 1/0 class MyTests(unittest.TestCase): @classmethod def setUpClass(cls): try: setup_that_may_fail() # placeholder for your actual setup except Exception as err: raise unittest.SkipTest( "class setup failed") # todo: better message def test_one(self): pass def test_two(self): pass if __name__ == "__main__": unittest.main() When the setup succeeds: $ python mayfail.py .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK Now let's pretend a failure by setting the FAIL environment variable. (In your actual code you won't do that as you get a "real" failure) $ FAIL=1 python mayfail.py s ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK (skipped=1) There's one oddity with this approach -- only one skipped test is reported even though there are two tests in the class, neither of which is run. From tony at vanderhoff.org Sat Dec 12 09:42:27 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 12 Dec 2015 14:42:27 +0000 Subject: 2to3 translation problem Message-ID: Debian Jessie, python 2.7; python 3.4 I have an application, using pygame for graphics, that works fine under python2.7. I have run it through 2to3, but when running the result under python 3.4, I get the error : Traceback (most recent call last): File "ppm304.py", line 9, in import pygame ImportError: No module named 'pygame' So, python 3.4 can't find the library, whilst python 2.7 can. How do I track down/fix the missing dependency. From breamoreboy at yahoo.co.uk Sat Dec 12 10:09:19 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Dec 2015 15:09:19 +0000 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/2015 14:42, Tony van der Hoff wrote: > Debian Jessie, python 2.7; python 3.4 > > I have an application, using pygame for graphics, that works fine under > python2.7. I have run it through 2to3, but when running the result under > python 3.4, I get the error : > > Traceback (most recent call last): > File "ppm304.py", line 9, in > import pygame > ImportError: No module named 'pygame' > > So, python 3.4 can't find the library, whilst python 2.7 can. > How do I track down/fix the missing dependency. This isn't a 2to3 translation problem. You've installed pygame under 2.7 at some point, repeat the process for 3.4. I've no idea how you'd do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From tony at vanderhoff.org Sat Dec 12 11:31:54 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 12 Dec 2015 16:31:54 +0000 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/15 15:09, Mark Lawrence wrote: > On 12/12/2015 14:42, Tony van der Hoff wrote: >> Debian Jessie, python 2.7; python 3.4 >> >> I have an application, using pygame for graphics, that works fine under >> python2.7. I have run it through 2to3, but when running the result under >> python 3.4, I get the error : >> >> Traceback (most recent call last): >> File "ppm304.py", line 9, in >> import pygame >> ImportError: No module named 'pygame' >> >> So, python 3.4 can't find the library, whilst python 2.7 can. >> How do I track down/fix the missing dependency. > > This isn't a 2to3 translation problem. You've installed pygame under > 2.7 at some point, repeat the process for 3.4. I've no idea how you'd > do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". > Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from Debian's repository, via apt-get install python-pygame. I believe that should be effective for any version of Python. Thanks anyway, Tony From breamoreboy at yahoo.co.uk Sat Dec 12 11:56:05 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Dec 2015 16:56:05 +0000 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/2015 16:31, Tony van der Hoff wrote: > On 12/12/15 15:09, Mark Lawrence wrote: >> On 12/12/2015 14:42, Tony van der Hoff wrote: >>> Debian Jessie, python 2.7; python 3.4 >>> >>> I have an application, using pygame for graphics, that works fine under >>> python2.7. I have run it through 2to3, but when running the result under >>> python 3.4, I get the error : >>> >>> Traceback (most recent call last): >>> File "ppm304.py", line 9, in >>> import pygame >>> ImportError: No module named 'pygame' >>> >>> So, python 3.4 can't find the library, whilst python 2.7 can. >>> How do I track down/fix the missing dependency. >> >> This isn't a 2to3 translation problem. You've installed pygame under >> 2.7 at some point, repeat the process for 3.4. I've no idea how you'd >> do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". >> > Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from > Debian's repository, via apt-get install python-pygame. I believe that > should be effective for any version of Python. > > Thanks anyway, > Tony My belief is that every package has to be installed in the site-packages directory for each version of Python. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From __peter__ at web.de Sat Dec 12 11:59:52 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Dec 2015 17:59:52 +0100 Subject: 2to3 translation problem References: Message-ID: Tony van der Hoff wrote: > On 12/12/15 15:09, Mark Lawrence wrote: >> On 12/12/2015 14:42, Tony van der Hoff wrote: >>> Debian Jessie, python 2.7; python 3.4 >>> >>> I have an application, using pygame for graphics, that works fine under >>> python2.7. I have run it through 2to3, but when running the result under >>> python 3.4, I get the error : >>> >>> Traceback (most recent call last): >>> File "ppm304.py", line 9, in >>> import pygame >>> ImportError: No module named 'pygame' >>> >>> So, python 3.4 can't find the library, whilst python 2.7 can. >>> How do I track down/fix the missing dependency. >> >> This isn't a 2to3 translation problem. You've installed pygame under >> 2.7 at some point, repeat the process for 3.4. I've no idea how you'd >> do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". >> > Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from > Debian's repository, via apt-get install python-pygame. I believe that > should be effective for any version of Python. No, that is the version for Python 2. If there is a Python 3 version it will be called python3-pygame but no such package seems to be available: https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=python3-pygame From lac at openend.se Sat Dec 12 12:08:30 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 12 Dec 2015 18:08:30 +0100 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: <201512121708.tBCH8U5c013113@fido.openend.se> In a message of Sat, 12 Dec 2015 16:31:54 +0000, Tony van der Hoff writes: >On 12/12/15 15:09, Mark Lawrence wrote: >> On 12/12/2015 14:42, Tony van der Hoff wrote: >>> Debian Jessie, python 2.7; python 3.4 >>> >>> I have an application, using pygame for graphics, that works fine under >>> python2.7. I have run it through 2to3, but when running the result under >>> python 3.4, I get the error : >>> >>> Traceback (most recent call last): >>> File "ppm304.py", line 9, in >>> import pygame >>> ImportError: No module named 'pygame' >>> >>> So, python 3.4 can't find the library, whilst python 2.7 can. >>> How do I track down/fix the missing dependency. >> >> This isn't a 2to3 translation problem. You've installed pygame under >> 2.7 at some point, repeat the process for 3.4. I've no idea how you'd >> do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". >> >Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from >Debian's repository, via apt-get install python-pygame. I believe that >should be effective for any version of Python. You are mistaken here. python-pygame is only a python 2.7 pygame. you want python3-pygame. https://packages.debian.org/search?keywords=python3-pygame Speaking as a debian user are going to have a _whole lot of this_. If you don't know about apt-cache search let me recommend it to you. This on debian unstable: lac at smartwheels:~$ apt-cache search pygame lightyears - single player real-time strategy game with steampunk sci-fi psychopy - environment for creating psychology stimuli in Python python-pygame - SDL bindings for games development in Python python-pyglet - cross-platform windowing and multimedia library pyntor - flexible and componentized presentation program solarwolf - Collect the boxes and don't become mad python-soya - high level 3D engine for Python python-soya-dbg - high level 3D engine for Python - debug extension python-soya-doc - high level 3D engine for Python python3-pygame - SDL bindings for games development in Python (Python 3) So, too many hits, alas, but it does tend to find such things. Laura From lac at openend.se Sat Dec 12 12:09:47 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 12 Dec 2015 18:09:47 +0100 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: <201512121709.tBCH9l0K013216@fido.openend.se> In a message of Sat, 12 Dec 2015 17:59:52 +0100, Peter Otten writes: >Tony van der Hoff wrote: > >> On 12/12/15 15:09, Mark Lawrence wrote: >>> On 12/12/2015 14:42, Tony van der Hoff wrote: >>>> Debian Jessie, python 2.7; python 3.4 >>>> >>>> I have an application, using pygame for graphics, that works fine under >>>> python2.7. I have run it through 2to3, but when running the result under >>>> python 3.4, I get the error : >>>> >>>> Traceback (most recent call last): >>>> File "ppm304.py", line 9, in >>>> import pygame >>>> ImportError: No module named 'pygame' >>>> >>>> So, python 3.4 can't find the library, whilst python 2.7 can. >>>> How do I track down/fix the missing dependency. >>> >>> This isn't a 2to3 translation problem. You've installed pygame under >>> 2.7 at some point, repeat the process for 3.4. I've no idea how you'd >>> do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". >>> >> Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from >> Debian's repository, via apt-get install python-pygame. I believe that >> should be effective for any version of Python. > >No, that is the version for Python 2. If there is a Python 3 version it will >be called > >python3-pygame > >but no such package seems to be available: > >https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=python3-pygame There is one in unstable, I forgot to check for jessie, sorry about that. Laura From tony at vanderhoff.org Sat Dec 12 12:30:55 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 12 Dec 2015 17:30:55 +0000 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/15 17:09, Laura Creighton wrote: > In a message of Sat, 12 Dec 2015 17:59:52 +0100, Peter Otten writes: >> Tony van der Hoff wrote: >> >>> On 12/12/15 15:09, Mark Lawrence wrote: >>>> On 12/12/2015 14:42, Tony van der Hoff wrote: >>>>> Debian Jessie, python 2.7; python 3.4 >>>>> >>>>> I have an application, using pygame for graphics, that works fine under >>>>> python2.7. I have run it through 2to3, but when running the result under >>>>> python 3.4, I get the error : >>>>> >>>>> Traceback (most recent call last): >>>>> File "ppm304.py", line 9, in >>>>> import pygame >>>>> ImportError: No module named 'pygame' >>>>> >>>>> So, python 3.4 can't find the library, whilst python 2.7 can. >>>>> How do I track down/fix the missing dependency. >>>> >>>> This isn't a 2to3 translation problem. You've installed pygame under >>>> 2.7 at some point, repeat the process for 3.4. I've no idea how you'd >>>> do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame". >>>> >>> Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from >>> Debian's repository, via apt-get install python-pygame. I believe that >>> should be effective for any version of Python. >> >> No, that is the version for Python 2. If there is a Python 3 version it will >> be called >> >> python3-pygame >> >> but no such package seems to be available: >> >> https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=python3-pygame > > There is one in unstable, I forgot to check for jessie, sorry about that. > > Laura > Thanks, Laura, and others who have replied. You're right; python-3-pygame exists in unstable, but has not yet made it to jessie, even in backports. So, I'll stick with python 2.7 for the time being; really no hardship :) From mkatietola at gmail.com Sat Dec 12 12:37:16 2015 From: mkatietola at gmail.com (mkatietola at gmail.com) Date: Sat, 12 Dec 2015 09:37:16 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <566c13e9$0$1583$c3e8da3$5496439d@news.astraweb.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <566c13e9$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: Thank you so much Steven you've given me a really great head start From rosuav at gmail.com Sat Dec 12 12:50:43 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 13 Dec 2015 04:50:43 +1100 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On Sun, Dec 13, 2015 at 4:30 AM, Tony van der Hoff wrote: > Thanks, Laura, and others who have replied. You're right; python-3-pygame > exists in unstable, but has not yet made it to jessie, even in backports. > > So, I'll stick with python 2.7 for the time being; really no hardship :) The easiest solution is simply: python3 -m pip install pygame Don't worry about it not being in the Jessie repo - you can always grab things using pip. ChrisA From lac at openend.se Sat Dec 12 12:54:23 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 12 Dec 2015 18:54:23 +0100 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: <201512121754.tBCHsNd6013810@fido.openend.se> In a message of Sun, 13 Dec 2015 04:50:43 +1100, Chris Angelico writes: >On Sun, Dec 13, 2015 at 4:30 AM, Tony van der Hoff wrote: >> Thanks, Laura, and others who have replied. You're right; python-3-pygame >> exists in unstable, but has not yet made it to jessie, even in backports. >> >> So, I'll stick with python 2.7 for the time being; really no hardship :) > >The easiest solution is simply: > >python3 -m pip install pygame > >Don't worry about it not being in the Jessie repo - you can always >grab things using pip. > >ChrisA What Chris said. :) If you are about to move your life from being python2.7 based to being 3.x, you are not going to be able to depend on things getting to jessie in a timely fashion. So you will be doing this a whole lot. Laura From amicale.salmson at free.fr Sat Dec 12 13:24:14 2015 From: amicale.salmson at free.fr (sms) Date: Sat, 12 Dec 2015 19:24:14 +0100 Subject: tkinter: Switch between two grids Message-ID: <566c664e$0$3071$426a74cc@news.free.fr> Hello all, I'm sorry to ask this question, but I am a very beginer. What I need: 1. Fullscreen application 2. On the home screen: Three row 3. When I click on the main screen, it switches to one row only. Actually, I am not able to switch from Window1 to Window2, Window2 comes under Window1 Any help would be greatly appreciated. Please, find my shameful code : import sys if sys.version_info[0] < 3: import Tkinter as Tk else: import tkinter as Tk def destroy(e): sys.exit() class Window1(): def __init__(self, master): self.frame=Tk.Frame(master, bg="Green", borderwidth=10) sticky=Tk.N+Tk.S+Tk.E+Tk.W self.frame.grid(sticky=sticky) self.frame.columnconfigure(0, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=1) self.frame.rowconfigure(2, weight=1) self.v = Tk.StringVar() text = Tk.Label(self.frame, text="Text1") text.grid(column=0, row=0, sticky=sticky) self.h = Tk.StringVar() text = Tk.Label(self.frame, text="Text2") text.grid(column=0, row=1, sticky=sticky) self.d = Tk.StringVar() text = Tk.Label(self.frame, text="Text3") text.grid(column=0, row=2, sticky=sticky) class Window2: def __init__(self, master): self.frame = Tk.Frame(master, bg="black", borderwidth=10) sticky=Tk.N+Tk.S+Tk.E+Tk.W self.frame.grid(sticky=sticky) self.v = Tk.StringVar() text = Tk.Label(self.frame, text="Prout") text.grid(column=0, row=0, sticky=sticky) class VGui: def __init__(self): self.root = Tk.Tk() self.root.attributes("-fullscreen", True) Tk.Grid.rowconfigure(self.root, 0, weight=1) Tk.Grid.columnconfigure(self.root, 0, weight=1) self.Window1 = Window1(self.root) self.Window2 = Window2(self.root) self.root.bind("", self.Callback) def Start(self): Tk.mainloop() def Callback(self, event): self.Window2.frame.tkraise() if __name__ == '__main__' : gui=VGui() gui.Start() Thanks for reading. From darcy at VybeNetworks.com Sat Dec 12 14:01:13 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sat, 12 Dec 2015 14:01:13 -0500 Subject: codecs.StreamRecoder not doing what I expected. Message-ID: <20151212140113.78e3c945@imp> More Unicode bafflement. What I am trying to do is pretty simple I think. I have a bunch of files that I am pretty sure are either utf-8 or iso-8859-1. I try utf-8 and fall back to iso-8859-1 if it throws a UnicodeError. Here is my test. #! /usr/pkg/bin/python3.4 # Running on a NetBSD 7.0 server # Installed with pkgsrc import codecs test_file = "StreamRecoder.txt" def read_file(fn): try: return open(fn, "r", encoding='utf-8').read() except UnicodeError: return codecs.StreamRecoder(open(fn), codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'), codecs.getreader('iso-8859-1'), codecs.getwriter('iso-8859-1'), "r").read() # plain ASCII open(test_file, 'wb').write(b'abc - cents\n') print(read_file(test_file)) # utf-8 open(test_file, 'wb').write(b'abc - \xc2\xa2\n') print(read_file(test_file)) # iso-8859-1 open(test_file, 'wb').write(b'abc - \xa2\n') print(read_file(test_file)) I expected all three to return UTF-8 strings but here is my output: abc - cents abc - ? Traceback (most recent call last): File "./StreamRecoder_test", line 9, in read_file try: return open(fn, "r", encoding='utf-8').read() File "/usr/pkg/lib/python3.4/codecs.py", line 319, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 6: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./StreamRecoder_test", line 27, in print(read_file(test_file)) File "./StreamRecoder_test", line 15, in read_file codecs.getwriter('iso-8859-1'), "r").read() File "/usr/pkg/lib/python3.4/codecs.py", line 798, in read data = self.reader.read(size) File "/usr/pkg/lib/python3.4/codecs.py", line 489, in read newdata = self.stream.read() File "/usr/pkg/lib/python3.4/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xa2 in position 6: ordinal not in range(128) -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From tjreedy at udel.edu Sat Dec 12 15:17:24 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Dec 2015 15:17:24 -0500 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/2015 12:30 PM, Tony van der Hoff wrote: > Thanks, Laura, and others who have replied. You're right; > python-3-pygame exists in unstable, but has not yet made it to jessie, > even in backports. > > So, I'll stick with python 2.7 for the time being; really no hardship :) pygame itself was ported to 3.x years ago and the port is quite stable. -- Terry Jan Reedy From tony at vanderhoff.org Sat Dec 12 15:24:10 2015 From: tony at vanderhoff.org (Tony van der Hoff) Date: Sat, 12 Dec 2015 20:24:10 +0000 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: On 12/12/15 17:54, Laura Creighton wrote: > In a message of Sun, 13 Dec 2015 04:50:43 +1100, Chris Angelico writes: >> On Sun, Dec 13, 2015 at 4:30 AM, Tony van der Hoff wrote: >>> Thanks, Laura, and others who have replied. You're right; python-3-pygame >>> exists in unstable, but has not yet made it to jessie, even in backports. >>> >>> So, I'll stick with python 2.7 for the time being; really no hardship :) >> >> The easiest solution is simply: >> >> python3 -m pip install pygame >> >> Don't worry about it not being in the Jessie repo - you can always >> grab things using pip. >> >> ChrisA > > What Chris said. :) > > If you are about to move your life from being python2.7 based to > being 3.x, you are not going to be able to depend on things getting > to jessie in a timely fashion. So you will be doing this a whole lot. No: tony at tony-lx:~$ python3 -m pip install pygame /usr/bin/python3: No module named pip Hmm, apt-get install python3-pip: OK tony at tony-lx:~$ python3 -m pip install pygame Downloading/unpacking pygame Could not find any downloads that satisfy the requirement pygame Some externally hosted files were ignored (use --allow-external pygame to allow). Cleaning up... No distributions at all found for pygame Storing debug log for failure in /home/tony/.pip/pip.log I really can't be bothered... Thanks for the hints. From tjreedy at udel.edu Sat Dec 12 15:29:26 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Dec 2015 15:29:26 -0500 Subject: tkinter: Switch between two grids In-Reply-To: <566c664e$0$3071$426a74cc@news.free.fr> References: <566c664e$0$3071$426a74cc@news.free.fr> Message-ID: On 12/12/2015 1:24 PM, sms wrote: > What I need: > 1. Fullscreen application Not directly relevant to the below. > 2. On the home screen: Three row > 3. When I click on the main screen, it switches to one row only. Create homescreen Frame(master=root) or subclasses thereof. Pack the homescreen. When click, homescreen.pack_forget(), then create and and pack the other screen (with root as master). -- Terry Jan Reedy From __peter__ at web.de Sat Dec 12 15:35:36 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Dec 2015 21:35:36 +0100 Subject: codecs.StreamRecoder not doing what I expected. References: <20151212140113.78e3c945@imp> Message-ID: D'Arcy J.M. Cain wrote: > More Unicode bafflement. What I am trying to do is pretty simple I > think. I have a bunch of files that I am pretty sure are either utf-8 > or iso-8859-1. I try utf-8 and fall back to iso-8859-1 if it throws a > UnicodeError. Here is my test. > > #! /usr/pkg/bin/python3.4 > # Running on a NetBSD 7.0 server > # Installed with pkgsrc > > import codecs > test_file = "StreamRecoder.txt" > > def read_file(fn): > try: return open(fn, "r", encoding='utf-8').read() > except UnicodeError: > return codecs.StreamRecoder(open(fn), A recoder converts bytes to bytes, so you have to open the file in binary mode. However, ... > codecs.getencoder('utf-8'), > codecs.getdecoder('utf-8'), > codecs.getreader('iso-8859-1'), > codecs.getwriter('iso-8859-1'), "r").read() > > # plain ASCII > open(test_file, 'wb').write(b'abc - cents\n') > print(read_file(test_file)) > > # utf-8 > open(test_file, 'wb').write(b'abc - \xc2\xa2\n') > print(read_file(test_file)) > > # iso-8859-1 > open(test_file, 'wb').write(b'abc - \xa2\n') > print(read_file(test_file)) ...when the recoder kicks in read_file() will return bytes which is probably not what you want. Why not just try the two encodings as in def read_file(filename): for encoding in ["utf-8", "iso-8859-1"]: try: with open(filename, encoding=encoding) as f: return f.read() except UnicodeDecodeError: pass raise AssertionError("unreachable") > > I expected all three to return UTF-8 strings but here is my output: > > abc - cents > > abc - ? > > Traceback (most recent call last): > File "./StreamRecoder_test", line 9, in read_file > try: return open(fn, "r", encoding='utf-8').read() > File "/usr/pkg/lib/python3.4/codecs.py", line 319, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 6: > invalid start byte > > During handling of the above exception, another exception occurred: > > Traceback (most recent call last): > File "./StreamRecoder_test", line 27, in > print(read_file(test_file)) > File "./StreamRecoder_test", line 15, in read_file > codecs.getwriter('iso-8859-1'), "r").read() > File "/usr/pkg/lib/python3.4/codecs.py", line 798, in read > data = self.reader.read(size) > File "/usr/pkg/lib/python3.4/codecs.py", line 489, in read > newdata = self.stream.read() > File "/usr/pkg/lib/python3.4/encodings/ascii.py", line 26, in decode > return codecs.ascii_decode(input, self.errors)[0] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa2 in position 6: > ordinal not in range(128) > From lac at openend.se Sat Dec 12 16:18:26 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 12 Dec 2015 22:18:26 +0100 Subject: 2to3 translation problem In-Reply-To: References: Message-ID: <201512122118.tBCLIQt7016118@fido.openend.se> In a message of Sat, 12 Dec 2015 20:24:10 +0000, Tony van der Hoff writes: >On 12/12/15 17:54, Laura Creighton wrote: >> In a message of Sun, 13 Dec 2015 04:50:43 +1100, Chris Angelico writes: >>> On Sun, Dec 13, 2015 at 4:30 AM, Tony van der Hoff wrote: >>>> Thanks, Laura, and others who have replied. You're right; python-3-pygame >>>> exists in unstable, but has not yet made it to jessie, even in backports. >>>> >>>> So, I'll stick with python 2.7 for the time being; really no hardship :) >>> >>> The easiest solution is simply: >>> >>> python3 -m pip install pygame >>> >>> Don't worry about it not being in the Jessie repo - you can always >>> grab things using pip. >>> >>> ChrisA >> >> What Chris said. :) >> >> If you are about to move your life from being python2.7 based to >> being 3.x, you are not going to be able to depend on things getting >> to jessie in a timely fashion. So you will be doing this a whole lot. > >No: >tony at tony-lx:~$ python3 -m pip install pygame >/usr/bin/python3: No module named pip > >Hmm, apt-get install python3-pip: OK > >tony at tony-lx:~$ python3 -m pip install pygame >Downloading/unpacking pygame > Could not find any downloads that satisfy the requirement pygame > Some externally hosted files were ignored (use --allow-external >pygame to allow). >Cleaning up... >No distributions at all found for pygame >Storing debug log for failure in /home/tony/.pip/pip.log > >I really can't be bothered... > >Thanks for the hints. Sorry, I forgot to warn you. Debian, in its wisdom breaks python up into several pieces, and so if you install python as a debian package, you have to install the ability to use pip separately. apt-get install python-pip (for 2.x) apt-get install python3-pip (for 3.x) Laura From vincentypedro at gmail.com Sat Dec 12 16:48:29 2015 From: vincentypedro at gmail.com (Pedro Vincenty) Date: Sat, 12 Dec 2015 13:48:29 -0800 (PST) Subject: appending a line to a list based off of a string found in a previous list Message-ID: Hello, I'm wondering how to append a line from a file onto a list(easy part) provided that the line contains strings specific to a previous list I've already made(hard part). I have this right now, for line in satellite_dataread: if any(i in line for i in list2): line= line.strip() satellite, country= line.split(',') satellite_origin_list.append(country) the statement if statement seems to work as I take it out of the for loop, but not as I have it presented. Thanks a bunch!! From tjreedy at udel.edu Sat Dec 12 17:17:59 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Dec 2015 17:17:59 -0500 Subject: appending a line to a list based off of a string found in a previous list In-Reply-To: References: Message-ID: On 12/12/2015 4:48 PM, Pedro Vincenty wrote: > Hello, I'm wondering how to append a line from a file onto a list(easy part) provided that the line contains strings specific to a previous list I've already made(hard part). I have this right now, > for line in satellite_dataread: > if any(i in line for i in list2): > line= line.strip() > satellite, country= line.split(',') > satellite_origin_list.append(country) > > the statement if statement seems to work as I take it out of the for loop, but not as I have it presented. Thanks a bunch!! You question and example are incomplete. Read https://stackoverflow.com/help/mcve and follow it by adding in the missing definitions and printing the result. For example: satellite_origin_list = [] satellite_dataread = '''\ hooray, usa salud3, ussr panda 33, china '''.splitlines() list2 = ['ray', 'and'] for line in satellite_dataread: if any(i in line for i in list2): line= line.strip() satellite, country= line.split(',') satellite_origin_list.append(country) print(satellite_origin_list) # prints [' usa', ' china'] Now tell us what you think is wrong with this result, which is exactly what I expected. Note: you might want to unpack lines first and then test either satellete or country separately. -- Terry Jan Reedy From python at lucidity.plus.com Sat Dec 12 17:20:44 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 12 Dec 2015 22:20:44 +0000 Subject: appending a line to a list based off of a string found in a previous list In-Reply-To: References: Message-ID: <566C9DBC.7050108@lucidity.plus.com> Hi Pedro, It would be _really useful_ if you included code that could be pasted into an interpreter or file directly to show your problem. You are referencing several data sources ("satellite_dataread" and "list2") that we can only guess at. On 12/12/15 21:48, Pedro Vincenty wrote: > Hello, I'm wondering how to append a line from a file onto a > list(easy part) provided that the line contains strings specific to a > previous list I've already made(hard part). The following is a complete version of your example with some guessed-at data: """ satellite_dataread = ( "spam ham eggs,ctry0\n", "spam ham eggs foo,ctry1\n", "spam ham,ctry2\n", "spam bar ham eggs,ctry3\n", ) list2 = ['foo', 'bar'] satellite_origin_list = [] for line in satellite_dataread: if any(i in line for i in list2): line = line.strip() satellite, country= line.split(',') satellite_origin_list.append(country) print (satellite_origin_list) """ When I put that in a file and run it, I get: $ python foo.py ['ctry1', 'ctry3'] $ python3 foo.py ['ctry1', 'ctry3'] So, it seems to work as you describe already - what is it that I am missing? Please explain what you expect to see (or change the guessed-at input data to an example of what you actually have). E. From vincentypedro at gmail.com Sat Dec 12 17:39:39 2015 From: vincentypedro at gmail.com (Pedro Vincenty) Date: Sat, 12 Dec 2015 14:39:39 -0800 (PST) Subject: appending a line to a list based off of a string found in a previous list In-Reply-To: References: Message-ID: <575432ff-000b-493a-805d-3147d5ceb133@googlegroups.com> On Saturday, December 12, 2015 at 4:48:46 PM UTC-5, Pedro Vincenty wrote: > Hello, I'm wondering how to append a line from a file onto a list(easy part) provided that the line contains strings specific to a previous list I've already made(hard part). I have this right now, > for line in satellite_dataread: > if any(i in line for i in list2): > line= line.strip() > satellite, country= line.split(',') > satellite_origin_list.append(country) > > the statement if statement seems to work as I take it out of the for loop, but not as I have it presented. Thanks a bunch!! I was able to get it it you guys were right. Thanks a bunch! From rxjwg98 at gmail.com Sat Dec 12 18:01:54 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 12 Dec 2015 15:01:54 -0800 (PST) Subject: Why doesn't response pydoc on my Python 2.7? Message-ID: Hi, I want to use pydoc as some online tutorial shows, but it cannot run as below. What is wrong? Thanks, >>> import pydoc >>> pydoc >>> pydoc sys SyntaxError: invalid syntax >>> import sys >>> pydoc sys SyntaxError: invalid syntax >>> help(pydoc) Help on module pydoc: ...... From rxjwg98 at gmail.com Sat Dec 12 18:08:48 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 12 Dec 2015 15:08:48 -0800 (PST) Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: References: Message-ID: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> On Saturday, December 12, 2015 at 6:02:11 PM UTC-5, Robert wrote: > Hi, > > I want to use pydoc as some online tutorial shows, but it cannot run as > below. What is wrong? > > > Thanks, > > > > > >>> import pydoc > >>> pydoc > > >>> pydoc sys > SyntaxError: invalid syntax > >>> import sys > >>> pydoc sys > SyntaxError: invalid syntax > >>> help(pydoc) > Help on module pydoc: > ...... In fact, I wanted to run the following code. When it failed, I moved to the original question above. Anyone can help? Thanks, ////////// It also changes what pydoc will show: module1.py a = "A" b = "B" c = "C" module2.py __all__ = ['a', 'b'] a = "A" b = "B" c = "C" $ pydoc module1 From python at lucidity.plus.com Sat Dec 12 18:15:27 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 12 Dec 2015 23:15:27 +0000 Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: References: Message-ID: <566CAA8F.30003@lucidity.plus.com> Hi Robert, On 12/12/15 23:01, Robert wrote: > I want to use pydoc as some online tutorial shows, but it cannot run as > below. What is wrong? "some online tutorial"? >>>> import pydoc >>>> pydoc > Correct - in the interactive interpreter, typing the name of an object prints its value. You have imported a module and then typed its name. >>>> pydoc sys > SyntaxError: invalid syntax >>>> import sys >>>> pydoc sys > SyntaxError: invalid syntax In both of these, there is no operator after "pydoc", so what does it mean? >>>> help(pydoc) > Help on module pydoc: > ...... Instead of omitting the result of that, read it! FWIW, The relevant part based on what I _think_ you're trying to do (as you didn't include the URL of your "some online tutorial") is probably this part: """ DESCRIPTION In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: Run "pydoc " to show documentation on something. """ E. From ben+python at benfinney.id.au Sat Dec 12 18:18:01 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 13 Dec 2015 10:18:01 +1100 Subject: Why doesn't response pydoc on my Python 2.7? References: Message-ID: <85si3745p2.fsf@benfinney.id.au> Robert writes: > I want to use pydoc as some online tutorial shows Which online tutorial? Please give the URL to the page that instructs you to use ?pydoc? in that manner. > >>> import pydoc Allows you to use, in Python code, the ?pydoc? module by name. > >>> pydoc > Accesses the ?pydoc? name. Because this is the interactive Python shell, it displays the result of that access: a module object. > >>> pydoc sys > SyntaxError: invalid syntax > >>> import sys > >>> pydoc sys > SyntaxError: invalid syntax Yes, using two names in a row like that is invalid Python syntax. > >>> help(pydoc) > Help on module pydoc: > ...... Gives help from the module object you access through the name ?pydoc?. I suspect the tutorial instructs you to invoke the ?pydoc? *command* on your operating system, not use it within Python. But I can only guess, until you show us which page from which tutorial you're referring to. -- \ ?Technology is neither good nor bad; nor is it neutral.? | `\ ?Melvin Kranzberg's First Law of Technology | _o__) | Ben Finney From python at lucidity.plus.com Sat Dec 12 18:21:02 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 12 Dec 2015 23:21:02 +0000 Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> Message-ID: <566CABDE.6040206@lucidity.plus.com> On 12/12/15 23:08, Robert wrote: > In fact, I wanted to run the following code. When it failed, I moved to > the original question above. How did it fail? Tell us what _did_ happen. It works fine for me: $ pydoc module1 Help on module module1: NAME module1 FILE /tmp/robert/module1.py DATA a = 'A' b = 'B' c = 'C' $ pydoc module2 Help on module module2: NAME module2 FILE /tmp/robert/module2.py DATA __all__ = ['a', 'b'] a = 'A' b = 'B' E. From rxjwg98 at gmail.com Sat Dec 12 19:04:39 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 12 Dec 2015 16:04:39 -0800 (PST) Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> Message-ID: <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> On Saturday, December 12, 2015 at 6:24:25 PM UTC-5, Erik wrote: > On 12/12/15 23:08, Robert wrote: > > In fact, I wanted to run the following code. When it failed, I moved to > > the original question above. > > How did it fail? Tell us what _did_ happen. > > It works fine for me: > > $ pydoc module1 > Help on module module1: > > NAME > module1 > > FILE > /tmp/robert/module1.py > > DATA > a = 'A' > b = 'B' > c = 'C' > > > $ pydoc module2 > Help on module module2: > > NAME > module2 > > FILE > /tmp/robert/module2.py > > DATA > __all__ = ['a', 'b'] > a = 'A' > b = 'B' > > E. Excuse me for the incomplete information on previous posts. Here is the message when I run it on Canopy (module1.py and module2.py are in the current folder): Welcome to Canopy's interactive data-analysis environment! with pylab-backend set to: qt Type '?' for more information. In [1]: pydoc module1 File "", line 1 pydoc module1 ^ SyntaxError: invalid syntax In [2]: The above code snippet is from here: http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python Thanks again. From python at lucidity.plus.com Sat Dec 12 19:17:55 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 13 Dec 2015 00:17:55 +0000 Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> Message-ID: <566CB933.4010409@lucidity.plus.com> Hi Robert, On 13/12/15 00:04, Robert wrote: > Excuse me for the incomplete information on previous posts. > Here is the message when I run it on Canopy (module1.py and module2.py > are in the current folder): > > Welcome to Canopy's interactive data-analysis environment! > with pylab-backend set to: qt > Type '?' for more information. I don't have any experience with "Canopy", but it looks to me like it is providing you with an interactive Python environment. > In [1]: pydoc module1 > File "", line 1 > pydoc module1 > ^ > SyntaxError: invalid syntax As this is an interactive Python environment, then Python syntax is required. Remember what "help(pydoc)" told you: """ In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. """ So, instead of "pydoc module1" (which is not good Python syntax), do what the help document tells you to do within a Python interpreter: import module1 pydoc.help(module1) import module2 pydoc.help(module2) Does that work better? E. From rxjwg98 at gmail.com Sat Dec 12 19:19:26 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 12 Dec 2015 16:19:26 -0800 (PST) Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> Message-ID: <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> On Saturday, December 12, 2015 at 7:05:39 PM UTC-5, Robert wrote: > On Saturday, December 12, 2015 at 6:24:25 PM UTC-5, Erik wrote: > > On 12/12/15 23:08, Robert wrote: > > > In fact, I wanted to run the following code. When it failed, I moved to > > > the original question above. > > > > How did it fail? Tell us what _did_ happen. > > > > It works fine for me: > > > > $ pydoc module1 > > Help on module module1: > > > > NAME > > module1 > > > > FILE > > /tmp/robert/module1.py > > > > DATA > > a = 'A' > > b = 'B' > > c = 'C' > > > > > > $ pydoc module2 > > Help on module module2: > > > > NAME > > module2 > > > > FILE > > /tmp/robert/module2.py > > > > DATA > > __all__ = ['a', 'b'] > > a = 'A' > > b = 'B' > > > > E. > > Excuse me for the incomplete information on previous posts. > Here is the message when I run it on Canopy (module1.py and module2.py > are in the current folder): > > Welcome to Canopy's interactive data-analysis environment! > with pylab-backend set to: qt > Type '?' for more information. > > In [1]: pydoc module1 > File "", line 1 > pydoc module1 > ^ > SyntaxError: invalid syntax > > > In [2]: > > > The above code snippet is from here: > http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python > > Thanks again. Hi, It turns out that Enthought does not allow pydoc as the link said: http://stackoverflow.com/questions/12063718/using-help-and-pydoc-to-list-python-modules-not-working Thanks, From python at lucidity.plus.com Sat Dec 12 19:31:12 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 13 Dec 2015 00:31:12 +0000 Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> Message-ID: <566CBC50.40807@lucidity.plus.com> On 13/12/15 00:19, Robert wrote: > It turns out that Enthought does not allow pydoc as the link said: > http://stackoverflow.com/questions/12063718/using-help-and-pydoc-to-list-python-modules-not-working I don't think that's what the article is telling you. Try what I said in my previous message. Other than that, I think I'm probably out of ideas on this one ... E. From __peter__ at web.de Sat Dec 12 19:35:44 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Dec 2015 01:35:44 +0100 Subject: Why doesn't response pydoc on my Python 2.7? References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> Message-ID: Robert wrote: > On Saturday, December 12, 2015 at 7:05:39 PM UTC-5, Robert wrote: >> On Saturday, December 12, 2015 at 6:24:25 PM UTC-5, Erik wrote: >> > On 12/12/15 23:08, Robert wrote: >> > > In fact, I wanted to run the following code. When it failed, I moved >> > > to the original question above. >> > >> > How did it fail? Tell us what _did_ happen. >> > >> > It works fine for me: >> > >> > $ pydoc module1 >> > Help on module module1: >> > >> > NAME >> > module1 >> > >> > FILE >> > /tmp/robert/module1.py >> > >> > DATA >> > a = 'A' >> > b = 'B' >> > c = 'C' >> > >> > >> > $ pydoc module2 >> > Help on module module2: >> > >> > NAME >> > module2 >> > >> > FILE >> > /tmp/robert/module2.py >> > >> > DATA >> > __all__ = ['a', 'b'] >> > a = 'A' >> > b = 'B' >> > >> > E. >> >> Excuse me for the incomplete information on previous posts. >> Here is the message when I run it on Canopy (module1.py and module2.py >> are in the current folder): >> >> Welcome to Canopy's interactive data-analysis environment! >> with pylab-backend set to: qt >> Type '?' for more information. >> >> In [1]: pydoc module1 >> File "", line 1 >> pydoc module1 >> ^ >> SyntaxError: invalid syntax >> >> >> In [2]: >> >> >> The above code snippet is from here: >> http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python >> >> Thanks again. > > Hi, > It turns out that Enthought does not allow pydoc as the link said: > http://stackoverflow.com/questions/12063718/using-help-and-pydoc-to-list-python-modules-not-working This is completely unrelated. >>> help("modules") for the specific string "modules" triggers a scan for all available modules. For other strings like "module1" that represent a module name >>> help("module1") should work unless >>> import module1 fails, too. From lac at openend.se Sat Dec 12 19:47:16 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 13 Dec 2015 01:47:16 +0100 Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: References: Message-ID: <201512130047.tBD0lGwL018918@fido.openend.se> In a message of Sat, 12 Dec 2015 15:01:54 -0800, Robert writes: >Hi, > >I want to use pydoc as some online tutorial shows, but it cannot run as >below. What is wrong? > > >Thanks, > > > > >>>> import pydoc >>>> pydoc > >>>> pydoc sys >SyntaxError: invalid syntax >>>> import sys >>>> pydoc sys >SyntaxError: invalid syntax >>>> help(pydoc) >Help on module pydoc: >...... >-- >https://mail.python.org/mailman/listinfo/python-list You aren't supposed to type pydoc sys from __inside__ your python command interpreter. You type this at a command prompt. Laura From rxjwg98 at gmail.com Sat Dec 12 21:31:02 2015 From: rxjwg98 at gmail.com (Robert) Date: Sat, 12 Dec 2015 18:31:02 -0800 (PST) Subject: Why doesn't response pydoc on my Python 2.7? In-Reply-To: References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> Message-ID: On Saturday, December 12, 2015 at 7:36:21 PM UTC-5, Peter Otten wrote: > Robert wrote: > > > On Saturday, December 12, 2015 at 7:05:39 PM UTC-5, Robert wrote: > >> On Saturday, December 12, 2015 at 6:24:25 PM UTC-5, Erik wrote: > >> > On 12/12/15 23:08, Robert wrote: > >> > > In fact, I wanted to run the following code. When it failed, I moved > >> > > to the original question above. > >> > > >> > How did it fail? Tell us what _did_ happen. > >> > > >> > It works fine for me: > >> > > >> > $ pydoc module1 > >> > Help on module module1: > >> > > >> > NAME > >> > module1 > >> > > >> > FILE > >> > /tmp/robert/module1.py > >> > > >> > DATA > >> > a = 'A' > >> > b = 'B' > >> > c = 'C' > >> > > >> > > >> > $ pydoc module2 > >> > Help on module module2: > >> > > >> > NAME > >> > module2 > >> > > >> > FILE > >> > /tmp/robert/module2.py > >> > > >> > DATA > >> > __all__ = ['a', 'b'] > >> > a = 'A' > >> > b = 'B' > >> > > >> > E. > >> > >> Excuse me for the incomplete information on previous posts. > >> Here is the message when I run it on Canopy (module1.py and module2.py > >> are in the current folder): > >> > >> Welcome to Canopy's interactive data-analysis environment! > >> with pylab-backend set to: qt > >> Type '?' for more information. > >> > >> In [1]: pydoc module1 > >> File "", line 1 > >> pydoc module1 > >> ^ > >> SyntaxError: invalid syntax > >> > >> > >> In [2]: > >> > >> > >> The above code snippet is from here: > >> http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python > >> > >> Thanks again. > > > > Hi, > > It turns out that Enthought does not allow pydoc as the link said: > > http://stackoverflow.com/questions/12063718/using-help-and-pydoc-to-list-python-modules-not-working > > This is completely unrelated. > > >>> help("modules") > > for the specific string "modules" triggers a scan for all available modules. > For other strings like "module1" that represent a module name > > >>> help("module1") > > should work unless > > >>> import module1 > > fails, too. Thanks Peter and others. It previously may not be at the right directory. After that, import pydoc, it works. Great thanks with the following command. pydoc.help('module1') Help on module module1: NAME module1 FILE c:\users\rj\pyprj\module1.py DATA a = 'A' b = 'B' c = 'C' From steve at pearwood.info Sat Dec 12 22:42:55 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 Dec 2015 14:42:55 +1100 Subject: Why doesn't response pydoc on my Python 2.7? References: <045e0006-feb0-4620-9911-c6d231662566@googlegroups.com> <2c78ed2d-c3ee-473c-8093-99efc62c6766@googlegroups.com> <280c8342-1a4a-413c-9c86-4ea29439ea24@googlegroups.com> Message-ID: <566ce941$0$1599$c3e8da3$5496439d@news.astraweb.com> On Sun, 13 Dec 2015 01:31 pm, Robert wrote: > pydoc.help('module1') > Help on module module1: You don't need to do all that. help() has been a built-in command for Python for, oh, probably a decade or more. Technically, it is added to the built-ins on startup, so if you mess about with the site.py script or disable it, it won't be available. But by default, help() should always be available at the interactive prompt. Enter this at the interactive Python prompt (by default you will see >>> as the prompt): help('sys') and you will see help for the built-in module sys. The only time you need to import pydoc is if you wish to use it programmatically. You don't need it just to view help. Alternative, at your operating system's command prompt (terminal, shell, DOS prompt, command line, etc), you may be able to call pydoc as if it were a program. The shell will probably have a dollar sign $ as the prompt. Enter this: pydoc sys and you will see the help for the sys module. But beware that since you are using the shell, not python, the syntax rules are different. For example: Inside Python, [] means an empty list, and you can say help([]) to see help about lists; but in the system shell, [] is a globbing pattern, and the result you get will be somewhat different (and platform-dependent). If the command "pydoc" doesn't work at your shell (remember: the shell has the $ prompt, Python has the >>> prompt) you can try something like this instead: python -m pydoc sys And last but not least, try calling pydoc without any arguments to see some extra options. -- Steven From frank at chagford.com Sun Dec 13 00:00:26 2015 From: frank at chagford.com (Frank Millman) Date: Sun, 13 Dec 2015 07:00:26 +0200 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: "Frank Millman" wrote in message news:n4gigr$f51$1 at ger.gmane.org... > I have found a workaround for my problem, but first I needed to understand > what was going on more clearly. This is what I have figured out. > [...] > > The reason for the '#' in the above function is that sqlite3 passes the > current value of 'balance' into my function, and it has a bad habit of > trying to second-guess the data-type to use. Even though I store it as a > string, it passes in an integer or float. Prefixing it with a '#' forces > it to remain as a string. Well that theory did not last very long! As soon as I applied this to my live app, I found that I am using the database to perform arithmetic all over the place - calculating tax, exchange rates, etc. I always round the result once it arrives from the database, so there was no rounding problem. With the prefix of '#' the calculations all just crash, and return null values. My new solution is to pass a 'scale' factor into my aggregate function. The function uses the Decimal quantize method to round the result before returning. So far it seems to be working. Frank From rosuav at gmail.com Sun Dec 13 00:04:38 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 13 Dec 2015 16:04:38 +1100 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: On Sun, Dec 13, 2015 at 4:00 PM, Frank Millman wrote: > My new solution is to pass a 'scale' factor into my aggregate function. The > function uses the Decimal quantize method to round the result before > returning. So far it seems to be working. So, effectively, you're using fixed point arithmetic. As long as you're restricting yourself to adding values together, that's easy; be careful of multiplying by tax percentages, as you might flick to float. Really, you'd do a lot better to move to PostgreSQL. ChrisA From frank at chagford.com Sun Dec 13 00:44:48 2015 From: frank at chagford.com (Frank Millman) Date: Sun, 13 Dec 2015 07:44:48 +0200 Subject: Problem with sqlite3 and Decimal In-Reply-To: References: Message-ID: "Chris Angelico" wrote in message news:CAPTjJmrfw-qNx-a=3Q2qJ244FGVxz3MPe4WA-WDUsmchXUfZbA at mail.gmail.com... > > On Sun, Dec 13, 2015 at 4:00 PM, Frank Millman wrote: > > My new solution is to pass a 'scale' factor into my aggregate function. > > The > > function uses the Decimal quantize method to round the result before > > returning. So far it seems to be working. > > So, effectively, you're using fixed point arithmetic. As long as > you're restricting yourself to adding values together, that's easy; be > careful of multiplying by tax percentages, as you might flick to > float. > > Really, you'd do a lot better to move to PostgreSQL. Thanks for the warning, but I think I am safe. There is only one exceptional case where I use my 'aggregate' function. It is a substitute for the following SQL statement - UPDATE table SET balance = balance + ? WHERE date > ? Normally it works fine. However, I wanted to populate my database with some real-world values, so I wrote a program to generate a few thousand transactions, and that triggered the rounding errors that caused me to start this thread. I have replaced the statement with - UPDATE table SET balance = aggregate(balance, ?, ?) WHERE date > ? This prevents rounding errors from creeping in. In all other cases, I use unadorned SQL to calculate a scalar value, which I round to the appropriate scaling factor before storing the result. Regarding PostgreSQL, I have mentioned before that I offer my users a choice of 3 databases - PostgreSQL, Sql Server, and sqlite3 - so I have to make sure that my app works with all of them. I agree that for serious database work one should use PostgreSQL or Sql Server. But I think that sqlite3 is perfect for demos and for one-man businesses. It is fast, lightweight, and very 'standards compliant'. It does have some quirks, but these are clearly documented and the mailing list is very responsive. Frank From darcy at VybeNetworks.com Sun Dec 13 01:35:45 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sun, 13 Dec 2015 01:35:45 -0500 Subject: codecs.StreamRecoder not doing what I expected. In-Reply-To: References: <20151212140113.78e3c945@imp> Message-ID: <20151213013545.5a57388b@imp> On Sat, 12 Dec 2015 21:35:36 +0100 Peter Otten <__peter__ at web.de> wrote: > def read_file(filename): > for encoding in ["utf-8", "iso-8859-1"]: > try: > with open(filename, encoding=encoding) as f: > return f.read() > except UnicodeDecodeError: > pass > raise AssertionError("unreachable") I replaced this in my test and it works. However, I still have a problem with my actual code. The point of this code was that I expect all the files that I am reading to be either ASCII, UTF-8 or LATIN-1 and I want to normalize my input. My problem may actually be elsewhere. My application is a web page of my wife's recipes. She has hundreds of files with a recipe in each one. Often she simply typed them in but sometimes she cuts and pastes from another source and gets non-ASCII characters. So far they seem to fit in the three categories above. I added test prints to sys.stderr so that I can see what is happening. In one particular case I have this "73 61 75 74 c3 a9" in the file. When I open the file with "open(filename, "r", encoding="utf-8").read()" I get what appears to be a latin-1 string. I print it to stderr and view it in the web log. The above string prints as "saut\xe9". The last is four actual characters in the file. When I try to print it to the web page it fails because the \xe9 character is not valid ASCII. However, my default encoding is utf-8. Other web pages on the same server display fine. I have the following in the Apache config by the way. SetEnv PYTHONIOENCODING utf8 So, my file is utf-8, I am reading it as utf-8, my Apache server output is set to utf-8. How is ASCII sneaking in? -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From __peter__ at web.de Sun Dec 13 05:23:03 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Dec 2015 11:23:03 +0100 Subject: codecs.StreamRecoder not doing what I expected. References: <20151212140113.78e3c945@imp> <20151213013545.5a57388b@imp> Message-ID: D'Arcy J.M. Cain wrote: > On Sat, 12 Dec 2015 21:35:36 +0100 > Peter Otten <__peter__ at web.de> wrote: >> def read_file(filename): >> for encoding in ["utf-8", "iso-8859-1"]: >> try: >> with open(filename, encoding=encoding) as f: >> return f.read() >> except UnicodeDecodeError: >> pass >> raise AssertionError("unreachable") > > I replaced this in my test and it works. However, I still have a > problem with my actual code. The point of this code was that I expect > all the files that I am reading to be either ASCII, UTF-8 or LATIN-1 > and I want to normalize my input. My problem may actually be elsewhere. > > My application is a web page of my wife's recipes. She has hundreds of > files with a recipe in each one. Often she simply typed them in but > sometimes she cuts and pastes from another source and gets non-ASCII > characters. So far they seem to fit in the three categories above. > > I added test prints to sys.stderr so that I can see what is happening. > In one particular case I have this "73 61 75 74 c3 a9" in the file. > When I open the file with > "open(filename, "r", encoding="utf-8").read()" I get what appears to be > a latin-1 string. No, you get unicode. The escape code for the 'LATIN SMALL LETTER E WITH ACUTE' codepoint just happens to be the same as its latin-1 value: >>> print(ascii("?")) '\xe9' >>> print("?".encode("latin1")) b'\xe9' > I print it to stderr and view it in the web log. > The above string prints as "saut\xe9". The last is four actual > characters in the file. > > When I try to print it to the web page it fails because the \xe9 > character is not valid ASCII. Can you give some code that reproduces the error? What is the traceback? > However, my default encoding is utf-8. That doesn't matter. sys.stout.encoding/sys.stderr.encoding are relevant. > Other web pages on the same server display fine. > > I have the following in the Apache config by the way. > > SetEnv PYTHONIOENCODING utf8 > > So, my file is utf-8, I am reading it as utf-8, my Apache server output > is set to utf-8. How is ASCII sneaking in? I don't know. Have you verified that python "sees" the setting, e. g. with import os import sys ioencoding = os.environ.get("PYTHONIOENCODING") assert ioencoding == "utf8" assert sys.stdout.encoding == ioencoding assert sys.stderr.endoding == ioencoding Have you tried setting LANG as Oscar suggested in the other thread? From dieter at handshake.de Sun Dec 13 06:34:34 2015 From: dieter at handshake.de (dieter) Date: Sun, 13 Dec 2015 12:34:34 +0100 Subject: XMPP pub sub setup and working References: <2745ea24-d06f-41e9-99a7-1516b3a2bbc3@googlegroups.com> Message-ID: <871taqlgz9.fsf@handshake.de> satish at driveu.in writes: > I am using xmpppy python library to connect with XMPP server(ejabberd2) but unable to connect and actually don't have clarity on how to connect, authenticate and send a message to the server. > If possible please provide some code snippet using XMPPPY. > > This is what I have tried: > > In [1]: from xmpp import Client > > In [2]: cl = Client(server='176.9.18.111', 5280) > > File "", line 1 > > cl = Client(server='176.9.18.111', 5280) > > SyntaxError: non-keyword arg after keyword arg A wrong call of the "Client" class: If you pass a parameter value in the form "=" (which you do for "server"), this is called a "keyword arg[ument]". If you pass it in the form "", this is called a "positional" or "non keyword arg[ument]". The error message tells you that you must not pass a positional argument after a keyword argument (what you do above). Likely, you can use "Client('176.9.18.111', 5280)" or "Client(server='176.9.18.111', port=5280)". Both should get rid of the "SyntaxError" - but, of course, you still have the issue with authentication. Have a look at the so called "signature" of "Client". The "signature" of a callable (usually function, method or class) tells you what parameters are available and what names (and potentially default values) they have. You might find in the signature for "Client" parameters which hint towards authentication (e.g. "user" and "password"). If so, pass values identifying yourself. I heavily use Python's builtin "help" function: "help(obj)" provides documentation for object "obj". Thus, "help(Client)" will display information about "Client". If it is indeed a class (which I assume), then the documentation will (among others) list the methods. The signature for "Client" is in this case, the signature of its "__init__" method (without the initial "self"). > In [3]: cl = Client(server='176.9.18.111', port =5280) > Invalid debugflag given: always > Invalid debugflag given: nodebuilder > DEBUG: > DEBUG: Debug created for /Users/gathole/.virtualenvs/driveu/lib/python2.7/site-packages/xmpp/client.py > DEBUG: flags defined: always,nodebuilder The output above is a bit strange - are you sure, you did not have requested debugging in some way (not shown above)? > In [4]: cl.connect() > ... > DEBUG: socket sent > > DEBUG: socket error Socket error while receiving data > DEBUG: client stop Disconnect detected Apparently, the server was not satisfied with the connection proceedure and has closed the communication stream. Check available documentation for the server you try to connect about the connection requirements. If there is no such documentation, you might try to contact the server administrator to find out the relevant details. From lac at openend.se Sun Dec 13 07:17:24 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 13 Dec 2015 13:17:24 +0100 Subject: codecs.StreamRecoder not doing what I expected. In-Reply-To: <20151213013545.5a57388b@imp> References: <20151212140113.78e3c945@imp> <20151213013545.5a57388b@imp> Message-ID: <201512131217.tBDCHOO0027527@fido.openend.se> In a message of Sun, 13 Dec 2015 01:35:45 -0500, "D'Arcy J.M. Cain" writes: >When I try to print it to the web page it fails because the \xe9 >character is not valid ASCII. However, my default encoding is utf-8. >Other web pages on the same server display fine. > >I have the following in the Apache config by the way. > >SetEnv PYTHONIOENCODING utf8 > >So, my file is utf-8, I am reading it as utf-8, my Apache server output >is set to utf-8. How is ASCII sneaking in? What is your sys.stdout.encoding ? just import sys and print the thing. I think you will find that it is not what you expect. Laura From eshikafe at gmail.com Sun Dec 13 09:14:03 2015 From: eshikafe at gmail.com (austin aigbe) Date: Sun, 13 Dec 2015 06:14:03 -0800 (PST) Subject: Python IO Redirection to Console Message-ID: <36dcb7f1-53a1-42a1-b0de-94b919decb42@googlegroups.com> Hello, I am trying to redirect the IO (stdout, stdin and stderr) to the console. Is there a Python module for this? Thanks. Regards From ganesh1pal at gmail.com Sun Dec 13 12:26:31 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Sun, 13 Dec 2015 22:56:31 +0530 Subject: Calling a list of functions Message-ID: Hi Team, Iam on linux and python 2.7 . I have a bunch of functions which I have run sequentially . I have put them in a list and Iam calling the functions in the list as shown below , this works fine for me , please share your opinion/views on the same Sample code : def print1(): print "one" def print2(): print "two" def print3(): print "three" print_test = [print1(),print2(),print3()] //calling the function for test in range(len(print_test)): try: print_test[test] except AssertionError as exc: Regards, Ganesh From bc at freeuk.com Sun Dec 13 12:38:13 2015 From: bc at freeuk.com (BartC) Date: Sun, 13 Dec 2015 17:38:13 +0000 Subject: Calling a list of functions In-Reply-To: References: Message-ID: On 13/12/2015 17:26, Ganesh Pal wrote: > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , please share your > opinion/views on the same > > > Sample code : > > def print1(): > print "one" > > def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function > > for test in range(len(print_test)): > try: > print_test[test] > except AssertionError as exc: > > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , please share your That's not quite what the code does, which is to call the three functions and put their results into the list (3 Nones I think). Then you evaluate each element of the list (a None each time). I had to modify it to the following, which sets up a list of the three functions, then calls them in turn using the loop. I don't know what the 'except' part was supposed to do: def print1(): print "one" def print2(): print "two" def print3(): print "three" print_test = [print1,print2,print3] #NOT calling the function for test in range(len(print_test)): try: print_test[test]() #calling the function except AssertionError: pass The output of the two programs would have been the same I think. -- Bartc From __peter__ at web.de Sun Dec 13 12:40:28 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Dec 2015 18:40:28 +0100 Subject: Calling a list of functions References: Message-ID: Ganesh Pal wrote: > Hi Team, > > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , please share your > opinion/views on the same > > > Sample code : > > def print1(): > print "one" > > def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function Python is not C++. In Python // is the integer division operator. > for test in range(len(print_test)): > try: > print_test[test] > except AssertionError as exc: 1 Why range()? Iterate directly over the list: for result in print_test: print result 2 Why the try...except? If there are functions in your actual code that may raise an AssertionError you won't catch it in the loop because you already invoked the functions when you built the list literal. To catch an exception like that you have to put the functions into the list, not the results: functions = [print1, print2, print3] for func in functions: try: print func() except AssertionError: pass From invalid at invalid.invalid Sun Dec 13 12:41:27 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 13 Dec 2015 17:41:27 +0000 (UTC) Subject: Calling a list of functions References: Message-ID: On 2015-12-13, Ganesh Pal wrote: > Hi Team, > > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . I have put them in a list and Iam calling the > functions in the list as shown below , this works fine for me , > please share your opinion/views on the same > > Sample code : > > def print1(): > print "one" > > def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function > > for test in range(len(print_test)): > try: > print_test[test] > except AssertionError as exc: I have no clue what your actual goal is, but it might be better to do the function call in the try/except block inside the loop. Otherwise your try/except block makes no sense because there's nothing being executed inside it: for test in [print1,print2,print3]: try: test() except AssertionError as exc: print exc From ian.g.kelly at gmail.com Sun Dec 13 12:43:54 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 13 Dec 2015 10:43:54 -0700 Subject: Calling a list of functions In-Reply-To: References: Message-ID: On Sun, Dec 13, 2015 at 10:26 AM, Ganesh Pal wrote: > Hi Team, > > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , please share your > opinion/views on the same > > > Sample code : > > def print1(): > print "one" > > def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function If I understand correctly, you want to build the list of functions and then call them later. If so, this is not quite correct. This is calling the functions at the time that you build the list and placing the return values in the list, not the functions. To build a list of the functions themselves, do: print_test = [print1, print2, print3] > for test in range(len(print_test)): Iterating over range(len(something)) is usually not correct. Just iterate over print_test instead. If you really need the indexes, then iterate over enumerate(print_test). > try: > print_test[test] > except AssertionError as exc: It looks like some code got cut off here since your exception handler has no body. Regardless, the exception handler will never be invoked because print_test[test] is just looking up the results of the functions that were called when building the list. To actually call the functions here instead of above, do: for test in print_test: test() From darcy at VybeNetworks.com Sun Dec 13 13:14:12 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Sun, 13 Dec 2015 13:14:12 -0500 Subject: codecs.StreamRecoder not doing what I expected. In-Reply-To: <201512131217.tBDCHOO0027527@fido.openend.se> References: <20151212140113.78e3c945@imp> <20151213013545.5a57388b@imp> <201512131217.tBDCHOO0027527@fido.openend.se> Message-ID: <20151213131412.310b2336@imp> On Sun, 13 Dec 2015 13:17:24 +0100 Laura Creighton wrote: > In a message of Sun, 13 Dec 2015 01:35:45 -0500, "D'Arcy J.M. Cain" > writes: > >When I try to print it to the web page it fails because the \xe9 > >character is not valid ASCII. However, my default encoding is utf-8. > >Other web pages on the same server display fine. > > > >I have the following in the Apache config by the way. > > > >SetEnv PYTHONIOENCODING utf8 > > > >So, my file is utf-8, I am reading it as utf-8, my Apache server > >output is set to utf-8. How is ASCII sneaking in? > > What is your sys.stdout.encoding ? > > just import sys and print the thing. > > I think you will find that it is not what you expect. > > Laura > >>> print(sys.stdout.encoding) utf8 That's what I was expecting. However when I add that to my web log output I get this: get_recipe() PYTHONIOENCODING: None get_recipe() encoding: 646 Dang! I was sure that I fixed that. I have this in my Apache configuration: SetEnv PYTHONIOENCODING utf8 I guess I have an Apache problem now, not a Python one. The strange thing is that this was a fix for a similar problem I asked about and it worked. Isn't there some way that I can just set the default encoding to utf8 for every Python program? Googling suggests that I can't do that but that doesn't see right. Since utf8 includes ASCII why wouldn't it be the default anyway? -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From tjreedy at udel.edu Sun Dec 13 14:13:04 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Dec 2015 14:13:04 -0500 Subject: Python IO Redirection to Console In-Reply-To: <36dcb7f1-53a1-42a1-b0de-94b919decb42@googlegroups.com> References: <36dcb7f1-53a1-42a1-b0de-94b919decb42@googlegroups.com> Message-ID: On 12/13/2015 9:14 AM, austin aigbe wrote: > I am trying to redirect the IO (stdout, stdin and stderr) to the console. For a program run from the console, console IO is the default. One must explicitly redirect to a file stream or pipe. At least on Windows, console IO is also the default for a program run with subprocess. Again, anything else must explicitly given. > Is there a Python module for this? Unless I have completely misunderstood the question, not needed. -- Terry Jan Reedy From high5storage at gmail.com Sun Dec 13 14:45:19 2015 From: high5storage at gmail.com (high5storage at gmail.com) Date: Sun, 13 Dec 2015 11:45:19 -0800 (PST) Subject: Weird list conversion Message-ID: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> Hi all, f = open("stairs.bin", "rb") data = list(f.read(16)) print data returns ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? As always, thanks for any help! From lac at openend.se Sun Dec 13 14:57:34 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 13 Dec 2015 20:57:34 +0100 Subject: Weird list conversion In-Reply-To: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> Message-ID: <201512131957.tBDJvYc6000927@fido.openend.se> In a message of Sun, 13 Dec 2015 11:45:19 -0800, high5storage at gmail.com writes: >Hi all, > > f = open("stairs.bin", "rb") > data = list(f.read(16)) > print data > >returns > >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] > >The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? > >As always, thanks for any help! 0x3d is the ascii code for '=' From ian.g.kelly at gmail.com Sun Dec 13 14:59:25 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 13 Dec 2015 12:59:25 -0700 Subject: Weird list conversion In-Reply-To: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> Message-ID: On Sun, Dec 13, 2015 at 12:45 PM, wrote: > Hi all, > > f = open("stairs.bin", "rb") > data = list(f.read(16)) > print data > > returns > > ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] > > The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? They're equivalent representations of the same thing. py> '\x3D' '=' From kai.peters at gmail.com Sun Dec 13 15:05:22 2015 From: kai.peters at gmail.com (KP) Date: Sun, 13 Dec 2015 12:05:22 -0800 (PST) Subject: Weird list conversion In-Reply-To: References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> Message-ID: <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton wrote: > In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes: > >Hi all, > > > > f = open("stairs.bin", "rb") > > data = list(f.read(16)) > > print data > > > >returns > > > >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] > > > >The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? > > > >As always, thanks for any help! > > 0x3d is the ascii code for '=' I am aware of that - so is the rule that non-printables are returned in hex notation whereas printables come in their ASCII representation? From python at lucidity.plus.com Sun Dec 13 15:28:16 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 13 Dec 2015 20:28:16 +0000 Subject: Weird list conversion In-Reply-To: <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> Message-ID: <566DD4E0.50804@lucidity.plus.com> On 13/12/15 20:05, KP wrote: > On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton wrote: >> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes: >>> Hi all, >>> >>> f = open("stairs.bin", "rb") data = list(f.read(16)) print data >>> >>> returns >>> >>> ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', >>> '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] >>> >>> The first byte of the file is 0x3D according to my hex editor, so >>> why does Python return '=' and not '\x3D'? >>> >>> As always, thanks for any help! >> >> 0x3d is the ascii code for '=' > > I am aware of that - so is the rule that non-printables are returned > in hex notation whereas printables come in their ASCII > representation? No, what is _returned_ is a list of one-byte strings. When you call "print", then the list class's __repr__() method is called which in turn calls the contained objects' __repr__() methods in turn - it is those methods (in this case, they are all the string class's) which is deciding to render ASCII printable characters as just their value and ASCII non-printable characters using their hex notation. E. From ian.g.kelly at gmail.com Sun Dec 13 15:28:40 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 13 Dec 2015 13:28:40 -0700 Subject: Weird list conversion In-Reply-To: <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> Message-ID: On Sun, Dec 13, 2015 at 1:05 PM, KP wrote: > On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton wrote: >> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes: >> >Hi all, >> > >> > f = open("stairs.bin", "rb") >> > data = list(f.read(16)) >> > print data >> > >> >returns >> > >> >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] >> > >> >The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? >> > >> >As always, thanks for any help! >> >> 0x3d is the ascii code for '=' > > I am aware of that - so is the rule that non-printables are returned in hex notation whereas printables come in their ASCII representation? What you're seeing there is the repr() of the string. The rule is that it should be a printable representation that can be passed to eval to reconstruct the string. The printable requirement means that NUL should always come out escaped as '\x00' or perhaps '\0', but for printable bytes escaping isn't necessary. I don't know if there's a requirement that the repr of '\x3D' be '=', but it's probably the most generally useful and I doubt that any implementation would depart from that. If you specifically want hex representations, then you could use hex(ord(foo)). py> hex(ord('=')) '0x3d' From python at lucidity.plus.com Sun Dec 13 15:31:32 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 13 Dec 2015 20:31:32 +0000 Subject: Weird list conversion In-Reply-To: <566DD4E0.50804@lucidity.plus.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> <566DD4E0.50804@lucidity.plus.com> Message-ID: <566DD5A4.9040905@lucidity.plus.com> On 13/12/15 20:28, Erik wrote: > When you call "print", then the list class's __repr__() method is called > which in turn calls the contained objects' __repr__() methods in turn I mean the __str__() method, not __repr__() in this case - however, the answer is otherwise the same. E. From orgnut at yahoo.com Sun Dec 13 15:42:36 2015 From: orgnut at yahoo.com (Larry Hudson) Date: Sun, 13 Dec 2015 12:42:36 -0800 Subject: Weird list conversion In-Reply-To: <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> Message-ID: On 12/13/2015 12:05 PM, KP wrote: > On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton wrote: >> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes: >>> Hi all, >>> >>> f = open("stairs.bin", "rb") >>> data = list(f.read(16)) >>> print data >>> >>> returns >>> >>> ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'] >>> >>> The first byte of the file is 0x3D according to my hex editor, so why does Python return '=' and not '\x3D'? >>> >>> As always, thanks for any help! >> >> 0x3d is the ascii code for '=' > > I am aware of that - so is the rule that non-printables are returned in hex notation whereas printables come in their ASCII representation? > No. The data is returned as raw bytes. It's the print that is responsible for the way these bytes are _displayed_. -=- Larry -=- From rosuav at gmail.com Sun Dec 13 16:09:45 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Dec 2015 08:09:45 +1100 Subject: Weird list conversion In-Reply-To: <566DD5A4.9040905@lucidity.plus.com> References: <5926ced0-5b86-41f2-81e8-55cc6f71b78c@googlegroups.com> <3193bf38-82c3-4538-b500-5e23158898e6@googlegroups.com> <566DD4E0.50804@lucidity.plus.com> <566DD5A4.9040905@lucidity.plus.com> Message-ID: On Mon, Dec 14, 2015 at 7:31 AM, Erik wrote: > On 13/12/15 20:28, Erik wrote: >> >> When you call "print", then the list class's __repr__() method is called >> which in turn calls the contained objects' __repr__() methods in turn > > > I mean the __str__() method, not __repr__() in this case - however, the > answer is otherwise the same. It actually makes no difference; lists don't have __str__, and fall back on object.__str__, which returns self.__repr__(). Inside list.__repr__, the contained objects' reprs are combined. With lists, you always get the repr. :) ChrisA From ned at nedbatchelder.com Sun Dec 13 16:10:03 2015 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 13 Dec 2015 13:10:03 -0800 (PST) Subject: Why is break allowed in finally, but continue is not? Message-ID: For testing coverage.py, I wrote a program to generate randomly-structured Python functions. When compiling the results, I got a message I'd never seen before: SyntaxError: 'continue' not supported inside 'finally' clause I guess this makes sense, when cleaning up from an exception, continuing the loop seems an odd thing to do. But 'break' is allowed in 'finally' clauses! I tried this: # Huh? This prints "here", and no exception is raised. for i in range(1): try: 1/0 finally: # If you change this to "continue", you get: # 'continue' not supported inside 'finally' clause break print "here" The finally is perfectly willing to have a 'break', but it's a syntax error to have 'continue'? Why? I don't see a difference between the two when it comes to cleaning up exceptions. There are other things you can do in a finally clause that will prevent the exception from being raised, like 'return', and 'break' works just fine. So why treat 'continue' specially? --Ned. From ben+python at benfinney.id.au Sun Dec 13 17:27:50 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 14 Dec 2015 09:27:50 +1100 Subject: Why is break allowed in finally, but continue is not? References: Message-ID: <85oadu3rx5.fsf@benfinney.id.au> Ned Batchelder writes: > For testing coverage.py, I wrote a program to generate > randomly-structured Python functions. When compiling > the results, I got a message I'd never seen before: > > SyntaxError: 'continue' not supported inside 'finally' clause > > I guess this makes sense, when cleaning up from an > exception, continuing the loop seems an odd thing to do. > But 'break' is allowed in 'finally' clauses! I tried this: > > # Huh? This prints "here", and no exception is raised. > > for i in range(1): > try: > 1/0 > finally: > # If you change this to "continue", you get: > # 'continue' not supported inside 'finally' clause > break > print "here" > > The finally is perfectly willing to have a 'break', but it's > a syntax error to have 'continue'? Why? I don't see a > difference between the two when it comes to cleaning up > exceptions. Raymond Hettinger's answer is: The use of continue in a finally-clause is forbidden because its interpretation would have been problematic. [?] The example he uses:: for i in range(10): print i try: raise RuntimeError finally: continue # if the loop continues, what would happen to the exception? print i What, in your opinion, should the above code do if instead of ?continue? some other flow-control statement is used? > There are other things you can do in a finally clause that > will prevent the exception from being raised, like 'return', > and 'break' works just fine. Hettinger doesn't defend those, and is dubious about ?return?'s candidacy: Interestingly, you can put a return inside a finally-clause and it will swallow all exceptions including KeyboardInterrupt, SystemExit, and MemoryError. That probably isn't a good idea either ;-) > So why treat 'continue' specially? I am inclined to agree, but in the opposite direction: a case should be made for allowing *any* flow-control statement in an exception-handler's ?finally? clause. -- \ ?We can't depend for the long run on distinguishing one | `\ bitstream from another in order to figure out which rules | _o__) apply.? ?Eben Moglen, _Anarchism Triumphant_, 1999 | Ben Finney From kai.peters at gmail.com Sun Dec 13 19:24:53 2015 From: kai.peters at gmail.com (KP) Date: Sun, 13 Dec 2015 16:24:53 -0800 (PST) Subject: List of integers Message-ID: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> data = list(f.read(4)) print data from a binary file might give ['\x10', '\x20', '\x12', '\x01'] How can I receive this instead? [0x10, 0x20, 0x12, 0x01] Thanks for all help! From rosuav at gmail.com Sun Dec 13 19:32:58 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Dec 2015 11:32:58 +1100 Subject: List of integers In-Reply-To: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> References: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> Message-ID: On Mon, Dec 14, 2015 at 11:24 AM, KP wrote: > data = list(f.read(4)) > print data > > from a binary file might give > > ['\x10', '\x20', '\x12', '\x01'] > > > How can I receive this instead? > > [0x10, 0x20, 0x12, 0x01] > > Thanks for all help! Try this: data = [ord(x) for x in f.read(4)] Note that it won't print out in hexadecimal. >>> [0x10, 0x20, 0x12, 0x01] [16, 32, 18, 1] If you insist on that, try a subclass of int: class ord(int): ord = ord def __new__(cls, x): return super().__new__(cls, cls.ord(x)) def __repr__(self): return hex(self) Then they'll come out in hex. ChrisA From rxjwg98 at gmail.com Sun Dec 13 19:40:47 2015 From: rxjwg98 at gmail.com (Robert) Date: Sun, 13 Dec 2015 16:40:47 -0800 (PST) Subject: Help on class understanding in pymc code Message-ID: <8914575b-92c4-4b0e-adbf-ccb63c5edde5@googlegroups.com> Hi, I follow code example at link: https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html There is the following code line: sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) I want to know the detail of pymc.MCMC, then I get help content of it with: ///////////// help(pymc.MCMC) Help on class MCMC in module pymc.MCMC: class MCMC(pymc.Model.Sampler) | This class fits probability models using Markov Chain Monte Carlo. Each stochastic variable | is assigned a StepMethod object, which makes it take a single MCMC step conditional on the | rest of the model. These step methods are called in turn. | | >>> A = MCMC(input, db, verbose=0) | \\\\\\\\\\\\\\\\\\ help('pymc.Model.Sampler') no Python documentation found for 'pymc.Model.Sampler' help('pymc.Model') Help on class Model in pymc: pymc.Model = class Model(pymc.Container.ObjectContainer) | The base class for all objects that fit probability models. Model is initialized with: | | >>> A = Model(input, verbose=0) | | :Parameters: | - input : module, list, tuple, dictionary, set, object or nothing. | Model definition, in terms of Stochastics, Deterministics, Potentials and Containers. | If nothing, all nodes are collected from the base namespace. | | Attributes: | - deterministics | - stochastics (with observed=False) | - data (stochastic variables with observed=True) | - variables | - potentials | - containers | - nodes | - all_objects | - status: Not useful for the Model base class, but may be used by subclasses. | | The following attributes only exist after the appropriate method is called: | - moral_neighbors: The edges of the moralized graph. A dictionary, keyed by stochastic variable, | whose values are sets of stochastic variables. Edges exist between the key variable and all variables | in the value. Created by method _moralize. | - extended_children: The extended children of self's stochastic variables. See the docstring of | extend_children. This is a dictionary keyed by stochastic variable. | - generations: A list of sets of stochastic variables. The members of each element only have parents in | previous elements. Created by method find_generations. | | Methods: | - sample_model_likelihood(iter): Generate and return iter samples of p(data and potentials|model). | Can be used to generate Bayes' factors. | | :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph. | | Method resolution order: | Model | pymc.Container.ObjectContainer | pymc.six.NewBase | pymc.Node.ContainerBase | __builtin__.object | | Methods defined here: | | __init__(self, input=None, name=None, verbose=-1) | Initialize a Model instance. | | :Parameters: | - input : module, list, tuple, dictionary, set, object or nothing. | Model definition, in terms of Stochastics, Deterministics, Potentials and Containers. | If nothing, all nodes are collected from the base namespace. | | draw_from_prior(self) | Sets all variables to random values drawn from joint 'prior', meaning contributions | of data and potentials to the joint distribution are not considered. | | get_node(self, node_name) | Retrieve node with passed name | | seed(self) | Seed new initial values for the stochastics. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | generations | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __slotnames__ = [] | | register = False | | ---------------------------------------------------------------------- | Methods inherited from pymc.Container.ObjectContainer: | | replace(self, item, new_container, key) | | ---------------------------------------------------------------------- | Data descriptors inherited from pymc.Container.ObjectContainer: | | value | A copy of self, with all variables replaced by their values. | | ---------------------------------------------------------------------- | Methods inherited from pymc.Node.ContainerBase: | | assimilate(self, new_container) | | ---------------------------------------------------------------------- | Data descriptors inherited from pymc.Node.ContainerBase: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | logp | The summed log-probability of all stochastic variables (data | or otherwise) and factor potentials in self. | | ---------------------------------------------------------------------- | Data and other attributes inherited from pymc.Node.ContainerBase: | | change_methods = [] | | containing_classes = [] --------- Now, I have puzzles on the class constructor input parameter: [alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true] 1. 'class MCMC(pymc.Model.Sampler)' says its inheritance is from 'pymc.Model.Sampler' 2. When I try to get help on 'pymc.Model.Sampler', it says: 'no Python documentation found for 'pymc.Model.Sampler' 3. When I continue to catch help on 'pymc.Model.Sampler', I don't see content mentions 'Sampler'. This complete help message is shown above. So, what is 'pymc.Model.Sampler'? BTW, I use Enthought Canopy, Python 2.7. Thanks, From __peter__ at web.de Sun Dec 13 20:09:51 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Dec 2015 02:09:51 +0100 Subject: Help on class understanding in pymc code References: <8914575b-92c4-4b0e-adbf-ccb63c5edde5@googlegroups.com> Message-ID: Robert wrote: > Hi, > > I follow code example at link: > > https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html > > > There is the following code line: > > sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) > > > I want to know the detail of pymc.MCMC, then I get help content of it > with: > > ///////////// > help(pymc.MCMC) > Help on class MCMC in module pymc.MCMC: > > class MCMC(pymc.Model.Sampler) > | This class fits probability models using Markov Chain Monte Carlo. > | Each stochastic variable is assigned a StepMethod object, which makes > | it take a single MCMC step conditional on the rest of the model. These > | step methods are called in turn. > | > | >>> A = MCMC(input, db, verbose=0) > | > \\\\\\\\\\\\\\\\\\ > > > help('pymc.Model.Sampler') > no Python documentation found for 'pymc.Model.Sampler' > > > help('pymc.Model') > Help on class Model in pymc: > > pymc.Model = class Model(pymc.Container.ObjectContainer) > | The base class for all objects that fit probability models. Model is > | initialized with: > | > | >>> A = Model(input, verbose=0) > | > | :Parameters: > | - input : module, list, tuple, dictionary, set, object or nothing. > | Model definition, in terms of Stochastics, Deterministics, > | Potentials and Containers. If nothing, all nodes are collected > | from the base namespace. > | > | Attributes: > | - deterministics > | - stochastics (with observed=False) > | - data (stochastic variables with observed=True) > | - variables > | - potentials > | - containers > | - nodes > | - all_objects > | - status: Not useful for the Model base class, but may be used by > | subclasses. > | > | The following attributes only exist after the appropriate method is > | called: > | - moral_neighbors: The edges of the moralized graph. A dictionary, > | keyed by stochastic variable, > | whose values are sets of stochastic variables. Edges exist between > | the key variable and all variables in the value. Created by method > | _moralize. > | - extended_children: The extended children of self's stochastic > | variables. See the docstring of > | extend_children. This is a dictionary keyed by stochastic > | variable. > | - generations: A list of sets of stochastic variables. The members > | of each element only have parents in > | previous elements. Created by method find_generations. > | > | Methods: > | - sample_model_likelihood(iter): Generate and return iter samples > | of p(data and potentials|model). > | Can be used to generate Bayes' factors. > | > | :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph. > | > | Method resolution order: > | Model > | pymc.Container.ObjectContainer > | pymc.six.NewBase > | pymc.Node.ContainerBase > | __builtin__.object > | > | Methods defined here: > | > | __init__(self, input=None, name=None, verbose=-1) > | Initialize a Model instance. > | > | :Parameters: > | - input : module, list, tuple, dictionary, set, object or > | nothing. > | Model definition, in terms of Stochastics, Deterministics, > | Potentials and Containers. If nothing, all nodes are > | collected from the base namespace. > | > | draw_from_prior(self) > | Sets all variables to random values drawn from joint 'prior', > | meaning contributions of data and potentials to the joint > | distribution are not considered. > | > | get_node(self, node_name) > | Retrieve node with passed name > | > | seed(self) > | Seed new initial values for the stochastics. > | > | ---------------------------------------------------------------------- > | Data descriptors defined here: > | > | generations > | > | ---------------------------------------------------------------------- > | Data and other attributes defined here: > | > | __slotnames__ = [] > | > | register = False > | > | ---------------------------------------------------------------------- > | Methods inherited from pymc.Container.ObjectContainer: > | > | replace(self, item, new_container, key) > | > | ---------------------------------------------------------------------- > | Data descriptors inherited from pymc.Container.ObjectContainer: > | > | value > | A copy of self, with all variables replaced by their values. > | > | ---------------------------------------------------------------------- > | Methods inherited from pymc.Node.ContainerBase: > | > | assimilate(self, new_container) > | > | ---------------------------------------------------------------------- > | Data descriptors inherited from pymc.Node.ContainerBase: > | > | __dict__ > | dictionary for instance variables (if defined) > | > | __weakref__ > | list of weak references to the object (if defined) > | > | logp > | The summed log-probability of all stochastic variables (data > | or otherwise) and factor potentials in self. > | > | ---------------------------------------------------------------------- > | Data and other attributes inherited from pymc.Node.ContainerBase: > | > | change_methods = [] > | > | containing_classes = [] > --------- > > > Now, I have puzzles on the class constructor input parameter: > [alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true] > > 1. 'class MCMC(pymc.Model.Sampler)' says its inheritance is from > 'pymc.Model.Sampler' > > 2. When I try to get help on 'pymc.Model.Sampler', it says: > 'no Python documentation found for 'pymc.Model.Sampler' > > 3. When I continue to catch help on 'pymc.Model.Sampler', I don't see > content mentions 'Sampler'. This complete help message is shown above. > > So, what is 'pymc.Model.Sampler'? Unfortunately there is a module pymc.Model and a class pymc.Model.Model, and in pymc.__init__.py there is code that overwrites the module with the class. Therefore when you write pymc.Model you get pymc.Model.Model as you can see when you type >>> import pymc >>> pymc.Model To get around this bad naming use >>> from pymc.Model import Sampler >>> help(Sampler) From rxjwg98 at gmail.com Sun Dec 13 20:45:53 2015 From: rxjwg98 at gmail.com (Robert) Date: Sun, 13 Dec 2015 17:45:53 -0800 (PST) Subject: Help on class understanding in pymc code In-Reply-To: References: <8914575b-92c4-4b0e-adbf-ccb63c5edde5@googlegroups.com> Message-ID: <9cb4a680-0c6a-445f-b94d-2d2a06daef91@googlegroups.com> On Sunday, December 13, 2015 at 8:10:25 PM UTC-5, Peter Otten wrote: > Robert wrote: > > > Hi, > > > > I follow code example at link: > > > > https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html > > > > > > There is the following code line: > > > > sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) > > > > > > I want to know the detail of pymc.MCMC, then I get help content of it > > with: > > > > ///////////// > > help(pymc.MCMC) > > Help on class MCMC in module pymc.MCMC: > > > > class MCMC(pymc.Model.Sampler) > > | This class fits probability models using Markov Chain Monte Carlo. > > | Each stochastic variable is assigned a StepMethod object, which makes > > | it take a single MCMC step conditional on the rest of the model. These > > | step methods are called in turn. > > | > > | >>> A = MCMC(input, db, verbose=0) > > | > > \\\\\\\\\\\\\\\\\\ > > > > > > help('pymc.Model.Sampler') > > no Python documentation found for 'pymc.Model.Sampler' > > > > > > help('pymc.Model') > > Help on class Model in pymc: > > > > pymc.Model = class Model(pymc.Container.ObjectContainer) > > | The base class for all objects that fit probability models. Model is > > | initialized with: > > | > > | >>> A = Model(input, verbose=0) > > | > > | :Parameters: > > | - input : module, list, tuple, dictionary, set, object or nothing. > > | Model definition, in terms of Stochastics, Deterministics, > > | Potentials and Containers. If nothing, all nodes are collected > > | from the base namespace. > > | > > | Attributes: > > | - deterministics > > | - stochastics (with observed=False) > > | - data (stochastic variables with observed=True) > > | - variables > > | - potentials > > | - containers > > | - nodes > > | - all_objects > > | - status: Not useful for the Model base class, but may be used by > > | subclasses. > > | > > | The following attributes only exist after the appropriate method is > > | called: > > | - moral_neighbors: The edges of the moralized graph. A dictionary, > > | keyed by stochastic variable, > > | whose values are sets of stochastic variables. Edges exist between > > | the key variable and all variables in the value. Created by method > > | _moralize. > > | - extended_children: The extended children of self's stochastic > > | variables. See the docstring of > > | extend_children. This is a dictionary keyed by stochastic > > | variable. > > | - generations: A list of sets of stochastic variables. The members > > | of each element only have parents in > > | previous elements. Created by method find_generations. > > | > > | Methods: > > | - sample_model_likelihood(iter): Generate and return iter samples > > | of p(data and potentials|model). > > | Can be used to generate Bayes' factors. > > | > > | :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph. > > | > > | Method resolution order: > > | Model > > | pymc.Container.ObjectContainer > > | pymc.six.NewBase > > | pymc.Node.ContainerBase > > | __builtin__.object > > | > > | Methods defined here: > > | > > | __init__(self, input=None, name=None, verbose=-1) > > | Initialize a Model instance. > > | > > | :Parameters: > > | - input : module, list, tuple, dictionary, set, object or > > | nothing. > > | Model definition, in terms of Stochastics, Deterministics, > > | Potentials and Containers. If nothing, all nodes are > > | collected from the base namespace. > > | > > | draw_from_prior(self) > > | Sets all variables to random values drawn from joint 'prior', > > | meaning contributions of data and potentials to the joint > > | distribution are not considered. > > | > > | get_node(self, node_name) > > | Retrieve node with passed name > > | > > | seed(self) > > | Seed new initial values for the stochastics. > > | > > | ---------------------------------------------------------------------- > > | Data descriptors defined here: > > | > > | generations > > | > > | ---------------------------------------------------------------------- > > | Data and other attributes defined here: > > | > > | __slotnames__ = [] > > | > > | register = False > > | > > | ---------------------------------------------------------------------- > > | Methods inherited from pymc.Container.ObjectContainer: > > | > > | replace(self, item, new_container, key) > > | > > | ---------------------------------------------------------------------- > > | Data descriptors inherited from pymc.Container.ObjectContainer: > > | > > | value > > | A copy of self, with all variables replaced by their values. > > | > > | ---------------------------------------------------------------------- > > | Methods inherited from pymc.Node.ContainerBase: > > | > > | assimilate(self, new_container) > > | > > | ---------------------------------------------------------------------- > > | Data descriptors inherited from pymc.Node.ContainerBase: > > | > > | __dict__ > > | dictionary for instance variables (if defined) > > | > > | __weakref__ > > | list of weak references to the object (if defined) > > | > > | logp > > | The summed log-probability of all stochastic variables (data > > | or otherwise) and factor potentials in self. > > | > > | ---------------------------------------------------------------------- > > | Data and other attributes inherited from pymc.Node.ContainerBase: > > | > > | change_methods = [] > > | > > | containing_classes = [] > > --------- > > > > > > Now, I have puzzles on the class constructor input parameter: > > [alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true] > > > > 1. 'class MCMC(pymc.Model.Sampler)' says its inheritance is from > > 'pymc.Model.Sampler' > > > > 2. When I try to get help on 'pymc.Model.Sampler', it says: > > 'no Python documentation found for 'pymc.Model.Sampler' > > > > 3. When I continue to catch help on 'pymc.Model.Sampler', I don't see > > content mentions 'Sampler'. This complete help message is shown above. > > > > So, what is 'pymc.Model.Sampler'? > > Unfortunately there is a module pymc.Model and a class pymc.Model.Model, and > in pymc.__init__.py there is code that overwrites the module with the class. > Therefore when you write > > pymc.Model > > you get > > pymc.Model.Model > > as you can see when you type > > >>> import pymc > >>> pymc.Model > > > To get around this bad naming use > > >>> from pymc.Model import Sampler > >>> help(Sampler) Thanks. Your answer does solve the problem, but I cannot follow your words. When you run below code, what is 'pymc.Model'? >>> import pymc >>> pymc.Model When I run: aaa=pymc.Model type(aaa) Out[160]: pymc.Node.ContainerMeta type(pymc.Model) Out[161]: pymc.Node.ContainerMeta I see that it is not ''. Thanks again. From steve at pearwood.info Sun Dec 13 21:43:07 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Dec 2015 13:43:07 +1100 Subject: Calling a list of functions References: Message-ID: <566e2cbc$0$1590$c3e8da3$5496439d@news.astraweb.com> On Mon, 14 Dec 2015 04:26 am, Ganesh Pal wrote: > Hi Team, > > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , No it doesn't. It doesn't even compile -- it gives a SyntaxError because you incorrectly use // as a comment deliminator instead of #. After fixing that, you get a second SyntaxError because your code has an empty "except" block. Obviously the code you show us is not the code you ran. Why do people do this? "Hi, here's a cake a made earlier, I think it tastes really nice. What do you think?" "That's not a cake. It's a bowl of mud with a cherry on top. Where is the actual cake?" -- Steven From rosuav at gmail.com Sun Dec 13 21:49:05 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Dec 2015 13:49:05 +1100 Subject: Calling a list of functions In-Reply-To: <566e2cbc$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <566e2cbc$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Dec 14, 2015 at 1:43 PM, Steven D'Aprano wrote: > Why do people do this? > > "Hi, here's a cake a made earlier, I think it tastes really nice. What do > you think?" > > "That's not a cake. It's a bowl of mud with a cherry on top. Where is the > actual cake?" Steven, haven't you ever had a mudcake before? ChrisA From kai.peters at gmail.com Sun Dec 13 22:11:47 2015 From: kai.peters at gmail.com (KP) Date: Sun, 13 Dec 2015 19:11:47 -0800 (PST) Subject: List of integers In-Reply-To: References: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> Message-ID: <980bd362-3c0f-4449-b474-bc8b492bc1cf@googlegroups.com> On Sunday, 13 December 2015 16:33:20 UTC-8, Chris Angelico wrote: > On Mon, Dec 14, 2015 at 11:24 AM, KP <> wrote: > > data = list(f.read(4)) > > print data > > > > from a binary file might give > > > > ['\x10', '\x20', '\x12', '\x01'] > > > > > > How can I receive this instead? > > > > [0x10, 0x20, 0x12, 0x01] > > > > Thanks for all help! > > Try this: > > data = [ord(x) for x in f.read(4)] > > Note that it won't print out in hexadecimal. > > >>> [0x10, 0x20, 0x12, 0x01] > [16, 32, 18, 1] > > If you insist on that, try a subclass of int: > > class ord(int): > ord = ord > def __new__(cls, x): > return super().__new__(cls, cls.ord(x)) > def __repr__(self): return hex(self) > > Then they'll come out in hex. > > ChrisA Thanks much! From abapat at gmail.com Mon Dec 14 00:54:41 2015 From: abapat at gmail.com (Anand) Date: Sun, 13 Dec 2015 21:54:41 -0800 (PST) Subject: Calling a list of functions In-Reply-To: References: Message-ID: On Sunday, December 13, 2015 at 9:26:52 AM UTC-8, Ganesh Pal wrote: > Hi Team, > > Iam on linux and python 2.7 . I have a bunch of functions which I > have run sequentially . > I have put them in a list and Iam calling the functions in the list as > shown below , this works fine for me , please share your > opinion/views on the same > > > Sample code : > > def print1(): > print "one" > > def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function > > for test in range(len(print_test)): > try: > print_test[test] > except AssertionError as exc: > > > Regards, > Ganesh def print1(): print "one" def print2(): > print "two" > > def print3(): > print "three" > > print_test = [print1(),print2(),print3()] //calling the function If the idea is to have a 'pointers to function array' (as in C), you can do this: fun_arr=[print1,print2,print3] # Execute now [ f() for f in fun_arr ] From dhaval.parekh at ncrypted.com Mon Dec 14 01:20:05 2015 From: dhaval.parekh at ncrypted.com (Dhaval Parekh - NCrypted) Date: Mon, 14 Dec 2015 11:50:05 +0530 Subject: Can't find way to install psycopg2 in 3.5 Message-ID: <000201d13637$87219040$9564b0c0$@ncrypted.com> Hello, I'm newbie in using python. I've installed python 3.5 and django 1.9 to develop web application. I wanted to set postgresql as a DBMS but I couldn't complete the setup as it was continuously throwing me an error that psycopg2 module not found. I've digged a lot but I couldn't find psycopg2 for python 3.5. Is it something 3.5 has different scenario for django? I couldn't find anyway to complete my setup so I'm going to downgrade to 3.4 as I found psycopg2 for 3.4 only. If you have any idea about it then please let me know. Regards, Dhaval Parekh Project Coordinator, NCrypted Technologies Pvt. Ltd. http://www.ncrypted.com An ISO 9001:2008 Certified Company | BID International Quality Crown (2012) Award Winner IDC: 2nd floor, Shivalik 5, Gondal Road, Rajkot (Gujarat), India | +91 (281) 237 8880, 391 8880 Disclaimer & Privilege Notice: This e-Mail may contain proprietary, privileged and confidential information and is sent for the intended recipient(s) only. If, by an addressing or transmission error, this mail has been misdirected to you, you are requested to notify us immediately by return email message and delete this mail and its attachments. You are also hereby notified that any use, any form of reproduction, dissemination, copying, disclosure, modification, distribution and/or publication of this e-mail message, contents or its attachment(s) other than by its intended recipient(s) is strictly prohibited. Any opinions expressed in this email are those of the individual and may not necessarily represent those of NCrypted Technologies Pvt. Ltd. Before opening attachment(s), please scan for viruses. NCrypted is a registered trademark of NCrypted Technologies Pvt. Ltd. in India and other countries. From __peter__ at web.de Mon Dec 14 03:56:39 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Dec 2015 09:56:39 +0100 Subject: Help on class understanding in pymc code References: <8914575b-92c4-4b0e-adbf-ccb63c5edde5@googlegroups.com> <9cb4a680-0c6a-445f-b94d-2d2a06daef91@googlegroups.com> Message-ID: Robert wrote: > On Sunday, December 13, 2015 at 8:10:25 PM UTC-5, Peter Otten wrote: >> Robert wrote: >> >> > Hi, >> > >> > I follow code example at link: >> > >> > https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html >> > >> > >> > There is the following code line: >> > >> > sampler = >> > pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) >> > >> > >> > I want to know the detail of pymc.MCMC, then I get help content of it >> > with: >> > >> > ///////////// >> > help(pymc.MCMC) >> > Help on class MCMC in module pymc.MCMC: >> > >> > class MCMC(pymc.Model.Sampler) >> > | This class fits probability models using Markov Chain Monte Carlo. >> > | Each stochastic variable is assigned a StepMethod object, which >> > | makes it take a single MCMC step conditional on the rest of the >> > | model. These step methods are called in turn. >> > | >> > | >>> A = MCMC(input, db, verbose=0) >> > | >> > \\\\\\\\\\\\\\\\\\ >> > >> > >> > help('pymc.Model.Sampler') >> > no Python documentation found for 'pymc.Model.Sampler' >> > >> > >> > help('pymc.Model') >> > Help on class Model in pymc: >> > >> > pymc.Model = class Model(pymc.Container.ObjectContainer) >> > | The base class for all objects that fit probability models. Model >> > | is initialized with: >> > | >> > | >>> A = Model(input, verbose=0) >> > | >> > | :Parameters: >> > | - input : module, list, tuple, dictionary, set, object or >> > | nothing. >> > | Model definition, in terms of Stochastics, Deterministics, >> > | Potentials and Containers. If nothing, all nodes are >> > | collected from the base namespace. >> > | >> > | Attributes: >> > | - deterministics >> > | - stochastics (with observed=False) >> > | - data (stochastic variables with observed=True) >> > | - variables >> > | - potentials >> > | - containers >> > | - nodes >> > | - all_objects >> > | - status: Not useful for the Model base class, but may be used by >> > | subclasses. >> > | >> > | The following attributes only exist after the appropriate method is >> > | called: >> > | - moral_neighbors: The edges of the moralized graph. A >> > | dictionary, keyed by stochastic variable, >> > | whose values are sets of stochastic variables. Edges exist >> > | between the key variable and all variables in the value. >> > | Created by method _moralize. >> > | - extended_children: The extended children of self's stochastic >> > | variables. See the docstring of >> > | extend_children. This is a dictionary keyed by stochastic >> > | variable. >> > | - generations: A list of sets of stochastic variables. The >> > | members of each element only have parents in >> > | previous elements. Created by method find_generations. >> > | >> > | Methods: >> > | - sample_model_likelihood(iter): Generate and return iter >> > | samples of p(data and potentials|model). >> > | Can be used to generate Bayes' factors. >> > | >> > | :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, >> > | :graph. >> > | >> > | Method resolution order: >> > | Model >> > | pymc.Container.ObjectContainer >> > | pymc.six.NewBase >> > | pymc.Node.ContainerBase >> > | __builtin__.object >> > | >> > | Methods defined here: >> > | >> > | __init__(self, input=None, name=None, verbose=-1) >> > | Initialize a Model instance. >> > | >> > | :Parameters: >> > | - input : module, list, tuple, dictionary, set, object or >> > | nothing. >> > | Model definition, in terms of Stochastics, >> > | Deterministics, Potentials and Containers. If nothing, >> > | all nodes are collected from the base namespace. >> > | >> > | draw_from_prior(self) >> > | Sets all variables to random values drawn from joint 'prior', >> > | meaning contributions of data and potentials to the joint >> > | distribution are not considered. >> > | >> > | get_node(self, node_name) >> > | Retrieve node with passed name >> > | >> > | seed(self) >> > | Seed new initial values for the stochastics. >> > | >> > | ---------------------------------------------------------------------- >> > | Data descriptors defined here: >> > | >> > | generations >> > | >> > | ---------------------------------------------------------------------- >> > | Data and other attributes defined here: >> > | >> > | __slotnames__ = [] >> > | >> > | register = False >> > | >> > | ---------------------------------------------------------------------- >> > | Methods inherited from pymc.Container.ObjectContainer: >> > | >> > | replace(self, item, new_container, key) >> > | >> > | ---------------------------------------------------------------------- >> > | Data descriptors inherited from pymc.Container.ObjectContainer: >> > | >> > | value >> > | A copy of self, with all variables replaced by their values. >> > | >> > | ---------------------------------------------------------------------- >> > | Methods inherited from pymc.Node.ContainerBase: >> > | >> > | assimilate(self, new_container) >> > | >> > | ---------------------------------------------------------------------- >> > | Data descriptors inherited from pymc.Node.ContainerBase: >> > | >> > | __dict__ >> > | dictionary for instance variables (if defined) >> > | >> > | __weakref__ >> > | list of weak references to the object (if defined) >> > | >> > | logp >> > | The summed log-probability of all stochastic variables (data >> > | or otherwise) and factor potentials in self. >> > | >> > | ---------------------------------------------------------------------- >> > | Data and other attributes inherited from pymc.Node.ContainerBase: >> > | >> > | change_methods = [] >> > | >> > | containing_classes = [] >> > --------- >> > >> > >> > Now, I have puzzles on the class constructor input parameter: >> > [alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true] >> > >> > 1. 'class MCMC(pymc.Model.Sampler)' says its inheritance is from >> > 'pymc.Model.Sampler' >> > >> > 2. When I try to get help on 'pymc.Model.Sampler', it says: >> > 'no Python documentation found for 'pymc.Model.Sampler' >> > >> > 3. When I continue to catch help on 'pymc.Model.Sampler', I don't see >> > content mentions 'Sampler'. This complete help message is shown above. >> > >> > So, what is 'pymc.Model.Sampler'? >> >> Unfortunately there is a module pymc.Model and a class pymc.Model.Model, >> and in pymc.__init__.py there is code that overwrites the module with the >> class. Therefore when you write >> >> pymc.Model >> >> you get >> >> pymc.Model.Model >> >> as you can see when you type >> >> >>> import pymc >> >>> pymc.Model >> >> >> To get around this bad naming use >> >> >>> from pymc.Model import Sampler >> >>> help(Sampler) > > Thanks. Your answer does solve the problem, but I cannot follow your > words. When you run below code, what is 'pymc.Model'? > > >>>> import pymc >>>> pymc.Model > > > > When I run: import pymc This imports the pymc package. Technically this is achieved by executing pymc/__init__.py In __init__.py there is a line from Model import * This line puts all names in pymc.Model.__all__ into the current namespace and is roughly equivalent to import Model as _tmp Model = _tmp.Model Sampler = _tmp.Sampler del _tmp so that after the star import pymc.Model is the class pymc.Model.Model. > aaa=pymc.Model Now aaa is (a name for) that class, too. > type(aaa) The type() of a class is its "metaclass". The relationship metaclass --> class is the same as class --> instance i. e. a Python class is an instance of its metaclass like 42 is an instance of int. > Out[160]: pymc.Node.ContainerMeta By default all classes derived from object are of type "type". So that's a custom metaclass. You probably don't care about that at this time in your career as a pythonista. > type(pymc.Model) > Out[161]: pymc.Node.ContainerMeta > > I see that it is not ''. Because pymc.Model is pymc.Model.Model already. The equivalent for int would be to type >>> type(int) and expecting it to return int. From rosuav at gmail.com Mon Dec 14 04:01:15 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Dec 2015 20:01:15 +1100 Subject: Can't find way to install psycopg2 in 3.5 In-Reply-To: <000201d13637$87219040$9564b0c0$@ncrypted.com> References: <000201d13637$87219040$9564b0c0$@ncrypted.com> Message-ID: On Mon, Dec 14, 2015 at 5:20 PM, Dhaval Parekh - NCrypted wrote: > I've digged a lot but I couldn't find psycopg2 for python 3.5. Here's where I'd get a psycopg2 binary: http://www.lfd.uci.edu/~gohlke/pythonlibs/#psycopg If you've tried that and still can't get Python to talk to Postgres, post any errors you got from the installation, and we'll see what's wrong. There were some changes to install locations and such in 3.5 so it's possible that something isn't working with those binaries. But I have fair confidence in them. ChrisA From tjreedy at udel.edu Mon Dec 14 04:56:06 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2015 04:56:06 -0500 Subject: List of integers In-Reply-To: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> References: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> Message-ID: On 12/13/2015 7:24 PM, KP wrote: > > > data = list(f.read(4)) > print data > > from a binary file might give In 2.x, a binary file and a text file are not distinguished. > ['\x10', '\x20', '\x12', '\x01'] If a 'binary' file yields strings, you must be using 2.x. > How can I receive this instead? > [0x10, 0x20, 0x12, 0x01] Use python 3. -- Terry Jan Reedy From framstag at rus.uni-stuttgart.de Mon Dec 14 05:19:30 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Mon, 14 Dec 2015 10:19:30 +0000 (UTC) Subject: pyinstaller ignores icon Message-ID: pyinstaller ignores a specified icon file: the resulting executable shows the default icon on the desktop. I compile with: S:\python>pyinstaller.exe --onefile --icon=fex.ico fexit.py 31 INFO: PyInstaller: 3.0 31 INFO: Python: 2.7.11 31 INFO: Platform: Windows-7-6.1.7601-SP1 31 INFO: wrote S:\python\fexit.spec 47 INFO: UPX is not available. 47 INFO: Extending PYTHONPATH with S:\python 47 INFO: checking Analysis 920 INFO: checking PYZ 1014 INFO: checking PKG 1092 INFO: Building because S:\python\build\fexit\fexit.exe.manifest changed 1092 INFO: Building PKG (CArchive) out00-PKG.pkg 1497 INFO: Redirecting Microsoft.VC90.CRT version (9, 0, 21022, 8) -> (9, 0, 30729, 4940) 5366 INFO: Bootloader c:\python27\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe 5366 INFO: checking EXE 5444 INFO: Building because out00-EXE.toc is bad 5475 INFO: Building EXE from out00-EXE.toc 5522 INFO: SRCPATH [('fex.ico', None)] 5522 INFO: Updating icons from ['fex.ico'] to c:\users\admin\appdata\local\temp\tmpoingb4 5522 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes 5522 INFO: Writing RT_ICON 1 resource with 18488 bytes 5538 INFO: Appending archive to EXE S:\python\dist\fexit.exe http://fex.rus.uni-stuttgart.de/fop/SsmdcBLk/X-20151214111803.png Where is the error? -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From michael.poeltl at univie.ac.at Mon Dec 14 05:24:05 2015 From: michael.poeltl at univie.ac.at (Michael Poeltl) Date: Mon, 14 Dec 2015 11:24:05 +0100 Subject: Can't find way to install psycopg2 in 3.5 In-Reply-To: <000201d13637$87219040$9564b0c0$@ncrypted.com> References: <000201d13637$87219040$9564b0c0$@ncrypted.com> Message-ID: <20151214102405.GE5520@horus> hi, I'm used to compile postgresql from source (last time it was postgresql-9.4.4 with ./configure --prefix=/usr --enable-thread-safety --docdir=/usr/share/doc/postgresql-9.4.4 --with-tcl --with-openssl --enable-nls=de --with-libxml on my linuxmint17-box) and then the installation of psycopg2 (in my case psycopg2-2.6.1) works just fine and smoothly (even for python-3.5!). If you've got postgresql through a pre-compiled package it is (maybe) necessary to *show* where to find 'pg_config' by editing the setup.cfg-file in the psycopg2-source-folder. Have you visited this site? http://initd.org/psycopg/ regards Michael * Dhaval Parekh - NCrypted [2015-12-14 09:29]: > Hello, > > > > I'm newbie in using python. I've installed python 3.5 and django 1.9 to > develop web application. I wanted to set postgresql as a DBMS but I couldn't > complete the setup as it was continuously throwing me an error that psycopg2 > module not found. I've digged a lot but I couldn't find psycopg2 for python > 3.5. Is it something 3.5 has different scenario for django? I couldn't find > anyway to complete my setup so I'm going to downgrade to 3.4 as I found > psycopg2 for 3.4 only. > > > > If you have any idea about it then please let me know. > > > > > > > > Regards, > > Dhaval Parekh > > Project Coordinator, > > NCrypted Technologies Pvt. Ltd. > http://www.ncrypted.com > > > > An ISO 9001:2008 Certified Company | BID International Quality Crown (2012) > Award Winner > > IDC: 2nd floor, Shivalik 5, Gondal Road, Rajkot (Gujarat), India | +91 (281) > 237 8880, 391 8880 > > Disclaimer & Privilege Notice: This e-Mail may contain proprietary, > privileged and confidential information and is sent for the intended > recipient(s) only. If, by an addressing or transmission error, this mail has > been misdirected to you, you are requested to notify us immediately by > return email message and delete this mail and its attachments. You are also > hereby notified that any use, any form of reproduction, dissemination, > copying, disclosure, modification, distribution and/or publication of this > e-mail message, contents or its attachment(s) other than by its intended > recipient(s) is strictly prohibited. Any opinions expressed in this email > are those of the individual and may not necessarily represent those of > NCrypted Technologies Pvt. Ltd. Before opening attachment(s), please scan > for viruses. > > NCrypted is a registered trademark of NCrypted Technologies Pvt. Ltd. in > India and other countries. > > > > -- > https://mail.python.org/mailman/listinfo/python-list -- Michael Poeltl Computational Materials Physics at University Wien, Sensengasse 8/12, A-1090 Wien, AUSTRIA http://cmp.univie.ac.at/ http://homepage.univie.ac.at/michael.poeltl/ using elinks-0.12, mutt-1.5.21, and vim-7.4, with python-3.4.3, on linux mint 17 (qiana) :-) fon: +43-1-4277-51409 "Lehrend lernen wir!" From steve at pearwood.info Mon Dec 14 05:37:38 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Dec 2015 21:37:38 +1100 Subject: List of integers References: <6faae197-594a-4447-b146-6f5e01185e26@googlegroups.com> Message-ID: <566e9bf4$0$1591$c3e8da3$5496439d@news.astraweb.com> On Mon, 14 Dec 2015 08:56 pm, Terry Reedy wrote: > On 12/13/2015 7:24 PM, KP wrote: >> >> >> data = list(f.read(4)) >> print data >> >> from a binary file might give > > In 2.x, a binary file and a text file are not distinguished. I think what you mean is that, in Python 2, reading from a file returns a byte string regardless of whether you open it in text mode or binary mode. That part is true, but there are other differences between text files and binary files (opened in the correct mode): binary mode is guaranteed to return the actual bytes in the file, but opening it in text mode may perform some platform-specific processing: (1) \r or \r\n may be converted to \n (2) Ctrl-Z may be interpreted as end-of-file There may be other changes made as well. >> ['\x10', '\x20', '\x12', '\x01'] > > If a 'binary' file yields strings, you must be using 2.x. > >> How can I receive this instead? >> [0x10, 0x20, 0x12, 0x01] > > Use python 3. True, except by default integers display in decimal, not hex: py> [0x10, 0x20, 0x12, 0x01] [16, 32, 18, 1] -- Steven From framstag at rus.uni-stuttgart.de Mon Dec 14 11:24:54 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Mon, 14 Dec 2015 16:24:54 +0000 (UTC) Subject: cannot open file with non-ASCII filename Message-ID: With Python 2.7.11 on Windows 7 my users cannot open/read files with non-ASCII filenames. They use the Windows explorer to drag&drop files into a console window running the Python program. os.path.exists() does not detect such a file and an open() fails, too. My code: print("\nDrag&drop files or directories into this window.") system('explorer "%s"' % HOME) file = get_paste() if not(os.path.exists(file)): die('"%s" does not exist' % file) def get_paste(): import msvcrt while True: c = msvcrt.getch() if c == '\t': return '' if c == '\003' or c == '\004': return None if not (c == '\n' or c == '\r'): break paste = c while msvcrt.kbhit(): c = msvcrt.getch() if c == '\n' or c == '\r': break paste += c if match(r'\s',paste): paste = subst('^"(.+)"$',r'\1',paste) return paste -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From sjeik_appie at hotmail.com Mon Dec 14 11:31:17 2015 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Mon, 14 Dec 2015 16:31:17 +0000 Subject: Screenshots in Sphinx docs Message-ID: Hello, I'd like to include up-to-date screenshots (of a tkinter app) into my Sphinx documentation. This looks ok: https://pypi.python.org/pypi/sphinxcontrib-programscreenshot BUT I need something that works on Windows (Python 2.7). Can any recommend an approach? I thought about using PIL: http://www.varesano.net/blog/fabio/capturing%20screen%20image%20python%20and%20pil%20windows Thanks! Albert-Jan From ned at nedbatchelder.com Mon Dec 14 12:37:13 2015 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 14 Dec 2015 09:37:13 -0800 (PST) Subject: Why is break allowed in finally, but continue is not? In-Reply-To: References: Message-ID: On Sunday, December 13, 2015 at 5:28:44 PM UTC-5, Ben Finney wrote: > Ned Batchelder writes: > > So why treat 'continue' specially? > > I am inclined to agree, but in the opposite direction: a case should be > made for allowing *any* flow-control statement in an exception-handler's > 'finally' clause. I agree, those all seem like bad ideas. But 'continue' has been singled out for a SyntaxError. Rumor has it that continue was difficult to make work at all, while the other keywords, while ill-advised, were at least possible. --Ned. From tjreedy at udel.edu Mon Dec 14 13:34:56 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2015 13:34:56 -0500 Subject: cannot open file with non-ASCII filename In-Reply-To: References: Message-ID: <566F0BD0.8020106@udel.edu> On 12/14/2015 11:24 AM, Ulli Horlacher wrote: > With Python 2.7.11 on Windows 7 my users cannot open/read files with > non-ASCII filenames. Right. They should either restrict themselves to ascii (or possibly latin-1) filenames or use current 3.x. This is one of the (known) unicode problems fixed in 3.x by making unicode the core text class, replacing the implementation of unicode, and performing further work with the new implementation. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Mon Dec 14 13:40:26 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 14 Dec 2015 18:40:26 +0000 Subject: Why is break allowed in finally, but continue is not? In-Reply-To: References: Message-ID: On 14/12/2015 17:37, Ned Batchelder wrote: > On Sunday, December 13, 2015 at 5:28:44 PM UTC-5, Ben Finney wrote: >> Ned Batchelder writes: >>> So why treat 'continue' specially? >> >> I am inclined to agree, but in the opposite direction: a case should be >> made for allowing *any* flow-control statement in an exception-handler's >> 'finally' clause. > > I agree, those all seem like bad ideas. But 'continue' has been singled > out for a SyntaxError. Rumor has it that continue was difficult to make > work at all, while the other keywords, while ill-advised, were at least > possible. > > --Ned. > Part of the rumour mill http://www.gossamer-threads.com/lists/python/dev/484210? This was referenced from the stackoverflow question that Ben Finney referred to yesterday. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From eryksun at gmail.com Mon Dec 14 13:45:31 2015 From: eryksun at gmail.com (eryk sun) Date: Mon, 14 Dec 2015 12:45:31 -0600 Subject: cannot open file with non-ASCII filename In-Reply-To: References: Message-ID: On Mon, Dec 14, 2015 at 10:24 AM, Ulli Horlacher wrote: > With Python 2.7.11 on Windows 7 my users cannot open/read files with > non-ASCII filenames. [...] > c = msvcrt.getch() This isn't an issue with Python per se, and the same problem exists in Python 3, using either getch or getwch. Microsoft's getwch function isn't designed to handle the variety of ways the console host (conhost.exe) encodes Unicode keyboard events. Their implementation calls ReadConsoleInput and looks for a KEY_EVENT. If bKeyDown is set it grabs the UnicodeChar field. In an ideal world it would be that simple. However, the console literally supports the alt+numpad sequences that allow entering characters by code. So the input event sequence, for example, could be +VK_MENU, +VK_NUMPAD7, -VK_NUMPAD7, +VK_NUMPAD6, -VK_NUMPAD6, -VK_MENU, which is an "L". (Denoting "+" as key down and "-" as key up.) This may just be the closest approximation in the system locale's codepage (ANSI). That doesn't matter because the actual Unicode codepoint is set in the last event's UnicodeChar field. Try using the pyreadline module. IIRC, it does a better job decoding the events from ReadConsoleInput. From lac at openend.se Mon Dec 14 13:51:45 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 14 Dec 2015 19:51:45 +0100 Subject: cannot open file with non-ASCII filename In-Reply-To: <566F0BD0.8020106@udel.edu> References: <566F0BD0.8020106@udel.edu> Message-ID: <201512141851.tBEIpjEl018009@fido.openend.se> In a message of Mon, 14 Dec 2015 13:34:56 -0500, Terry Reedy writes: >On 12/14/2015 11:24 AM, Ulli Horlacher wrote: >> With Python 2.7.11 on Windows 7 my users cannot open/read files with >> non-ASCII filenames. > >Right. They should either restrict themselves to ascii (or possibly >latin-1) filenames or use current 3.x. This is one of the (known) >unicode problems fixed in 3.x by making unicode the core text class, >replacing the implementation of unicode, and performing further work >with the new implementation. > >-- >Terry Jan Reedy > >-- >https://mail.python.org/mailman/listinfo/python-list Given that Ulli is in Germany, latin-1 is likely to work fine for him. And you do it like this: # -*- coding: latin-1 -*- from Tkinter import * root = Tk() s = 'V?lkommen till G?teborg' # Welcome to Gothenburg (where I live) u = unicode(s, 'iso8859-1') Label(root, text=u).pack() root.mainloop() Laura From tjreedy at udel.edu Mon Dec 14 14:01:03 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2015 14:01:03 -0500 Subject: Screenshots in Sphinx docs In-Reply-To: References: Message-ID: On 12/14/2015 11:31 AM, Albert-Jan Roskam wrote: > I'd like to include up-to-date screenshots (of a tkinter app) > into my Sphinx documentation. If you manually take screenshots with *any* screen grabber and save in an appropriate format, this is apparently trivial -- use the ..image directive. From the below, it appears that what you want is to have a literally up-to-date screenshot taken automatically during the doc build. This requires that one be able to automate getting the application into the exact display state one wants to capture. You can probably do that with a tkinter app if you write it with that possibility in mind. In particular, you must keep a Python reference to every widget you want to manipulate, even if not needed for normal program operation. There is also an issue with grabbing the whole screen versus only a program-specific window. > This looks ok: > https://pypi.python.org/pypi/sphinxcontrib-programscreenshot This (automatically) takes 'screenshots' on a no-screen (headless) *nix system (during doc build) by redirecting X-windows output to a pseudo-screen program. Rather clever, and system-specific. > BUT I need something that works on Windows (Python 2.7). > Can any recommend an approach? I thought about using PIL: Get the pillow fork/upgrade on pypi. > http://www.varesano.net/blog/fabio/capturing%20screen%20image%20python%20and%20pil%20windows Or look into Windows screen grabber programs, of which there are many. -- Terry Jan Reedy From mbrahimi02 at gmail.com Mon Dec 14 14:08:51 2015 From: mbrahimi02 at gmail.com (Malik Brahimi) Date: Mon, 14 Dec 2015 14:08:51 -0500 Subject: No subject Message-ID: Basically, I'm trying to make an event based system with pywin32 that handles spooled files that are to be printed. Users often print under the impression that their document has yet to emerge from the printer when it is in fact in queue. I'm creating a script that polls print jobs, saves them in a Mongo DB as needed, and prompts the user to reconsider another print job for a duplicate document. However, I'm running into some problems distinguishing documents as unique because the print job could have the same document name but the files could be in different directories. Additionally, I have no idea how to temporarily halt spooling until the user has confirmed their decision. Does anyone have any idea how to distinguish documents as unique and how to temporarily halt spooling as described? From framstag at rus.uni-stuttgart.de Mon Dec 14 17:11:05 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Mon, 14 Dec 2015 22:11:05 +0000 (UTC) Subject: cannot open file with non-ASCII filename References: <566F0BD0.8020106@udel.edu> Message-ID: Laura Creighton wrote: > Given that Ulli is in Germany, latin-1 is likely to work fine for him. For me, but not for my users. We have people from about 100 nations at our university. > And you do it like this: > > # -*- coding: latin-1 -*- > from Tkinter import * > root = Tk() > s = 'V?lkommen till G?teborg' # Welcome to Gothenburg (where I live) > u = unicode(s, 'iso8859-1') > Label(root, text=u).pack() The problem is the input of these filenames. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From vincent at vincentdavis.net Mon Dec 14 17:38:05 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 14 Dec 2015 15:38:05 -0700 Subject: Try: rather than if : Message-ID: In the code below try is used to check if handle has the attribute name. It seems an if statement could be used. Is there reason one way would be better than another? def write_header(self): handle = self.handle try: handle.write("# Report_file: %s\n" % handle.name) except AttributeError: pass handle.write("########################################\n") The specific use case I noticed this was https://github.com/biopython/biopython/blob/master/Bio/AlignIO/EmbossIO.py#L38 Vincent Davis From PointedEars at web.de Mon Dec 14 17:41:21 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 14 Dec 2015 23:41:21 +0100 Subject: cannot open file with non-ASCII filename References: <566F0BD0.8020106@udel.edu> Message-ID: <4412672.gUIyRlH8Kf@PointedEars.de> Ulli Horlacher wrote: > Laura Creighton wrote: >> Given that Ulli is in Germany, latin-1 is likely to work fine for him. > > For me, but not for my users. We have people from about 100 nations at our > university. > [?] > The problem is the input of these filenames. Why do you have to use msvcrt? I would use curses for user input, but: ,- ,- | | No one has made a Windows port of the curses module. On a Windows | platform, try the Console module written by Fredrik Lundh. The Console | module provides cursor-addressable text output, plus full support for | mouse and keyboard input, and is available from | http://effbot.org/zone/console-index.htm. So you should try that instead. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From ian.g.kelly at gmail.com Mon Dec 14 18:12:26 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 14 Dec 2015 16:12:26 -0700 Subject: Try: rather than if : In-Reply-To: References: Message-ID: On Mon, Dec 14, 2015 at 3:38 PM, Vincent Davis wrote: > In the code below try is used to check if handle has the attribute name. It > seems an if statement could be used. Is there reason one way would be > better than another? http://www.oranlooney.com/lbyl-vs-eafp/ From cs at zip.com.au Mon Dec 14 18:14:20 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 15 Dec 2015 10:14:20 +1100 Subject: Try: rather than if : In-Reply-To: References: Message-ID: <20151214231420.GA20631@cskk.homeip.net> On 14Dec2015 15:38, Vincent Davis wrote: >In the code below try is used to check if handle has the attribute name. It >seems an if statement could be used. Only by using hasattr(), which IIRC does a try/except internally. >Is there reason one way would be >better than another? try/except is more directly, but hasattr() is shorter. However, consider this: I would write your example: > try: > handle.write("# Report_file: %s\n" % handle.name) > except AttributeError: > pass > handle.write("########################################\n") as: try: write = handle.write except AttributeError: pass # or complain else: write("# Report_file: %s\n" % handle.name) write("########################################\n") Two things: First, notice that the code inside the try/except _only_ fetches the attribute. Your version calls the "write" attribute, and also accesses handle.name. Either of those might also emit AttributeError, and should probably not be silently caught. Second, notice that as a side effect of the: write = handle.write line we now have the attribute value. If it were an if: if hasattr(handle, 'write'): write = handle.write ... write messages now ... which is two steps to test and get the attribute. Feels... clunky. Perhaps partly because of the scope of a spelling error between the "'write'" string and the "handle.write" use below it, but clunky anyway. Which to use depends on how you weigh readability and directness. But try to get decide how mugh of your "if" preference is personal uncomfortableness with try/except (for whatever reasons), and then how much those reasons may be generally applicable or a personal foible. But it is your code, your call. What reads better to your eye? Cheers, Cameron Simpson From ben+python at benfinney.id.au Mon Dec 14 18:19:38 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 15 Dec 2015 10:19:38 +1100 Subject: EAFP and LBYL (was: Try: rather than if :) References: Message-ID: <85d1u84nzp.fsf@benfinney.id.au> Vincent Davis writes: > In the code below try is used to check if handle has the attribute name. It > seems an if statement could be used. Is there reason one way would be > better than another? The Python community refers to the difference by contrasting ?look before you leap? (LBYL) versus ?easier to ask forgiveness than permission? (EAFP), and tends to prefer the latter. ?It is easier to ask forgiveness than permission? is attributed to computer programming legend Rear Admiral Grace Hopper (she who documented the first actual computer bug ? a large moth in the wires). Alex Martelli explores when LBYL and EAFP are each appropriate in Python . -- \ ?The optimist thinks this is the best of all possible worlds. | `\ The pessimist fears it is true.? ?J. Robert Oppenheimer | _o__) | Ben Finney From vincent at vincentdavis.net Mon Dec 14 18:48:58 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 14 Dec 2015 16:48:58 -0700 Subject: Try: rather than if : In-Reply-To: <20151214231420.GA20631@cskk.homeip.net> References: <20151214231420.GA20631@cskk.homeip.net> Message-ID: On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson wrote: > First, notice that the code inside the try/except _only_ fetches the > attribute. Your version calls the "write" attribute, and also accesses > handle.name. Either of those might also emit AttributeError, and should > probably not be silently caught. > ?I think the intent of the original code was to check if handle had the attribute "name", I don't think the attribute "write" was the issue. So then possibly this based on your suggestion: try: write = handel.write except AttributeError: raise try: name = handel.name write("# Report_file: %s\n" % name) except AttributeError: pass write("########################################\n") Vincent Davis 720-301-3003 From rosuav at gmail.com Mon Dec 14 18:51:54 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 15 Dec 2015 10:51:54 +1100 Subject: Try: rather than if : In-Reply-To: References: <20151214231420.GA20631@cskk.homeip.net> Message-ID: On Tue, Dec 15, 2015 at 10:48 AM, Vincent Davis wrote: > try: > write = handel.write > except AttributeError: > raise Just "write = handel.write" :) ChrisA From ian.g.kelly at gmail.com Mon Dec 14 18:53:49 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 14 Dec 2015 16:53:49 -0700 Subject: Try: rather than if : In-Reply-To: References: <20151214231420.GA20631@cskk.homeip.net> Message-ID: On Mon, Dec 14, 2015 at 4:48 PM, Vincent Davis wrote: > On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson wrote: > >> First, notice that the code inside the try/except _only_ fetches the >> attribute. Your version calls the "write" attribute, and also accesses >> handle.name. Either of those might also emit AttributeError, and should >> probably not be silently caught. >> > > I think the intent of the original code was to check if handle had the > attribute "name", I don't think the attribute "write" was the issue. > > So then possibly this based on your suggestion: > try: > write = handel.write > except AttributeError: > raise Except that catching an exception just to immediately re-raise it is silly. This would be better: try: name = handle.name except AttributeError: pass else: handle.write("# Report_file: %s\n" % name) From eryksun at gmail.com Mon Dec 14 18:55:04 2015 From: eryksun at gmail.com (eryk sun) Date: Mon, 14 Dec 2015 17:55:04 -0600 Subject: cannot open file with non-ASCII filename In-Reply-To: <20151214221751.GM12472@rus.uni-stuttgart.de> References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: On Mon, Dec 14, 2015 at 4:17 PM, Ulli Horlacher wrote: > > ImportError: No module named pyreadline > > Is it a python 3.x module? > > I am limited to Python 2.7 pyreadline is available for 2.7-3.5 on PyPI. Anyway, I tried it to no avail. When dropping a file path into the console it ignores the alt-numpad sequences that get queued for non-ASCII characters, just like mvcrt.getwch. If you decide to roll your own getwch via ctypes or PyWin32, I suggest starting a new topic on the ctypes list or Windows list. From lac at openend.se Mon Dec 14 19:07:49 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 15 Dec 2015 01:07:49 +0100 Subject: cannot open file with non-ASCII filename In-Reply-To: <4412672.gUIyRlH8Kf@PointedEars.de> References: <566F0BD0.8020106@udel.edu> <4412672.gUIyRlH8Kf@PointedEars.de> Message-ID: <201512150007.tBF07nMo021611@fido.openend.se> In a message of Mon, 14 Dec 2015 23:41:21 +0100, "Thomas 'PointedEars' Lahn" wr ites: >Why do you have to use msvcrt? > >I would use curses for user input, but: > >,- >,- >| >| No one has made a Windows port of the curses module. On a Windows >| platform, try the Console module written by Fredrik Lundh. The Console >| module provides cursor-addressable text output, plus full support for >| mouse and keyboard input, and is available from >| http://effbot.org/zone/console-index.htm. > >So you should try that instead. If going for curses, I'd try this instead: http://pdcurses.sourceforge.net/ Laura From lac at openend.se Mon Dec 14 19:13:18 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 15 Dec 2015 01:13:18 +0100 Subject: cannot open file with non-ASCII filename In-Reply-To: References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: <201512150013.tBF0DI4L021859@fido.openend.se> In a message of Mon, 14 Dec 2015 17:55:04 -0600, eryk sun writes: >On Mon, Dec 14, 2015 at 4:17 PM, Ulli Horlacher > wrote: >> >> ImportError: No module named pyreadline >> >> Is it a python 3.x module? >> >> I am limited to Python 2.7 > >pyreadline is available for 2.7-3.5 on PyPI. Anyway, I tried it to no >avail. When dropping a file path into the console it ignores the >alt-numpad sequences that get queued for non-ASCII characters, just >like mvcrt.getwch. If you decide to roll your own getwch via ctypes or >PyWin32, I suggest starting a new topic on the ctypes list or Windows >list. >-- >https://mail.python.org/mailman/listinfo/python-list PyPy wrote its own pyreadline. You can get it here. https://bitbucket.org/pypy/pyrepl And see if it works any better. Laura From vincent at vincentdavis.net Mon Dec 14 19:20:57 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 14 Dec 2015 17:20:57 -0700 Subject: Try: rather than if : In-Reply-To: References: <20151214231420.GA20631@cskk.homeip.net> Message-ID: On Mon, Dec 14, 2015 at 4:53 PM, Ian Kelly wrote: > > Except that catching an exception just to immediately re-raise it is > silly. This would be better: > > try: > name = handle.name > except AttributeError: > pass > else: > handle.write("# Report_file: %s\n" % name) ?Ya that would be silly. Thanks? everyone for the education. From rantingrickjohnson at gmail.com Mon Dec 14 21:33:40 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 14 Dec 2015 18:33:40 -0800 (PST) Subject: Is vars() the most useless Python built-in ever? In-Reply-To: <566ba636$0$1589$c3e8da3$5496439d@news.astraweb.com> References: <565cf141$0$1612$c3e8da3$5496439d@news.astraweb.com> <4f0f7fc5-c93a-4223-9c05-e192a8fafbbd@googlegroups.com> <565d5282$0$14486$c3e8da3@news.astraweb.com> <11a610aa-41d8-433c-b36b-e23ba4d83243@googlegroups.com> <566ba636$0$1589$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, December 11, 2015 at 10:45:02 PM UTC-6, Steven D'Aprano wrote: > On Sat, 12 Dec 2015 09:13 am, Rick Johnson wrote: > > > Intuitiveness and productivity have a > > synergy like peas and carrots! One cannot be productive if one is fighting > > an unintuitive interface. Could you drive with your toes? How about your > > tongue? > > Drive a car with my tongue? Perhaps not, but I could drive a car with my > mouth if it were equipped with a sufficiently powerful interface. > > "Driver, please take me to the airport." Sorry Steven, but that command will not be executed. First you must say: "Ok Google". ;-) Even google is not insane enough to write software that attempts interpretation of every spoken within ear-shot of it. But your interface has an even greater problem: since software cannot yet read minds, and since most metropolitan areas contain more than one airport, you may want to be more specific than "take me to the airport". Heck, why not follow that one with "take me shopping". ;-) Not only have you demonstrated that your "mock interface" is un-intuitive, your commands are so implicit that the banter between human<->software is likely to descend into a sad parody of Abbott and Costello! > > Sure, even the most atrocious interface can be "learned", but what i > > cannot understand, except in the case of you being a contrarian, is why > > you would argue *AGAINST* intuitive interfaces? And believe it or not, > > *SYNTAX* is an interface! As are paradigms! > > I do believe that you are arguing against a strawman. I don't think that > anyone here has argued *against* "intuitiveness", all else being equal. But > you are glossing over a whole lot of real complexity: > > - what makes you think all else actually is equal? > > - who decides what is intuitive and what isn't? why should we take > your word over what's intuitive and what isn't? > > - intuitive for who? my dad, who has never used a computer? my mum, > who has used a computer but only for word processing and web > browsing? a ten year old maths prodigy? a thirty year veteran > of C programming? a beginner to programming with a month's > experience in PHP? > > - what level of power are we willing to forgo in order to keep > the language "intuitive"? > > - what the hell does "intuitive" mean anyway? Who's needs Abbott! Listen Steven, the litmus test for intuitiveness is simple: if the overwhelming majority of the users find it to be intuitive during the learning process, then your interface is intuitive. That's it. > I know what the definition of the word is, but it doesn't apply to > programming language interfaces. As has been pointed out many times, the > only truly intuitive interface is the nipple. Everything else has to be > learned. And what experience do *YOU* have with breast feeding that would in any way qualify *YOU* to make such an assertion? > In practice, "intuitive interface" gets bandied about in two ways: > > (1) Some people use it as a thought-terminating cliche. What they really > mean is that they want this interface feature, for reasons of their own, > and by calling it 'intuitive', they hope to bamboozle or intimidate others > into backing down and accepting the feature. Who could possibly be > against "intuitive" interfaces? That's like being against "usefulness", > or "flexibility". > > When people start protesting about others being "against intuitive > interfaces" (especially if they SHOUT the word "against", that's an good > sign that they're using it as a thought-terminating cliche. To these > people, "intuitive" is like "New And Improved!!!" to advertisers. > > (2) Others use it to mean an interface which is: > > * predictable; > * consistent; > * easy to explore and learn; > * and "easy to use" in some vague sense. This last comparison looks an awful lot like a straw-man Steven. Nice. Extra points for painting me as a bully, and then using my exact definition of intuitiveness but applying it to the "friendly challenger". Your sleight of hand is impressive my friend. > [...] > > And most importantly, they recognize that programmers are beginners for > perhaps 1% of their programming life: you might be completely new to > programming for three months out of a 30 year span of programming. Why > optimize the language for something that you will use for less than 1% of > your productive lifespan? Apart from intentional beginner's languages like > Scratch, for most languages it makes sense to add power even if it > increases the learning curve. I can assure you that complexity is not sacrificed when we design interfaces to be intuitive. And to illustrate, we need look no further than the automobile for a fine example. The interface for driving a car is not only intuitive, it is consistent! It is intuitive because it exposes a small number of high level operator components: the steering wheel, the brake petal, and the accelerator petal. And it is consistent because no matter what brand or model you choose to drive, *ALL* of them will expose these same three components. *Heck, even when observing the differences between British and American driver position (left side versus right side), the components are still the same! Now, even though all automobiles expose an interface of only three high level components, the range of power is vast. Because the power is not defined inside the *CONTROLS*, no, the power is *ABSTRACTED* away under the hood, and the controls are merely methods of wielding the power. We can observe this elegance, and broad range of power, by observing that, not only can a small child putt around in a toy car in the front yard with great ease, but a Formula One race car driver can push an advanced power-train to the limits of physics! From the nostalgic joy of a treasured childhood toy, to the harsh grind of daily commuting, to the bleeding edge of high performance motorsports, the interface remains the same. But the most important aspect of this great design to observe, is that, the power and the interface are two separate components. Alone they cannot do much, but when linked together in a master/slave relationship, they become the basis of the "relegation of logical abstractions". The secret to great software design is realizing that it is the layers of abstraction that exist *underneath* intuitive interfaces which provide scale-able power on demand. (RETORT_1) The "idea" that intuitive interfaces are only useful for "toy programs" is complete rubbish. Trying to blame performance issues on an interface is like driving a toy car on the interstate at 0.2 miles per hour, and then suing drivers who accidentally plow over you. Poor performance is a result of poor design choice. The absurdity of expecting a toy car to perform at highway speeds is only overshadowed by the absurdity of blaming the accelerator petal for the lack of power! (RETORT_2) The "idea" that experienced users are limited by intuitive interfaces is also rubbish. When abstractions are properly layered, many levels of interfacing will be exposed. Our goal should not be to create the highest level interface, but instead, the highest layer of the interfacing *CAKE*! If the experienced programmer feels that the highest layer is too confining, then all he needs to do is drop-into a lower level interface. Using our car example, if we wanted to gain more power, we would modify the engine (we could inject more air/fuel, or use a more volatile fuel). But this type of modification is not possible for the new user, so we must provide the high levels, while maintaining multiple lower levels of interfacing. But most importantly, we *MUST* maintain a layered cake model. Abstractions built on abstractions. From rxjwg98 at gmail.com Mon Dec 14 21:43:08 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 14 Dec 2015 18:43:08 -0800 (PST) Subject: Question about figure plot Message-ID: Hi, When I run the following code, there is no figure shown in the end. ////////// import pymc import numpy as np n = 5*np.ones(4,dtype=int) x = np.array([-.86,-.3,-.05,.73]) alpha = pymc.Normal('alpha',mu=0,tau=.01) beta = pymc.Normal('beta',mu=0,tau=.01) @pymc.deterministic def theta(a=alpha, b=beta): """theta = logit^{-1}(a+b)""" return pymc.invlogit(a+b*x) d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\ observed=True) .... import pymc import mymodel S = pymc.MCMC(mymodel, db='pickle') S.sample(iter=10000, burn=5000, thin=2) pymc.Matplot.plot(S) I find that the figures are shown after these two lines by myself: ************* import matplotlib.pyplot as plt plt.show() I have searched around and have not found some explanation about it. The plot function here is different from Matlab's. Is there better ways than my last two lines? (I am not confident whether my last two lines is the only choice. Thanks, From eryksun at gmail.com Mon Dec 14 22:20:18 2015 From: eryksun at gmail.com (eryk sun) Date: Mon, 14 Dec 2015 21:20:18 -0600 Subject: cannot open file with non-ASCII filename In-Reply-To: <201512150007.tBF07nMo021611@fido.openend.se> References: <566F0BD0.8020106@udel.edu> <4412672.gUIyRlH8Kf@PointedEars.de> <201512150007.tBF07nMo021611@fido.openend.se> Message-ID: On Mon, Dec 14, 2015 at 6:07 PM, Laura Creighton wrote: > In a message of Mon, 14 Dec 2015 23:41:21 +0100, "Thomas 'PointedEars' Lahn" wr > ites: > >>Why do you have to use msvcrt? >> >>I would use curses for user input, but: >> >>,- >>,- >>| >>| No one has made a Windows port of the curses module. On a Windows >>| platform, try the Console module written by Fredrik Lundh. The Console >>| module provides cursor-addressable text output, plus full support for >>| mouse and keyboard input, and is available from >>| http://effbot.org/zone/console-index.htm. >> >>So you should try that instead. > > If going for curses, I'd try this instead: > http://pdcurses.sourceforge.net/ Christoph Gohlke has an extension module based on PDCurses [1]. The good news for Python 3 users is that it uses the [W]ide-character console API, such as ReadConsoleInputW. Also, its _get_key_count [2] function is designed to support the alt numpad event sequences that the system creates for the input filepath when dragging a file into the console. In my limited testing, dragging filepaths from Explorer worked without a hitch using a random Latin-1 name "???????????" and a Latin Extended-B name "????????????". Unfortunately the Python 2.7 version is linked against the [A]NSI API, which maps each Unicode character to either the closest matching character in the console's codepage or "?". Moreover the PDCurses code has a bug in narrow builds in that it returns the UnicodeChar from the KEY_EVENT_RECORD [3] instead of the AsciiChar (the name is a misnomer). In this case the high byte is junk. You can mask it out using a bitwise & with 0xFF. That said, IIRC, the OP wants to avoid using any frameworks such as curses or a GUI toolkit. [1]: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses [2]: https://github.com/wmcbrine/PDCurses/blob/PDCurses_3_4/win32/pdckbd.c#L259 [3]: https://msdn.microsoft.com/en-us/library/ms684166 From cs at zip.com.au Tue Dec 15 01:11:19 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 15 Dec 2015 17:11:19 +1100 Subject: Try: rather than if : In-Reply-To: References: Message-ID: <20151215061119.GA14163@cskk.homeip.net> On 14Dec2015 16:48, Vincent Davis wrote: >On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson wrote: > >> First, notice that the code inside the try/except _only_ fetches the >> attribute. Your version calls the "write" attribute, and also accesses >> handle.name. Either of those might also emit AttributeError, and should >> probably not be silently caught. >> > >?I think the intent of the original code was to check if handle had the >attribute "name", I don't think the attribute "write" was the issue. I have to say that this was not at all evident to me. I think that also argues for putting the smallest possible bit of code inside the try/except. >So then possibly this based on your suggestion: >try: > write = handel.write >except AttributeError: > raise Someone has already suggested dropping the try/except altogether for this. >try: > name = handel.name > write("# Report_file: %s\n" % name) >except AttributeError: > pass Again, I would minimise the stuff in the try/except, so: try: name = handle.name except AttributeError: pass else: write("# Report_file: %s\n" % name) But in this case, in my code, I do two things: Firstly, things needing names always get one: class Foo: def __init__(self, blah, name=None): if name is None: name = "Foo-%s" % (id(self),) self.name = name Secondly, for your use case "print the name if it has one" I _would_ use hasattr: if hasattr(handle, name): write("# Report_file: %s\n" % name) The logic feels far clearer to my eye. Cheers, Cameron Simpson From cs at zip.com.au Tue Dec 15 01:16:31 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 15 Dec 2015 17:16:31 +1100 Subject: Try: rather than if : In-Reply-To: <20151215061119.GA14163@cskk.homeip.net> References: <20151215061119.GA14163@cskk.homeip.net> Message-ID: <20151215061631.GA53282@cskk.homeip.net> On 15Dec2015 17:11, Cameron Simpson wrote: >On 14Dec2015 16:48, Vincent Davis wrote: [...] >>?I think the intent of the original code was to check if handle had the >>attribute "name", I don't think the attribute "write" was the issue. [...] >Secondly, for your use case "print the name if it has one" I _would_ use >hasattr: > > if hasattr(handle, name): > write("# Report_file: %s\n" % name) On reflection, there's also this: name = getattr(handle, 'name', repr(handle)) write("# Report_file: %s\n" % name) i.e. _always_ identfy the handle, even if it has no nice name. Cheers, Cameron Simpson From aezhil90 at gmail.com Tue Dec 15 02:29:10 2015 From: aezhil90 at gmail.com (Ezhilarasan Chandrasekar) Date: Tue, 15 Dec 2015 12:59:10 +0530 Subject: Need help - How to identify the cell display format? Message-ID: Hi folks, I just want to find the cell display format in Excel. I have a Expected excel file and Actual Excel file. I have some knowledge about, how to check the cell value, cell font, alignment. But I also want to know about what type of cell format is being used. For example: If the cell value has "*04:05:00 AM*", but it displays as " *04:05:00*"(AM notation not needed) which is of format "*hh:mm:ss*" I want to identify the cell format *(hh:mm:ss)* from Expected Excel file and compare with the Actual Excel file Please help me! -- Warm regards, Ezhilarasan From framstag at rus.uni-stuttgart.de Tue Dec 15 03:26:37 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 08:26:37 +0000 (UTC) Subject: cannot open file with non-ASCII filename References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: Laura Creighton wrote: > PyPy wrote its own pyreadline. > You can get it here. https://bitbucket.org/pypy/pyrepl As far as I can see, it has no getkey function. My users do not hit ENTER after drag&drop or copy&paste files. I need an input function with a timeout. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From gvm2121 at gmail.com Tue Dec 15 06:53:31 2015 From: gvm2121 at gmail.com (Gonzalo V) Date: Tue, 15 Dec 2015 07:53:31 -0400 Subject: Need help - How to identify the cell display format? In-Reply-To: References: Message-ID: Are you working with time series? saludos, desde un m?vil. El dic 15, 2015 9:41 a.m., "Ezhilarasan Chandrasekar" escribi?: > Hi folks, > > I just want to find the cell display format in Excel. I have a Expected > excel file and Actual Excel file. > > I have some knowledge about, how to check the cell value, cell font, > alignment. But I also want to know about what type of cell format is being > used. > > For example: If the cell value has "*04:05:00 AM*", but it displays as " > *04:05:00*"(AM notation not needed) which is of format "*hh:mm:ss*" > > I want to identify the cell format *(hh:mm:ss)* from Expected Excel file > and compare with the Actual Excel file > > Please help me! > > -- > Warm regards, > Ezhilarasan > -- > https://mail.python.org/mailman/listinfo/python-list > From jeanmichel at sequans.com Tue Dec 15 07:19:20 2015 From: jeanmichel at sequans.com (jmp) Date: Tue, 15 Dec 2015 13:19:20 +0100 Subject: Try: rather than if : In-Reply-To: References: Message-ID: On 12/14/2015 11:38 PM, Vincent Davis wrote: > In the code below try is used to check if handle has the attribute name. It > seems an if statement could be used. Is there reason one way would be > better than another? > > def write_header(self): > handle = self.handle > try: > handle.write("# Report_file: %s\n" % handle.name) > except AttributeError: > pass > handle.write("########################################\n") > > The specific use case I noticed this was > https://github.com/biopython/biopython/blob/master/Bio/AlignIO/EmbossIO.py#L38 > > Vincent Davis > Nothing wrong with the try block. However other forms may be shorter/more readable. Since there is 2 attribute lookups in the try block, (write and name) it's not clear which one you want to catch (except for the line following the except clause but it could not be the case). Here are 2 alternative forms 1/ handle.write(handle.name if hasattr(handle, 'name') else '') 2/ handle.write(getattr(handle, 'name', '')) Here's the best solution imo: 3/ assume handle has always a name attribute and don't write code handling attribute existence. Instead handle the attribute values: class Handle: def __init__(self): self.name= None # and the problem is gone if handle.name : handle.write(handle.name) By the way, in the use case you've linked, it is written 'handle = self.handle' at every beginning of each method. Don't follow that rule. Jm From brisher777 at gmail.com Tue Dec 15 07:37:57 2015 From: brisher777 at gmail.com (Benjamin Risher) Date: Tue, 15 Dec 2015 04:37:57 -0800 (PST) Subject: wrapper api / proxying third party exception? Message-ID: <77743c9d-8554-4b76-b3b3-8d35cf894905@googlegroups.com> Ok, here's my issue. I have a plugin framework I wrote that relies on a third party library that I can't change. As a part of that framework, I wrote a small stub library to proxy calls to the third party library, so that if their api ever changes, plugins written against the stub won't have to change, I'll just have to update the back-half that interfaces with the library. I think this is called an adapter design pattern...? plugin --> my api --> their api --> their library It works, for the most part. Most of my classes look similar to this class MYClass: def __init__(self, *args, **kwargs): self.__theirclass = TheirClass(*args, **kwargs) def __getattr__(self, attr): return getattr(self.__theirclass, attr) What I'm having issue with, is their exception class. 1. A plugin calls a stub in my library 2. That stub calls the corresponding call in the third party library 3. The call raises an exception from the library 4. The plugin can't catch the exception without importing directly from the third party library What is the correct way to allow plugins to import my stub exception, but catch the ones raised by the library? I was looking at monkeying with subclasshook or something along those lines, but it doesn't seem like the best approach. Hoping for some help from here. Please let me know if you need any clarification to help! Thank you. From framstag at rus.uni-stuttgart.de Tue Dec 15 07:51:24 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 12:51:24 +0000 (UTC) Subject: subprocess.call with non-ASCII arguments? Message-ID: I want to create a zip file within a Python 2.7 program on windows. My code: cmd = ['7za.exe','a','-tzip',archive] + files status = subprocess.call(cmd) leads to: File "fexit.py", line 971, in sendfile_retry status = subprocess.call(cmd) File "C:\Python27\lib\subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 710, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 958, in _execute_child startupinfo) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 87: ordinal not in range(128) This is because the array "files" contains filenames with non-ASCII characters. So, the problem is in subprocess.py, which I cannot modify. What can I do? -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From stephane at wirtel.be Tue Dec 15 08:54:05 2015 From: stephane at wirtel.be (Stephane Wirtel) Date: Tue, 15 Dec 2015 14:54:05 +0100 Subject: Urgent: Last call for the CfP of PythonFOSDEM 2016 Message-ID: <20151215135405.GA32632@sg1> Hi all Because the deadline is imminent and because we have only received some proposals, we have extended the current deadline. The new submission deadline is 2015-12-20. Call For Proposals ================== This is the official call for sessions for the Python devroom at FOSDEM 2016. FOSDEM is the Free and Open source Software Developers' European Meeting, a free and non-commercial two-day week-end that offers open source contributors a place to meet, share ideas and collaborate. It's the biggest event in Europe with +5000 hackers, +400 speakers. For this edition, Python will be represented by its Community. If you want to discuss with a lot of Python Users, it's the place to be! Important dates =============== * Submission deadlines: 2015-12-20 * Acceptance notifications: 2015-12-24 Practical ========= * The duration for talks will be 30 minutes, including presentations and questions and answers. * Presentation can be recorded and streamed, sending your proposal implies giving permission to be recorded. * A mailing list for the Python devroom is available for discussions about devroom organisation. You can register at this address: https://lists.fosdem.org/listinfo/python-devroom How to submit ============= All submissions are made in the Pentabarf event planning tool at https://penta.fosdem.org/submission/FOSDEM16 When submitting your talk in Pentabarf, make sure to select the Python devroom as the Track. Of course, if you already have a user account, please reuse it. Questions ========= Any questions, please sned an email to info AT python-fosdem DOT org Thank you for submitting your sessions and see you soon in Brussels to talk about Python. If you want to keep informed for this edition, you can follow our twitter account @PythonFOSDEM. * FOSDEM 2016: https://fosdem.org/2016 * Python Devroom: http://python-fosdem.org * Twitter: https://twitter.com/PythonFOSDEM Thank you so much, Stephane -- St?phane Wirtel - http://wirtel.be - @matrixise From stephane at wirtel.be Tue Dec 15 08:57:56 2015 From: stephane at wirtel.be (Stephane Wirtel) Date: Tue, 15 Dec 2015 14:57:56 +0100 Subject: Urgent: Last call for the CfP of PythonFOSDEM 2016 Message-ID: <20151215135756.GA1160@sg1> Hi all Because the deadline is imminent and because we have only received some proposals, we have extended the current deadline. The new submission deadline is 2015-12-20. Call For Proposals ================== This is the official call for sessions for the Python devroom at FOSDEM 2016. FOSDEM is the Free and Open source Software Developers' European Meeting, a free and non-commercial two-day week-end that offers open source contributors a place to meet, share ideas and collaborate. It's the biggest event in Europe with +5000 hackers, +400 speakers. For this edition, Python will be represented by its Community. If you want to discuss with a lot of Python Users, it's the place to be! Important dates =============== * Submission deadlines: 2015-12-20 * Acceptance notifications: 2015-12-24 Practical ========= * The duration for talks will be 30 minutes, including presentations and questions and answers. * Presentation can be recorded and streamed, sending your proposal implies giving permission to be recorded. * A mailing list for the Python devroom is available for discussions about devroom organisation. You can register at this address: https://lists.fosdem.org/listinfo/python-devroom How to submit ============= All submissions are made in the Pentabarf event planning tool at https://penta.fosdem.org/submission/FOSDEM16 When submitting your talk in Pentabarf, make sure to select the Python devroom as the Track. Of course, if you already have a user account, please reuse it. Questions ========= Any questions, please sned an email to info AT python-fosdem DOT org Thank you for submitting your sessions and see you soon in Brussels to talk about Python. If you want to keep informed for this edition, you can follow our twitter account @PythonFOSDEM. * FOSDEM 2016: https://fosdem.org/2016 * Python Devroom: http://python-fosdem.org * Twitter: https://twitter.com/PythonFOSDEM Thank you so much, Stephane -- St?phane Wirtel - http://wirtel.be - @matrixise From larry.martell at gmail.com Tue Dec 15 09:04:24 2015 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 15 Dec 2015 09:04:24 -0500 Subject: Need help - How to identify the cell display format? In-Reply-To: References: Message-ID: On Tue, Dec 15, 2015 at 2:29 AM, Ezhilarasan Chandrasekar wrote: > Hi folks, > > I just want to find the cell display format in Excel. I have a Expected > excel file and Actual Excel file. > > I have some knowledge about, how to check the cell value, cell font, > alignment. But I also want to know about what type of cell format is being > used. > > For example: If the cell value has "*04:05:00 AM*", but it displays as " > *04:05:00*"(AM notation not needed) which is of format "*hh:mm:ss*" > > I want to identify the cell format *(hh:mm:ss)* from Expected Excel file > and compare with the Actual Excel file You can do this with openpyxl, for example: from openpyxl.reader.excel import load_workbook book = load_workbook(filename='transactions.xlsx') sheet = book.get_sheet_by_name('transactions') print sheet.cell("A12").style.number_format print sheet.cell("A13").style.number_format From lac at openend.se Tue Dec 15 09:09:16 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 15 Dec 2015 15:09:16 +0100 Subject: cannot open file with non-ASCII filename In-Reply-To: References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: <201512151409.tBFE9GSM031481@fido.openend.se> In a message of Tue, 15 Dec 2015 08:26:37 +0000, Ulli Horlacher writes: >Laura Creighton wrote: > >> PyPy wrote its own pyreadline. >> You can get it here. https://bitbucket.org/pypy/pyrepl > >As far as I can see, it has no getkey function. >My users do not hit ENTER after drag&drop or copy&paste files. >I need an input function with a timeout. Right, then this isn't going to work. Sorry about that. Laura From framstag at rus.uni-stuttgart.de Tue Dec 15 09:25:50 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 14:25:50 +0000 (UTC) Subject: subprocess.call with non-ASCII arguments? Message-ID: (My first posting seems to got lost) I want to create a zip file within a Python 2.7 program on windows. My code: cmd = ['7za.exe','a','-tzip',archive] + files status = subprocess.call(cmd) leads to: File "fexit.py", line 971, in sendfile_retry status = subprocess.call(cmd) File "C:\Python27\lib\subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 710, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 958, in _execute_child startupinfo) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 87: ordinal not in range(128) This is because the array "files" contains filenames with non-ASCII characters. So, the problem is in subprocess.py, which I cannot modify. Instead of calling a 7z subprocess with non-ASCII arguments I tried to call it with a listfile: it starts with a "@" and contains the names of the files to be packed into the arcive. It is a special 7z feature. New code: fileslist = archive + '.list' flo = open(fileslist,'w') for file in files: print(file,file=flo) flo.close() cmd = ['7za.exe','a','-tzip',archive,'@'+fileslist] status = subprocess.call(cmd) But with that I get a new error: File "fexit.py", line 959, in sendfile_retry for file in files: print(file,file=flo) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 8: ordinal not in range(128) I get the same error message, when i use: flo = open(fileslist,'wb') How can I tell open() or print() that I want to write non-ASCII ? -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From framstag at rus.uni-stuttgart.de Tue Dec 15 10:05:00 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 15:05:00 +0000 (UTC) Subject: subprocess.call with non-ASCII arguments? References: Message-ID: Ulli Horlacher wrote: > Instead of calling a 7z subprocess with non-ASCII arguments I tried to > call it with a listfile: it starts with a "@" and contains the names of > the files to be packed into the arcive. It is a special 7z feature. > > New code: > > fileslist = archive + '.list' > flo = open(fileslist,'w') > for file in files: print(file,file=flo) > flo.close() > cmd = ['7za.exe','a','-tzip',archive,'@'+fileslist] > status = subprocess.call(cmd) > > > But with that I get a new error: > > File "fexit.py", line 959, in sendfile_retry > for file in files: print(file,file=flo) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 8: > ordinal not in range(128) I found a partial solution: for file in files: print(file.encode('utf8'),file=flo) But this works only for files I get from Tk askopenfilename(), not for files from sys.argv[] Then I see: S:\>python fexit.py -a x.zip C:\Users\admin\_X?X.exe . files selected: "C:\Users\admin\_X?X.exe" 2015-12-07 16:17:15 114 kB Traceback (most recent call last): File "fexit.py", line 2166, in wexit(main()) File "fexit.py", line 260, in main status = sendfile_retry(files,recipient,comment) File "fexit.py", line 959, in sendfile_retry for file in files: print(file.encode('utf8'),file=flo) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 17: ordinal not in range(128) -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From lac at openend.se Tue Dec 15 10:08:23 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 15 Dec 2015 16:08:23 +0100 Subject: subprocess.call with non-ASCII arguments? In-Reply-To: References: Message-ID: <201512151508.tBFF8NHQ032721@fido.openend.se> In a message of Tue, 15 Dec 2015 14:25:50 +0000, Ulli Horlacher writes: >(My first posting seems to got lost) > >I want to create a zip file within a Python 2.7 program on windows. > >My code: > > cmd = ['7za.exe','a','-tzip',archive] + files > status = subprocess.call(cmd) > >leads to: > > File "fexit.py", line 971, in sendfile_retry > status = subprocess.call(cmd) > File "C:\Python27\lib\subprocess.py", line 522, in call > return Popen(*popenargs, **kwargs).wait() > File "C:\Python27\lib\subprocess.py", line 710, in __init__ > errread, errwrite) > File "C:\Python27\lib\subprocess.py", line 958, in _execute_child > startupinfo) >UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 87: > ordinal not in range(128) > > >This is because the array "files" contains filenames with non-ASCII >characters. > >So, the problem is in subprocess.py, which I cannot modify. > > >Instead of calling a 7z subprocess with non-ASCII arguments I tried to >call it with a listfile: it starts with a "@" and contains the names of >the files to be packed into the arcive. It is a special 7z feature. > >New code: > > fileslist = archive + '.list' > flo = open(fileslist,'w') > for file in files: print(file,file=flo) > flo.close() > cmd = ['7za.exe','a','-tzip',archive,'@'+fileslist] > status = subprocess.call(cmd) > > >But with that I get a new error: > > File "fexit.py", line 959, in sendfile_retry > for file in files: print(file,file=flo) >UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 8: > ordinal not in range(128) > > >I get the same error message, when i use: > flo = open(fileslist,'wb') > > >How can I tell open() or print() that I want to write non-ASCII ? see if setting the environment variable PYTHONIOENCODING https://docs.python.org/2/using/cmdline.html works for you. No promises, not a windows user. Laura From robert.kern at gmail.com Tue Dec 15 10:22:14 2015 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 15 Dec 2015 15:22:14 +0000 Subject: Question about figure plot In-Reply-To: References: Message-ID: On 2015-12-15 02:43, Robert wrote: > Hi, > > When I run the following code, there is no figure shown in the end. > > > ////////// > import pymc > import numpy as np > > n = 5*np.ones(4,dtype=int) > x = np.array([-.86,-.3,-.05,.73]) > > alpha = pymc.Normal('alpha',mu=0,tau=.01) > beta = pymc.Normal('beta',mu=0,tau=.01) > > @pymc.deterministic > def theta(a=alpha, b=beta): > """theta = logit^{-1}(a+b)""" > return pymc.invlogit(a+b*x) > > d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\ > observed=True) > .... > import pymc > import mymodel > > S = pymc.MCMC(mymodel, db='pickle') > S.sample(iter=10000, burn=5000, thin=2) > pymc.Matplot.plot(S) > > > > I find that the figures are shown after these two lines by myself: > ************* > import matplotlib.pyplot as plt > plt.show() > > I have searched around and have not found some explanation about it. > The plot function here is different from Matlab's. Is there better ways than > my last two lines? (I am not confident whether my last two lines is the > only choice. No, that's right. pymc.Matplot.plot() uses matplotlib's pyplot API underneath. pyplot can run in two different modes: interactive and non-interactive. When used in a standalone script, like I assume here, it defaults to non-interactive. That means that it will not raise any plot windows until you call plt.show(). http://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode See any of the examples here (note: "pylab" is the essentially the same as "pyplot" for these purposes): http://matplotlib.org/examples/pylab_examples/index.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From eryksun at gmail.com Tue Dec 15 10:34:17 2015 From: eryksun at gmail.com (eryk sun) Date: Tue, 15 Dec 2015 09:34:17 -0600 Subject: cannot open file with non-ASCII filename In-Reply-To: References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: On Tue, Dec 15, 2015 at 2:26 AM, Ulli Horlacher wrote: > Laura Creighton wrote: > >> PyPy wrote its own pyreadline. >> You can get it here. https://bitbucket.org/pypy/pyrepl > > As far as I can see, it has no getkey function. > My users do not hit ENTER after drag&drop or copy&paste files. > I need an input function with a timeout. pyreadline looked promising for its extensive ctypes implementation of the Windows console API [1], wrapped by high-level methods such as peek, getchar, and getkeypress. It turns out it ignores the event sequences you need for alt+numpad input (used when a file is dragged into the console). You'd have to modify its console and keysyms modules to make it work. It would be a useful enhancement, so probably your patches would be accepted upstream. AFAICT, pyrepl has no Windows support. Check the TODO [2]: > + port to windows [1]: https://github.com/pyreadline/pyreadline/blob/master/pyreadline/console/console.py [2]: https://bitbucket.org/pypy/pyrepl/src/62f2256014af7b74b97c00827f1a7789e00dd814/TODO?at=v0.8.4 From paul.hermeneutic at gmail.com Tue Dec 15 10:43:08 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Tue, 15 Dec 2015 08:43:08 -0700 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: On Dec 13, 2015 7:20 AM, "William Abdo" wrote: > > Problem Resolved. > I have fixed the Oracle connection issue under Windows 10 with cx_Oracle . > PYODBC was only failing on the Oracle connection and worked fine on MS SQL under Windows 10. Please tell us what the fix is. Thanks. From pavlos.parissis at gmail.com Tue Dec 15 10:49:57 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 16:49:57 +0100 Subject: subclassing collections.Counter Message-ID: <567036A5.6050205@gmail.com> Hi, I need to store values for metrics and return the average for some and the sum for the rest. Thus, I thought I could extend collections.Counter class by returning averages for some keys. My class modifies the update() to increment a counter and the __getitem__ to perform the calculation. But, I get RuntimeError: maximum recursion depth exceeded as I access an attribute inside __getitem__. Does anyone has an idea how I can achieve this? Example:: In [7]: metrics = {'f':6, 'g':1} In [8]: avg_metrics = ['f'] In [9]: a = CounterExt(avg_metrics=avg_metrics) In [10]: a.update(metrics) In [11]: a Out[11]: CounterExt({'f': 6, 'g': 1}) In [12]: a.update(metrics) In [13]: a Out[13]: CounterExt({'f': 12, 'g': 2}) In [14]: a['f'] ......... RuntimeError: maximum recursion depth exceeded Code:: from collections import Counter from collections.abc import Mapping class CounterExt(Counter): def __init__(self, iterable=None, avg_metrics=None, **kwds): self._counter = 1 # a zero value will raise ZeroDivisionError self.avg_metrics = avg_metrics super().__init__() self.update(iterable, **kwds) def _count_elements(self, iterable): """Tally elements from the iterable. This is copied from collections/__init__.py original code:: def _count_elements(mapping, iterable): 'Tally elements from the iterable.' mapping_get = mapping.get for elem in iterable: mapping[elem] = mapping_get(elem, 0) + 1 """ for elem in iterable: self[elem] = self.get(elem, 0) + 1 def __getitem__(self, key): if (self.avg_metrics is not None and key in self.avg_metrics): return self[key] / self._counter else: return self[key] def update(self, iterable=None, **kwds): if iterable is not None: if isinstance(iterable, Mapping): if self: self_get = self.get self._counter +=1 # local modification for elem, count in iterable.items(): self[elem] = count + self_get(elem, 0) else: super().update(iterable) else: self._count_elements(iterable) if kwds: self.update(kwds) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Tue Dec 15 11:08:15 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 15 Dec 2015 17:08:15 +0100 Subject: subclassing collections.Counter References: <567036A5.6050205@gmail.com> Message-ID: Pavlos Parissis wrote: > I need to store values for metrics and return the average for some > and the sum for the rest. Thus, I thought I could extend > collections.Counter class by returning averages for some keys. > > My class modifies the update() to increment a counter and the > __getitem__ to perform the calculation. But, I get RuntimeError: maximum > recursion depth exceeded as I access an attribute inside > __getitem__. > > Does anyone has an idea how I can achieve this? > class CounterExt(Counter): > def __getitem__(self, key): > if (self.avg_metrics is not None and key in self.avg_metrics): > return self[key] / self._counter > else: > return self[key] self[key] will call the CounterExt.__getitem__() method again. Use super().__getitem__(key) instead to invoke Counter.__getitem__(). From ian.g.kelly at gmail.com Tue Dec 15 11:11:30 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 15 Dec 2015 09:11:30 -0700 Subject: subclassing collections.Counter In-Reply-To: <567036A5.6050205@gmail.com> References: <567036A5.6050205@gmail.com> Message-ID: On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis wrote: > Hi, > > I need to store values for metrics and return the average for some > and the sum for the rest. Thus, I thought I could extend > collections.Counter class by returning averages for some keys. Leave Counter out of it, as this is not what it's designed for. Write a custom Metrics class, with each attribute being a pseudo-collection that maintains a sum or average. From rxjwg98 at gmail.com Tue Dec 15 11:15:24 2015 From: rxjwg98 at gmail.com (Robert) Date: Tue, 15 Dec 2015 08:15:24 -0800 (PST) Subject: Help on code comprehension from an example project of pymc Message-ID: <5e772de2-e50f-48f1-988c-a7c3eff33b10@googlegroups.com> Hi, I find the useful small code project for me: #https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html It runs as expected. When I review the code, I find 'data' in the original line: data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) has not been referenced thereafter. If I comment out the line as: #data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) the result is ugly different from the original. If I change it to: pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) it still runs as the original. Reading the last half part (after data= line), I cannot see anything uses 'data', though I suspect below line may use it: sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) This is quite different from my any other language experience. Could you help me on this? Thanks, -------------- #https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html from numpy import * Nobs = 20 x_true = random.uniform(0,10, size=Nobs) y_true = random.uniform(-1,1, size=Nobs) alpha_true = 0.5 beta_x_true = 1.0 beta_y_true = 10.0 eps_true = 0.5 z_true = alpha_true + beta_x_true*x_true + beta_y_true*y_true z_obs = z_true + random.normal(0, eps_true, size=Nobs) import pymc # define the parameters with their associated priors #alpha = pymc.Normal('alpha',mu=0,tau=.01) #beta = pymc.Normal('beta',mu=0,tau=.01) alpha = pymc.Uniform('alpha', -100,100, value=median(z_obs)) betax = pymc.Uniform('betax', -100,100, value=std(z_obs)/std(x_true)) betay = pymc.Uniform('betay', -100,100, value=std(z_obs)/std(y_true)) eps = pymc.Uniform('eps', 0,100, value=0.01) # Now define the model @pymc.deterministic def model(alpha=alpha, betax=betax, betay=betay, x=x_true, y=y_true): return alpha + betax*x + betay*y # pymc parametrizes the width of the normal distribution by tau=1/sigma**2 @pymc.deterministic def tau(eps=eps): return power(eps, -2) # Lastly relate the model/parameters to the data #data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) pymc.Normal('data0', mu=model, tau=tau, value=z_obs, observed=True) sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true]) sampler.use_step_method(pymc.AdaptiveMetropolis, [alpha,betax,betay,eps], scales={alpha:0.1, betax:0.1, betay:1.0, eps:0.1}) sampler.sample(iter=10000) pymc.Matplot.plot(sampler) sampler.sample(iter=10000) alpha.summary() m_alpha = median(alpha.trace()) m_betax = median(betax.trace()) m_betay = median(betay.trace()) m_eps = median(eps.trace()) import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) plt.subplot(1,2,1) plt.plot(x_true, z_obs-m_alpha-m_betay*y_true, 'o') plt.xlabel('X') plt.ylabel('Z - alpha - beta_y y') # Now plot the model xx = array([x_true.min(), x_true.max()]) plt.plot(xx, xx*m_betax) plt.plot(xx, xx*m_betax + m_eps, '--', color='k') plt.plot(xx, xx*m_betax - m_eps, '--', color='k') plt.subplot(1,2,2) plt.plot(y_true, z_obs-m_alpha-m_betax*x_true, 'o') plt.xlabel('Y') plt.ylabel('Z - alpha - beta_x x') yy = array([y_true.min(), y_true.max()]) plt.plot(yy, yy*m_betay) plt.plot(yy, yy*m_betay + m_eps, '--', color='k') plt.plot(yy, yy*m_betay - m_eps, '--', color='k') plt.show() From pavlos.parissis at gmail.com Tue Dec 15 11:18:31 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 17:18:31 +0100 Subject: subclassing collections.Counter In-Reply-To: References: <567036A5.6050205@gmail.com> Message-ID: <56703D57.1080209@gmail.com> On 15/12/2015 05:08 ??, Peter Otten wrote: > Pavlos Parissis wrote: > >> I need to store values for metrics and return the average for some >> and the sum for the rest. Thus, I thought I could extend >> collections.Counter class by returning averages for some keys. >> >> My class modifies the update() to increment a counter and the >> __getitem__ to perform the calculation. But, I get RuntimeError: maximum >> recursion depth exceeded as I access an attribute inside >> __getitem__. >> >> Does anyone has an idea how I can achieve this? > >> class CounterExt(Counter): > >> def __getitem__(self, key): >> if (self.avg_metrics is not None and key in self.avg_metrics): >> return self[key] / self._counter >> else: >> return self[key] > > self[key] will call the CounterExt.__getitem__() method again. Use > super().__getitem__(key) instead to invoke Counter.__getitem__(). > > > I applied your suggestion and worked! def __getitem__(self, key): if (self.avg_metrics is not None and key in self.avg_metrics): return super().__getitem__(key) / self.__counter else: return super().__getitem__(key) Thank you very much, Pavlos -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From pavlos.parissis at gmail.com Tue Dec 15 11:20:56 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 17:20:56 +0100 Subject: subclassing collections.Counter In-Reply-To: References: <567036A5.6050205@gmail.com> Message-ID: <56703DE8.7010609@gmail.com> On 15/12/2015 05:11 ??, Ian Kelly wrote: > On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis > wrote: >> Hi, >> >> I need to store values for metrics and return the average for some >> and the sum for the rest. Thus, I thought I could extend >> collections.Counter class by returning averages for some keys. > > Leave Counter out of it, as this is not what it's designed for. Write > a custom Metrics class, with each attribute being a pseudo-collection > that maintains a sum or average. > But then I will have to override a lot of magic methods, right? What is the real problem of extending Counter in the way I did? Cheers, Pavlos -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From w.abdo at ntta.com Tue Dec 15 11:23:28 2015 From: w.abdo at ntta.com (William Abdo) Date: Tue, 15 Dec 2015 16:23:28 +0000 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: Hi Paul Hermeneutic, The issue was it could not establish a connection , it threw an error ORA-01019 (1019) . So after some research it began to look like it was unable to connect via the TNS Names. I was unable to verify this since it was just dying and not logging the issue. So I started a search for an Oracle based ODBC client since PYODBC is still working with the Microsoft DB?s, I tried cx_Oracle and it worked perfectly after I managed to get the parameters correct on the call, It utilized all the syntax for the most part of PYODBC calls so only the connection information needed to be altered. Using parts of a snippet found on the internet that helped me. Since I still needed PYODBC to talk to SQL Server I found that it worked best if cx_Oracle?s import statement is Place before other ODBC clients. At least it appeared that way to me in my testing. See Below: import cx_Oracle #Place before other ODBC Clients pconnObj = cx_Oracle.connect('User/Password at TNSname') #replace with your settings pcur = pconnObj.cursor() if pcur.execute('select * from dual'): print "Yeah, it works!!!" else: print "Failure" pcur.close() I named the cursor the same as I had with PYODBC and no other changes were necessary .fetchall() .fetchone() All worked Returnd values requested also as PYODBC did: prows = pcur.execute("SELECT name,TableID,LastAlteredDate FROM myTable where tableType = '1' order by name").fetchall() print "#rows=" + str(len(prows)) + '\n' tscnt = len(prows) Good Luck! If you have more questions just ask. Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] From: paul.hermeneutic at gmail.com [mailto:paul.hermeneutic at gmail.com] Sent: Tuesday, December 15, 2015 10:43 AM To: William Abdo Cc: python-list at python.org Subject: RE: Windows 10 and PYODBC On Dec 13, 2015 7:20 AM, "William Abdo" > wrote: > > Problem Resolved. > I have fixed the Oracle connection issue under Windows 10 with cx_Oracle . > PYODBC was only failing on the Oracle connection and worked fine on MS SQL under Windows 10. Please tell us what the fix is. Thanks. **************************************************************** This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. **************************************************************** From paul.hermeneutic at gmail.com Tue Dec 15 11:33:51 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Tue, 15 Dec 2015 09:33:51 -0700 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: On Dec 15, 2015 9:22 AM, "William Abdo" wrote: > > So I started a search for an Oracle based ODBC client since PYODBC is still working with the Microsoft DB?s, I tried cx_Oracle and it worked perfectly after I managed to get the parameters correct on the call, It sounds like PYODBC cannot connect to Oracle on Windows 10. Is that correct? From pavlos.parissis at gmail.com Tue Dec 15 11:59:56 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 17:59:56 +0100 Subject: subclassing collections.Counter In-Reply-To: <56703D57.1080209@gmail.com> References: <567036A5.6050205@gmail.com> <56703D57.1080209@gmail.com> Message-ID: <5670470C.6080002@gmail.com> On 15/12/2015 05:18 ??, Pavlos Parissis wrote: > On 15/12/2015 05:08 ??, Peter Otten wrote: >> Pavlos Parissis wrote: >> >>> I need to store values for metrics and return the average for some >>> and the sum for the rest. Thus, I thought I could extend >>> collections.Counter class by returning averages for some keys. >>> >>> My class modifies the update() to increment a counter and the >>> __getitem__ to perform the calculation. But, I get RuntimeError: maximum >>> recursion depth exceeded as I access an attribute inside >>> __getitem__. >>> >>> Does anyone has an idea how I can achieve this? >> >>> class CounterExt(Counter): >> >>> def __getitem__(self, key): >>> if (self.avg_metrics is not None and key in self.avg_metrics): >>> return self[key] / self._counter >>> else: >>> return self[key] >> >> self[key] will call the CounterExt.__getitem__() method again. Use >> super().__getitem__(key) instead to invoke Counter.__getitem__(). >> >> >> > > I applied your suggestion and worked! > def __getitem__(self, key): > if (self.avg_metrics is not None and key in self.avg_metrics): > return super().__getitem__(key) / self.__counter > else: > return super().__getitem__(key) > > Thank you very much, > Pavlos > Calling items() over the object doesn't call __getitem__ and I can't find in the doc which method I need to change, any ideas? Cheers, Pavlos -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From framstag at rus.uni-stuttgart.de Tue Dec 15 12:04:55 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 17:04:55 +0000 (UTC) Subject: cannot open file with non-ASCII filename References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: eryk sun wrote: > pyreadline looked promising for its extensive ctypes implementation of > the Windows console API [1], wrapped by high-level methods such as > peek, getchar, and getkeypress. It turns out it ignores the event > sequences you need for alt+numpad input (used when a file is dragged > into the console). You'd have to modify its console and keysyms > modules to make it work. It would be a useful enhancement, so probably > your patches would be accepted upstream. Ehhh... I started Python programming some weeks ago and I know nearly nothing about Windows. I am a UNIX and VMS guy :-) I am far away from delivering patches for Windows system programming. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From ian.g.kelly at gmail.com Tue Dec 15 12:22:20 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 15 Dec 2015 10:22:20 -0700 Subject: subclassing collections.Counter In-Reply-To: <56703DE8.7010609@gmail.com> References: <567036A5.6050205@gmail.com> <56703DE8.7010609@gmail.com> Message-ID: On Tue, Dec 15, 2015 at 9:20 AM, Pavlos Parissis wrote: > On 15/12/2015 05:11 ??, Ian Kelly wrote: >> On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis >> wrote: >>> Hi, >>> >>> I need to store values for metrics and return the average for some >>> and the sum for the rest. Thus, I thought I could extend >>> collections.Counter class by returning averages for some keys. >> >> Leave Counter out of it, as this is not what it's designed for. Write >> a custom Metrics class, with each attribute being a pseudo-collection >> that maintains a sum or average. >> > > But then I will have to override a lot of magic methods, right? > What is the real problem of extending Counter in the way I did? Only the ones that you have use for. So far, you haven't indicated that you need any. All you said about your use case was "I need to store values for metrics." If you want your metrics container to act like a dict, then my suggestion would be to just use a dict, with pseudo-collections for the values as above. > Calling items() over the object doesn't call __getitem__ and I can't > find in the doc which method I need to change, any ideas? You can find the source at https://hg.python.org/cpython/file/3.5/Lib/collections/__init__.py. Counter subclasses dict but doesn't override items, so if you want to change the behavior of items then you'll probably have to override items. From w.abdo at ntta.com Tue Dec 15 12:35:42 2015 From: w.abdo at ntta.com (William Abdo) Date: Tue, 15 Dec 2015 17:35:42 +0000 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: Yes Paul Hermeneutic , that is correct. I tried everything I could however, I was unable to make PYODBC talk to Oracle under Windows 10. Maybe there are smarter than me that can make this work. For me it was easier to just use cx_Oracle for the Oracle connection. Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] From: paul.hermeneutic at gmail.com [mailto:paul.hermeneutic at gmail.com] Sent: Tuesday, December 15, 2015 11:34 AM To: William Abdo Cc: python-list at python.org Subject: RE: Windows 10 and PYODBC On Dec 15, 2015 9:22 AM, "William Abdo" > wrote: > > So I started a search for an Oracle based ODBC client since PYODBC is still working with the Microsoft DB?s, I tried cx_Oracle and it worked perfectly after I managed to get the parameters correct on the call, It sounds like PYODBC cannot connect to Oracle on Windows 10. Is that correct? **************************************************************** This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. **************************************************************** From jorge.conrado at cptec.inpe.br Tue Dec 15 12:42:39 2015 From: jorge.conrado at cptec.inpe.br (jorge.conrado at cptec.inpe.br) Date: Tue, 15 Dec 2015 15:42:39 -0200 Subject: netcdf 4 time Message-ID: <1b1187703bc96c0fe21f85c2e97c3694@cptec.inpe.br> Hi, I'm reading ndetcdf 4 data from NCEP Reanalyisis project. I use to read the data: air_2010_2014_850hPa_d.nc is four year daily data. mport matplotlib.pylab as plt from netCDF4 import Dataset, num2date, date2index, date2num import pandas as pd from mpl_toolkits.basemap import Basemap import numpy as np from jdcal import gcal2jd, jd2gcal f = Dataset('air_2010_2014_850hPa_d.nc') air = f.variables['air'][:] time = f.variables['time'] lon = f.variables['lon'][:] lat = f.variables['lat'][:] lon, lat = np.meshgrid(lon, lat) dates = num2date(time[:], time.units) print dates This is the date values: [datetime.datetime(2010, 1, 1, 0, 0) datetime.datetime(2010, 1, 2, 0, 0) datetime.datetime(2010, 1, 3, 0, 0) ..., datetime.datetime(2014, 12, 29, 0, 0) datetime.datetime(2014, 12, 30, 0, 0) datetime.datetime(2014, 12, 31, 0, 0)] Please, how can I get an arrya for each year, monht and day from the dates values and how can I get an specific day for my dates array. Please anyone have any example of date2index for the netcdf 4. This is the time for my netcdf data. float64 time(time) long_name: Time delta_t: 0000-00-01 00:00:00 avg_period: 0000-00-01 00:00:00 standard_name: time axis: T units: hours since 1800-01-01 00:00:0.0 actual_range: [ 1840824. 1884624.] unlimited dimensions: time current shape = (1826,) filling on, default _FillValue of 9.96920996839e+36 used Thanks in advance, Conrado From pavlos.parissis at gmail.com Tue Dec 15 12:43:05 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 18:43:05 +0100 Subject: subclassing collections.Counter In-Reply-To: References: <567036A5.6050205@gmail.com> <56703DE8.7010609@gmail.com> Message-ID: <56705129.2020004@gmail.com> On 15/12/2015 06:22 ??, Ian Kelly wrote: > On Tue, Dec 15, 2015 at 9:20 AM, Pavlos Parissis > wrote: >> On 15/12/2015 05:11 ??, Ian Kelly wrote: >>> On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis >>> wrote: >>>> Hi, >>>> >>>> I need to store values for metrics and return the average for some >>>> and the sum for the rest. Thus, I thought I could extend >>>> collections.Counter class by returning averages for some keys. >>> >>> Leave Counter out of it, as this is not what it's designed for. Write >>> a custom Metrics class, with each attribute being a pseudo-collection >>> that maintains a sum or average. >>> >> >> But then I will have to override a lot of magic methods, right? >> What is the real problem of extending Counter in the way I did? > > Only the ones that you have use for. So far, you haven't indicated > that you need any. All you said about your use case was "I need to > store values for metrics." > I needed the update() to do the addition rather the override. > If you want your metrics container to act like a dict, then my > suggestion would be to just use a dict, with pseudo-collections for > the values as above. > If I understood you correctly, you are saying store all metrics in a dict and have a counter key as well to store the times metrics are pushed in, and then have a function to do the math. Am I right? >> Calling items() over the object doesn't call __getitem__ and I can't >> find in the doc which method I need to change, any ideas? > > You can find the source at > https://hg.python.org/cpython/file/3.5/Lib/collections/__init__.py. > Counter subclasses dict but doesn't override items, so if you want to > change the behavior of items then you'll probably have to override > items. > I thought that items() calls a magic method, but it is actually a method itself. Thanks for highlight this. Cheers, Pavlos -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From ian.g.kelly at gmail.com Tue Dec 15 12:55:05 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 15 Dec 2015 10:55:05 -0700 Subject: subclassing collections.Counter In-Reply-To: <56705129.2020004@gmail.com> References: <567036A5.6050205@gmail.com> <56703DE8.7010609@gmail.com> <56705129.2020004@gmail.com> Message-ID: On Tue, Dec 15, 2015 at 10:43 AM, Pavlos Parissis wrote: >> If you want your metrics container to act like a dict, then my >> suggestion would be to just use a dict, with pseudo-collections for >> the values as above. >> > > If I understood you correctly, you are saying store all metrics in a > dict and have a counter key as well to store the times metrics are > pushed in, and then have a function to do the math. Am I right? That would work, although I was actually thinking of something like this: class SummedMetric: def __init__(self): self.total = 0 self.count = 0 @property def average(self): return self.total / self.count def add(self, value): self.total += value self.count += 1 metrics = {} for metric_name in all_metrics: metrics[metric_name] = SummedMetric() For averaged metrics, look at metrics['f'].average, otherwise look at metrics['f'].total. From framstag at rus.uni-stuttgart.de Tue Dec 15 12:57:18 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Tue, 15 Dec 2015 17:57:18 +0000 (UTC) Subject: subprocess.call with non-ASCII arguments? References: Message-ID: Dennis Lee Bieber wrote: > Python has a zipfile library that is portable between OS. Along with > libraries for gzip, bzip2, and tarfiles... Ohh.. this is new to me! https://docs.python.org/2/library/tarfile.html https://docs.python.org/2/library/zipfile.html What is missing in the documentation: Is the tar/zip file generation done in memory or will it be written directly to disk? My program creates zip or tar files up to TB size. This cannot be done in memory. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From paul.hermeneutic at gmail.com Tue Dec 15 13:40:48 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Tue, 15 Dec 2015 11:40:48 -0700 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: On Dec 15, 2015 10:34 AM, "William Abdo" wrote: > > Yes Paul Hermeneutic , that is correct. > > I tried everything I could however, I was unable to make PYODBC talk to Oracle under Windows 10. It would be of help to everyone if you would file a bug report on the issue tracker. http://bugs.python.org/ From w.abdo at ntta.com Tue Dec 15 14:01:06 2015 From: w.abdo at ntta.com (William Abdo) Date: Tue, 15 Dec 2015 19:01:06 +0000 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: As you wish, [issue577] PYODBC will not talk to Oracle under Windows 10. Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] From: paul.hermeneutic at gmail.com [mailto:paul.hermeneutic at gmail.com] Sent: Tuesday, December 15, 2015 1:41 PM To: William Abdo Cc: python-list at python.org Subject: RE: Windows 10 and PYODBC On Dec 15, 2015 10:34 AM, "William Abdo" > wrote: > > Yes Paul Hermeneutic , that is correct. > > I tried everything I could however, I was unable to make PYODBC talk to Oracle under Windows 10. It would be of help to everyone if you would file a bug report on the issue tracker. http://bugs.python.org/ **************************************************************** This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. **************************************************************** From paul.hermeneutic at gmail.com Tue Dec 15 15:08:41 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Tue, 15 Dec 2015 13:08:41 -0700 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: On Dec 15, 2015 12:00 PM, "William Abdo" wrote: > > As you wish, > > [issue577] PYODBC will not talk to Oracle under Windows 10. Where is this issue filed? I do not see it on http://bugs.python.org/ From w.abdo at ntta.com Tue Dec 15 15:33:10 2015 From: w.abdo at ntta.com (William Abdo) Date: Tue, 15 Dec 2015 20:33:10 +0000 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: issue 25875 created I put it in the wrong area the first time. First time bug tracker user errors. Respectfully, William Abdo Software App Engineer II NTT America, an NTT Communications Company Office: +1 561.912.2434 Email: w.abdo at ntta.com [https://rvip.team-center.net/externals/images/email/ntta.png] [https://rvip.team-center.net/externals/images/email/ntta-twitter.png] [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] [https://rvip.team-center.net/externals/images/email/ntta-facebook.png] [https://rvip.team-center.net/externals/images/email/ntta-youtube.png] From: paul.hermeneutic at gmail.com [mailto:paul.hermeneutic at gmail.com] Sent: Tuesday, December 15, 2015 3:09 PM To: William Abdo Cc: python-list at python.org Subject: RE: Windows 10 and PYODBC On Dec 15, 2015 12:00 PM, "William Abdo" > wrote: > > As you wish, > > [issue577] PYODBC will not talk to Oracle under Windows 10. Where is this issue filed? I do not see it on http://bugs.python.org/ **************************************************************** This email message is intended for the use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. NTT America makes no warranty that this email is error or virus free. Thank you. **************************************************************** From sjeik_appie at hotmail.com Tue Dec 15 17:04:27 2015 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Tue, 15 Dec 2015 22:04:27 +0000 Subject: Screenshots in Sphinx docs In-Reply-To: References: , Message-ID: > To: python-list at python.org > From: tjreedy at udel.edu > Subject: Re: Screenshots in Sphinx docs > Date: Mon, 14 Dec 2015 14:01:03 -0500 > > On 12/14/2015 11:31 AM, Albert-Jan Roskam wrote: > > > I'd like to include up-to-date screenshots (of a tkinter app) > > into my Sphinx documentation. > > If you manually take screenshots with *any* screen grabber and save in > an appropriate format, this is apparently trivial -- use the ..image > directive. From the below, it appears that what you want is to have a > literally up-to-date screenshot taken automatically during the doc build. > > This requires that one be able to automate getting the application into > the exact display state one wants to capture. You can probably do that > with a tkinter app if you write it with that possibility in mind. In > particular, you must keep a Python reference to every widget you want to > manipulate, even if not needed for normal program operation. > > There is also an issue with grabbing the whole screen versus only a > program-specific window. I need only a few screens. I think I will call my tkinter app with subprocess.Popen, wait until it's loaded, grab the image, then kill it. Then I indeed wanted to use the ..image directive. > > This looks ok: > > https://pypi.python.org/pypi/sphinxcontrib-programscreenshot > > This (automatically) takes 'screenshots' on a no-screen (headless) *nix > system (during doc build) by redirecting X-windows output to a > pseudo-screen program. Rather clever, and system-specific. > > > BUT I need something that works on Windows (Python 2.7). > > Can any recommend an approach? I thought about using PIL: > > Get the pillow fork/upgrade on pypi. Thanks for the tip! So good ol' PIL is no longer maintained? > > http://www.varesano.net/blog/fabio/capturing%20screen%20image%20python%20and%20pil%20windows > > Or look into Windows screen grabber programs, of which there are many. > > -- > Terry Jan Reedy > > -- > https://mail.python.org/mailman/listinfo/python-list From pavlos.parissis at gmail.com Tue Dec 15 17:18:27 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Tue, 15 Dec 2015 23:18:27 +0100 Subject: subclassing collections.Counter In-Reply-To: References: <567036A5.6050205@gmail.com> <56703DE8.7010609@gmail.com> <56705129.2020004@gmail.com> Message-ID: <567091B3.7010008@gmail.com> On 15/12/2015 06:55 ??, Ian Kelly wrote: > On Tue, Dec 15, 2015 at 10:43 AM, Pavlos Parissis > wrote: >>> If you want your metrics container to act like a dict, then my >>> suggestion would be to just use a dict, with pseudo-collections for >>> the values as above. >>> >> >> If I understood you correctly, you are saying store all metrics in a >> dict and have a counter key as well to store the times metrics are >> pushed in, and then have a function to do the math. Am I right? > > That would work, although I was actually thinking of something like this: > > class SummedMetric: > def __init__(self): > self.total = 0 > self.count = 0 > > @property > def average(self): > return self.total / self.count > > def add(self, value): > self.total += value > self.count += 1 > > metrics = {} > for metric_name in all_metrics: > metrics[metric_name] = SummedMetric() > > For averaged metrics, look at metrics['f'].average, otherwise look at > metrics['f'].total. > With this approach I will have for each metric 1 object, which could cause performance issues for my case. Let me bring some context on what I am trying to do here. I want to provide a fast retrieval and processing of statistics metrics for HAProxy. HAProxy exposes stats over a UNIX socket(stats socket). HAProxy is a multi-process daemon and each process can only be accessed by a distinct stats socket. There isn't any shared memory for all these processes. That means that if a frontend or backend is managed by more than one processes, you have to collect metrics from all processes and do the sum or average based on type of the metric. stats are provided in a CSV format: https://gist.github.com/unixsurfer/ba7e3bb3f3f79dcea686 there is 1 line per frontend and backend. For servers is a bit more complicated. When there are 100 lines per process, it is easy to do the work even in setups with 24 processes(24 *100=2.4K lines). But, there are a lot of cases where a stats socket will return 10K lines, due to the amount of backends and servers in backends. This is 240K lines to process and provide stats per 10secs or 5 secs. My plan is to split the processing from the collection. A program will connect to all UNIX sockets asynchronously and dump the CSV to files, one per socket, and group them by EPOCH time. It will dump all files under 1 directory which will have as name the time of the retrieval. Another program in multi-process mode[1], will pick those files and parse them in sequentially to perform the aggregation. For this program I needed the CounterExt. I will try your approach as well as it is very simple and it does the work with fewer lines:-) I will compare both in terms of performance and select the fastest. Thank you very much for your assistance, very much appreciated. [1] pseudo-code from multiprocessing import Process, Queue import pyinotify wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.IN_CREATE # watched events class EventHandler(pyinotify.ProcessEvent): def __init__(self, queue): self.queue = queue def process_IN_CREATE(self, event): self.queue.put(event.pathname) def work(queue): while True: job = queue.get() if job == 'STOP': break print(job) def main(): pnum = 10 queue = Queue() plist = [] for i in range(pnum): p = Process(target=work, args=(queue,)) p.start() plist.append(p) handler = EventHandler(queue) notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('/tmp/test', mask, rec=True) notifier.loop() -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From rosuav at gmail.com Tue Dec 15 17:34:24 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 16 Dec 2015 09:34:24 +1100 Subject: Help on code comprehension from an example project of pymc In-Reply-To: <5e772de2-e50f-48f1-988c-a7c3eff33b10@googlegroups.com> References: <5e772de2-e50f-48f1-988c-a7c3eff33b10@googlegroups.com> Message-ID: On Wed, Dec 16, 2015 at 3:15 AM, Robert wrote: > When I review the code, I find 'data' in the original line: > > data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > has not been referenced thereafter. > If I comment out the line as: > > #data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > the result is ugly different from the original. > > If I change it to: > > pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > it still runs as the original. > > This is quite different from my any other language experience. > > Could you help me on this? What this suggests is that the call you're doing returns something (as every function call must, unless it raises an exception or doesn't terminate), but it also has side effects. You're ignoring the return value (which is why "data = " doesn't affect your code), but you need the side effects. Unfortunately this is the case with quite a lot of Python's high end math/stats modules, presumably because their APIs are lifted directly from other languages; have a look at pyplot, for instance, where a more Pythonic API would be to instantiate a plot object every time. (In that particular example, I believe that's an option; but most examples just use the module-level default.) It's my guess (based on skimming the docs) that the objects passed in, including those referenced as function default arguments, are getting mutated. But I'm no expert on pymc. It's equally likely that module-level (global) state is being changed. ChrisA From tjreedy at udel.edu Tue Dec 15 17:45:01 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Dec 2015 17:45:01 -0500 Subject: Help on code comprehension from an example project of pymc In-Reply-To: <5e772de2-e50f-48f1-988c-a7c3eff33b10@googlegroups.com> References: <5e772de2-e50f-48f1-988c-a7c3eff33b10@googlegroups.com> Message-ID: On 12/15/2015 11:15 AM, Robert wrote: > Hi, > > I find the useful small code project for me: > #https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html > > It runs as expected. > > When I review the code, I find 'data' in the original line: > > data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > has not been referenced thereafter. If the function is called strictly for its side-effect, then it would be normal to not keep the 'return' value. Code checkers will catch this and warn. Just because code is make available, does not mean it follows the best style. Perhaps the programmer though 'data' might be needed before writing the rest. > If I comment out the line as: > > #data = pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > the result is ugly different from the original. > > If I change it to: > > pymc.Normal('data', mu=model, tau=tau, value=z_obs, observed=True) > > it still runs as the original. -- Terry Jan Reedy From sgardne at gmail.com Tue Dec 15 19:42:22 2015 From: sgardne at gmail.com (sgardne at gmail.com) Date: Tue, 15 Dec 2015 16:42:22 -0800 (PST) Subject: How can I remove the first line of a multi-line string? In-Reply-To: References: <5224B786.2050606@gmail.com> Message-ID: <2e611ff1-c95e-4343-aeb2-9119f6755493@googlegroups.com> On Monday, September 2, 2013 at 11:53:32 AM UTC-5, MRAB wrote: > On 02/09/2013 17:12, Chris "Kwpolska" Warrick wrote: > > On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion wrote: > >> Hello Everyone, > >> > >> I have a multi-line string and I need to remove the very first line from > >> it. How can I do that? I looked at StringIO but I can't seem to figure > >> out how to properly use it to remove the first line. Basically, I want > >> to toss the first line but keep everything else. Can anyone put me on > >> the right path? I know it is probably easy but I'm still learning Python > >> and don't have all the string functions down yet. > >> > >> Thanks, > >> Anthony > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > Use split() and join() methods of strings, along with slicing. Like this: > > > > fullstring = """foo > > bar > > baz""" > > > > sansfirstline = '\n'.join(fullstring.split('\n')[1:]) > > > > The last line does this: > > 1. fullstring.split('\n') turns it into a list of ['foo', 'bar', 'baz'] > > 2. the [1:] slice removes the first element, making it ['bar', 'baz'] > > 3. Finally, '\n'.join() turns the list into a string separated by > > newlines ("""bar > > baz""") > > > Another way is to use .partition: > > >>> fullstring = """foo\nbar\nbaz""" > >>> fullstring.partition("\n")[2] > 'bar\nbaz' I realize this is very old, but thanks for posting this reply. I like this answer the best. From simian336 at gmail.com Tue Dec 15 20:54:46 2015 From: simian336 at gmail.com (simian336 at gmail.com) Date: Tue, 15 Dec 2015 17:54:46 -0800 (PST) Subject: error reading api with urllib Message-ID: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Hi, I am pretty new to python. I have a project reading an api with urllib. The problem is I have to sections of code almost exactly the same. The first url works great. They second one fails. If I manually copy and paste the url in the browser ti works great. The error I get back is... Bad Request b'' I have manipulated it a few ways and I sometimes she bad url type b'http I have attempted to try to pass it as ascii and unicode but may not have been correct. Thanks for any suggestions. Simian #Getting Individual Customer services Info custinfostart='http://192.17.3.17:7780/dataservices/cdk?SP=md_cst.get_customer(%270003%27,%27' custinforend ='%27,?,?int%20status)' CustLink=custinfostart+curr_cust+custinforend #print(CustLink) req=urllib.request.Request(CustLink) resp=urllib.request.urlopen(req) respData=resp.read() CustServ.write('Customer ID:'+curr_cust+'\n') CustServ.write(str(respData)+'\n') #************************************************************************* #Getting Device Info custinfostart='http://192.17.3.17:7780/dataservices/cdk?SP=md_dev.get_device(%270003%27,%272%27,%27' custinforend ='%27,%27n%27,%271%27,%27100%27,?,?,?int status)' #custinfostart="http://192.17.3.17:7780/dataservices/cdk?SP=md_dev.get_device('0003','2','" #custinforend ="','n','1','100',?,?,?int status)" print(custinfostart) print(curr_cust) print(custinforend) CustLink=custinfostart+curr_cust+custinforend #CustLink=CustLink.encode('ascii', 'ignore') print('test') print(CustLink) ######### Code Fails Here ########## req=urllib.request.Request(CustLink) # resp=urllib.request.urlopen(req) try: resp=urllib.request.urlopen(req) except urllib.error.URLError as e: print(e.reason) respData=resp.read() print(respData) sys.exit("Device Error") respData=resp.read() DeviceInfo.write(str(respData)+'\n') From simian336 at gmail.com Tue Dec 15 21:46:10 2015 From: simian336 at gmail.com (Simian) Date: Tue, 15 Dec 2015 18:46:10 -0800 (PST) Subject: error reading api with urllib In-Reply-To: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> References: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Message-ID: I added except urllib.error.HTTPError as e: print('HTTP Errpr') print('Error code: ', e.code) to my try and I recieve... 400: ('Bad Request', 'Bad request syntax or unsupported method'), but processing the string with a browser works fine. Simi From scarrera53 at gmail.com Wed Dec 16 00:40:12 2015 From: scarrera53 at gmail.com (scarrera53 at gmail.com) Date: Tue, 15 Dec 2015 21:40:12 -0800 (PST) Subject: TypeError: 'float' object is not iterable In-Reply-To: <5b49a5b4-dfaa-44fe-a60a-8e9aafde9f60@googlegroups.com> References: <3984882c-0144-47ba-af4f-b29877bc4698@googlegroups.com> <5b49a5b4-dfaa-44fe-a60a-8e9aafde9f60@googlegroups.com> Message-ID: <08cc84ed-e084-46d6-9621-f3ad18e59b52@googlegroups.com> Someone stealing my points, I don't know how someone do it, but they had stolen some of my points. From rosuav at gmail.com Wed Dec 16 00:52:30 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 16 Dec 2015 16:52:30 +1100 Subject: TypeError: 'float' object is not iterable In-Reply-To: <08cc84ed-e084-46d6-9621-f3ad18e59b52@googlegroups.com> References: <3984882c-0144-47ba-af4f-b29877bc4698@googlegroups.com> <5b49a5b4-dfaa-44fe-a60a-8e9aafde9f60@googlegroups.com> <08cc84ed-e084-46d6-9621-f3ad18e59b52@googlegroups.com> Message-ID: On Wed, Dec 16, 2015 at 4:40 PM, wrote: > Someone stealing my points, I don't know how someone do it, but they had stolen some of my points. They were floating. You should fix them down. Also, you're replying to a years-old thread with no context. ChrisA From yangyc.frank at live.com Wed Dec 16 02:03:12 2015 From: yangyc.frank at live.com (Yaocheng Frank Yang) Date: Wed, 16 Dec 2015 07:03:12 +0000 Subject: sublime textx 3 and python 35 Message-ID: Dear Python Team, I'm trying to install python35 and use sublime text 3 to write code on it. After I change the path name to the python app location. I still have some problem. I wrote a simple print function in sublime text(I already saved the file with .py extension) and the console show "finished in 0.2 s " without popping up any window displaying the word I tried to print. Could you give any of your insights on this issue? Also python 35 is automatically installed under my User folder and I for some reason couldn't find it from scratch by clikcing on folders(like from My computer to user to ....) Thanks! Frank From dieter at handshake.de Wed Dec 16 02:48:03 2015 From: dieter at handshake.de (dieter) Date: Wed, 16 Dec 2015 08:48:03 +0100 Subject: wrapper api / proxying third party exception? References: <77743c9d-8554-4b76-b3b3-8d35cf894905@googlegroups.com> Message-ID: <87y4cu7s24.fsf@handshake.de> Benjamin Risher writes: > Ok, here's my issue. I have a plugin framework I wrote that relies on a third party library that I can't change. As a part of that framework, I wrote a small stub library to proxy calls to the third party library, so that if their api ever changes, plugins written against the stub won't have to change, I'll just have to update the back-half that interfaces with the library. I think this is called an adapter design pattern...? > > plugin --> my api --> their api --> their library > > It works, for the most part. Most of my classes look similar to this > > class MYClass: > def __init__(self, *args, **kwargs): > self.__theirclass = TheirClass(*args, **kwargs) > > def __getattr__(self, attr): > return getattr(self.__theirclass, attr) > > What I'm having issue with, is their exception class. > > 1. A plugin calls a stub in my library > 2. That stub calls the corresponding call in the third party library > 3. The call raises an exception from the library > 4. The plugin can't catch the exception without importing directly from the third party library > > What is the correct way to allow plugins to import my stub exception, but catch the ones raised by the library? I would approach this as follows: * define an exception hiearchy for your wrapper with a common root class and document those hiearchy to be used for the plugins * in your wrapper, catch all exceptions - if it is one of your execptions, you know what to do - if it is a general Python exception, it likely indicates a programming error in the plugin or library -- handle as appropriately (personally, I would "reraise") - if it is something else, it likely indicates that the plugin violated its contract (towards your wrapper API) -- handle as appropriate (again, I would "reraise"). From ben+python at benfinney.id.au Wed Dec 16 03:14:11 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 16 Dec 2015 19:14:11 +1100 Subject: TypeError: 'float' object is not iterable References: <3984882c-0144-47ba-af4f-b29877bc4698@googlegroups.com> <5b49a5b4-dfaa-44fe-a60a-8e9aafde9f60@googlegroups.com> <08cc84ed-e084-46d6-9621-f3ad18e59b52@googlegroups.com> Message-ID: <854mfi4xpo.fsf@benfinney.id.au> scarrera53 at gmail.com writes: > Someone stealing my points, I don't know how someone do it, but they > had stolen some of my points. Make new points, summarise them succinctly in the Subject field, and be prepared to defend them. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but there's still a bug stuck in here from last time.? | _o__) ?_Pinky and The Brain_ | Ben Finney From wxjmfauth at gmail.com Wed Dec 16 03:50:52 2015 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 16 Dec 2015 00:50:52 -0800 (PST) Subject: How can I remove the first line of a multi-line string? In-Reply-To: <2e611ff1-c95e-4343-aeb2-9119f6755493@googlegroups.com> References: <5224B786.2050606@gmail.com> <2e611ff1-c95e-4343-aeb2-9119f6755493@googlegroups.com> Message-ID: <8ee60b1d-42df-40f7-9f66-baecba802f0a@googlegroups.com> >>> s = """abc ... ??? ... ???""" >>> i = 0 >>> ns = '' >>> while i < len(s): ... if s[i] == '\n': ... break ... i += 1 ... >>> i += 1 >>> while i < len(s): ... ns += s[i] ... i += 1 ... >>> print(ns) ??? ??? From steve at pearwood.info Wed Dec 16 05:18:35 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 Dec 2015 21:18:35 +1100 Subject: How can I remove the first line of a multi-line string? References: <5224B786.2050606@gmail.com> <2e611ff1-c95e-4343-aeb2-9119f6755493@googlegroups.com> Message-ID: <56713a7c$0$1592$c3e8da3$5496439d@news.astraweb.com> On Wed, 16 Dec 2015 11:42 am, sgardne at gmail.com wrote: > On Monday, September 2, 2013 at 11:53:32 AM UTC-5, MRAB wrote: >> On 02/09/2013 17:12, Chris "Kwpolska" Warrick wrote: >> > On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion > > gmail.com> wrote: >> >> Hello Everyone, >> >> >> >> I have a multi-line string and I need to remove the very first line >> >> from it. How can I do that? I looked at StringIO but I can't seem to >> >> figure out how to properly use it to remove the first line. Basically, >> >> I want >> >> to toss the first line but keep everything else. The maxsplit parameter to str.split makes this easier than falling off a greased log: py> astring = """Hello world, ... How are things? ... Hope you are well. ... Goodbye. ... """ py> astring.split("\n", 1)[1] 'How are things?\nHope you are well.\nGoodbye.\n' -- Steven From rxjwg98 at gmail.com Wed Dec 16 05:44:06 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 02:44:06 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " Message-ID: Hi, When I run the following code, there is an error: ValueError: For numerical factors, num_columns must be an int ================ import numpy as np import pandas as pd from patsy import dmatrices from sklearn.linear_model import LogisticRegression X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, 3.5,4.0,4.25,4.5,4.75,5.0,5.5] y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] zipped = list(zip(X,y)) df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") ======================= I have check 'df' is this type: ============= type(df) Out[25]: pandas.core.frame.DataFrame ============= I cannot figure out where the problem is. Can you help me? Thanks. Error message: .......... --------------------------------------------------------------------------- ValueError Traceback (most recent call last) C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) 18 ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") 20 21 y = np.ravel(y) C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, --> 297 NA_action, return_type) 298 if lhs.shape[1] == 0: 299 raise PatsyError("model is missing required outcome variables") C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) 150 return iter([data]) 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, --> 152 NA_action) 153 if design_infos is not None: 154 return build_design_matrices(design_infos, data, C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) 55 data_iter_maker, 56 eval_env, ---> 57 NA_action) 58 else: 59 return None C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) 704 factor_states[factor], 705 num_columns=num_column_counts[factor], --> 706 categories=None) 707 else: 708 assert factor in cat_levels_contrasts C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) 86 if self.type == "numerical": 87 if not isinstance(num_columns, int): ---> 88 raise ValueError("For numerical factors, num_columns " 89 "must be an int") 90 if categories is not None: ValueError: For numerical factors, num_columns must be an int From rxjwg98 at gmail.com Wed Dec 16 05:56:51 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 02:56:51 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: References: Message-ID: On Wednesday, December 16, 2015 at 5:44:21 AM UTC-5, Robert wrote: > Hi, > > When I run the following code, there is an error: > > ValueError: For numerical factors, num_columns must be an int > > > ================ > import numpy as np > import pandas as pd > from patsy import dmatrices > from sklearn.linear_model import LogisticRegression > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > zipped = list(zip(X,y)) > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > ======================= > > I have check 'df' is this type: > ============= > type(df) > Out[25]: pandas.core.frame.DataFrame > ============= > > I cannot figure out where the problem is. Can you help me? > Thanks. > > Error message: > .......... > > > --------------------------------------------------------------------------- > ValueError Traceback (most recent call last) > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > 18 > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > 20 > 21 y = np.ravel(y) > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > --> 297 NA_action, return_type) > 298 if lhs.shape[1] == 0: > 299 raise PatsyError("model is missing required outcome variables") > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > 150 return iter([data]) > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > --> 152 NA_action) > 153 if design_infos is not None: > 154 return build_design_matrices(design_infos, data, > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > 55 data_iter_maker, > 56 eval_env, > ---> 57 NA_action) > 58 else: > 59 return None > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > 704 factor_states[factor], > 705 num_columns=num_column_counts[factor], > --> 706 categories=None) > 707 else: > 708 assert factor in cat_levels_contrasts > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > 86 if self.type == "numerical": > 87 if not isinstance(num_columns, int): > ---> 88 raise ValueError("For numerical factors, num_columns " > 89 "must be an int") > 90 if categories is not None: > > ValueError: For numerical factors, num_columns must be an int BTW, I use Python 2.7 on Canopy. patsy: VERSION 0.4.0 Thanks, From rxjwg98 at gmail.com Wed Dec 16 06:03:59 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 03:03:59 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: References: Message-ID: <1bac9aef-43e8-49c9-b07d-254b1100011d@googlegroups.com> On Wednesday, December 16, 2015 at 5:57:04 AM UTC-5, Robert wrote: > On Wednesday, December 16, 2015 at 5:44:21 AM UTC-5, Robert wrote: > > Hi, > > > > When I run the following code, there is an error: > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > ================ > > import numpy as np > > import pandas as pd > > from patsy import dmatrices > > from sklearn.linear_model import LogisticRegression > > > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > > > zipped = list(zip(X,y)) > > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > ======================= > > > > I have check 'df' is this type: > > ============= > > type(df) > > Out[25]: pandas.core.frame.DataFrame > > ============= > > > > I cannot figure out where the problem is. Can you help me? > > Thanks. > > > > Error message: > > .......... > > > > > > --------------------------------------------------------------------------- > > ValueError Traceback (most recent call last) > > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > 18 > > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > 20 > > 21 y = np.ravel(y) > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > > --> 297 NA_action, return_type) > > 298 if lhs.shape[1] == 0: > > 299 raise PatsyError("model is missing required outcome variables") > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > > 150 return iter([data]) > > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > > --> 152 NA_action) > > 153 if design_infos is not None: > > 154 return build_design_matrices(design_infos, data, > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > > 55 data_iter_maker, > > 56 eval_env, > > ---> 57 NA_action) > > 58 else: > > 59 return None > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > > 704 factor_states[factor], > > 705 num_columns=num_column_counts[factor], > > --> 706 categories=None) > > 707 else: > > 708 assert factor in cat_levels_contrasts > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > > 86 if self.type == "numerical": > > 87 if not isinstance(num_columns, int): > > ---> 88 raise ValueError("For numerical factors, num_columns " > > 89 "must be an int") > > 90 if categories is not None: > > > > ValueError: For numerical factors, num_columns must be an int > > BTW, I use Python 2.7 on Canopy. > > patsy: VERSION 0.4.0 > > Thanks, When I use this code snippet, copied from the wb, it is also wrong: import numpy as np import pandas as pd import patsy time = np.tile([1, 2, 3, 4], 3) country = np.repeat(['a', 'b', 'c'], 4) event_int = np.random.randint(0, 2, size=len(time)) df = pd.DataFrame({'event_int':event_int, 'time_day':time, 'country':country}) f0 = 'event_int ~ C(time_day):C(country) - 1' y,X0 = patsy.dmatrices(f0, df, return_type='dataframe') print len(X0.columns) I am new to these packages. I don't know why it is correct for other users. Thanks, From breamoreboy at yahoo.co.uk Wed Dec 16 06:33:39 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 16 Dec 2015 11:33:39 +0000 Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: References: Message-ID: On 16/12/2015 10:44, Robert wrote: > Hi, > > When I run the following code, there is an error: > > ValueError: For numerical factors, num_columns must be an int > > > ================ > import numpy as np > import pandas as pd > from patsy import dmatrices > from sklearn.linear_model import LogisticRegression > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > zipped = list(zip(X,y)) > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > ======================= > > I have check 'df' is this type: > ============= > type(df) > Out[25]: pandas.core.frame.DataFrame > ============= > > I cannot figure out where the problem is. Can you help me? > Thanks. > > Error message: > .......... > > > --------------------------------------------------------------------------- > ValueError Traceback (most recent call last) > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > 18 > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > 20 > 21 y = np.ravel(y) > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > --> 297 NA_action, return_type) > 298 if lhs.shape[1] == 0: > 299 raise PatsyError("model is missing required outcome variables") > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > 150 return iter([data]) > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > --> 152 NA_action) > 153 if design_infos is not None: > 154 return build_design_matrices(design_infos, data, > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > 55 data_iter_maker, > 56 eval_env, > ---> 57 NA_action) > 58 else: > 59 return None > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > 704 factor_states[factor], > 705 num_columns=num_column_counts[factor], > --> 706 categories=None) > 707 else: > 708 assert factor in cat_levels_contrasts > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > 86 if self.type == "numerical": > 87 if not isinstance(num_columns, int): > ---> 88 raise ValueError("For numerical factors, num_columns " > 89 "must be an int") > 90 if categories is not None: > > ValueError: For numerical factors, num_columns must be an int > Slap the ValueError into a search engine and the first hit is https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From framstag at rus.uni-stuttgart.de Wed Dec 16 07:44:16 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Wed, 16 Dec 2015 12:44:16 +0000 (UTC) Subject: subprocess.call with non-ASCII arguments? References: Message-ID: Dennis Lee Bieber wrote: > >I want to create a zip file within a Python 2.7 program on windows. > > > >My code: > > > > cmd = ['7za.exe','a','-tzip',archive] + files > > status = subprocess.call(cmd) > > > My first thought would be... > > WHY spawn an OS dependent subprocess... > > Python has a zipfile library that is portable between OS. Along with > libraries for gzip, bzip2, and tarfiles... Great hint! With the python modules zipfile and tarfile I have no more problems with non-ASCII filenames! It needed a little bit more programming with os.walk(), because zipfile cannot add directories recursivly. S:\>python fexit.py * framstag Container name: test creating C:\Users\admin\AppData\Local\Temp\fex\test.zip zip dist\fexit.exe zip mf.cmd zip fex.ico zip fexit.spec zip build\fexit\fexit.exe.manifest zip build\fexit\out00-Analysis.toc zip build\fexit\out00-EXE.toc zip build\fexit\out00-PKG.pkg zip build\fexit\out00-PKG.toc zip build\fexit\out00-PYZ.pyz zip build\fexit\out00-PYZ.toc zip build\fexit\out00-Tree.toc zip build\fexit\out01-Tree.toc zip build\fexit\warnfexit.txt zip fexit.py zip tar.py zip zip.py Recipient: framstag at rus.uni-stuttgart.de test.zip: 13 MB of 13 MB (100%) 28540 kB/s -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From framstag at rus.uni-stuttgart.de Wed Dec 16 08:18:54 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Wed, 16 Dec 2015 13:18:54 +0000 (UTC) Subject: Tk alternative to askopenfilename and askdirectory? Message-ID: Is there an alternative to Tk's askopenfilename() and askdirectory()? I want to select a files and directories within one widget, but askopenfilename() let me only select files and askdirectory() let me only select directories. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From fsn761304 at gmail.com Wed Dec 16 09:04:37 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 06:04:37 -0800 (PST) Subject: Why my image is in bad quality ? Message-ID: I'm trying to make OCR-recognition on a screenshot, after screenshot taken it goes to pibxbuffer, which content goes to pytesseract. But after using pixbuffer image quality is bad (I tried to save it in a directory, instead of pixbuffer, and looked at it). Below is the problematic snippets of code, further is the whole function. pixbufObj = Gdk.pixbuf_get_from_window(window, x, y, width, height) ... image = Image.frombuffer("RGB", (width, height), pixbufObj.get_pixels(), 'raw', 'RGB', 0, 1) image = image.resize((width*20,height*20), Image.ANTIALIAS) ... print(pytesseract.image_to_string(image)) Full function: def takeScreenshot(self, x, y, width = 150, height = 30): self.width=width self.height=height window = Gdk.get_default_root_window() #x, y, width, height = window.get_geometry() #print("The size of the root window is {} x {}".format(width, height)) # get_from_drawable() was deprecated. See: # https://developer.gnome.org/gtk3/stable/ch24s02.html#id-1.6.3.4.7 pixbufObj = Gdk.pixbuf_get_from_window(window, x, y, width, height) height = pixbufObj.get_height() width = pixbufObj.get_width() image = Image.frombuffer("RGB", (width, height), pixbufObj.get_pixels(), 'raw', 'RGB', 0, 1) image = image.resize((width*20,height*20), Image.ANTIALIAS) #image.save("saved.png") print(pytesseract.image_to_string(image)) print("takenScreenshot:",x,y) From denismfmcmahon at gmail.com Wed Dec 16 09:15:00 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 16 Dec 2015 14:15:00 -0000 (UTC) Subject: Why my image is in bad quality ? References: Message-ID: On Wed, 16 Dec 2015 06:04:37 -0800, fsn761304 wrote: > I'm trying to make OCR-recognition on a screenshot, after screenshot > taken it goes to pibxbuffer, which content goes to pytesseract. > But after using pixbuffer image quality is bad > image = image.resize((width*20,height*20), Image.ANTIALIAS) This appears to attempt to extrapolate 400 pixels from each pixel in the original image. That only works on TV crime dramas, you can't do it in real life. -- Denis McMahon, denismfmcmahon at gmail.com From fsn761304 at gmail.com Wed Dec 16 09:21:50 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 06:21:50 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: References: Message-ID: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> On Wednesday, December 16, 2015 at 6:18:00 PM UTC+4, Denis McMahon wrote: > On Wed, 16 Dec 2015 06:04:37 -0800, fsn761304 wrote: > > > I'm trying to make OCR-recognition on a screenshot, after screenshot > > taken it goes to pibxbuffer, which content goes to pytesseract. > > But after using pixbuffer image quality is bad > > > image = image.resize((width*20,height*20), Image.ANTIALIAS) > > This appears to attempt to extrapolate 400 pixels from each pixel in the > original image. > > That only works on TV crime dramas, you can't do it in real life. > > -- > Denis McMahon, denismfmcmahon at gmail.com I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. from pytesseract import image_to_string from PIL import Image im = Image.open("screen.png") print(im) im = im.resize((214*20,26*20), Image.ANTIALIAS) print(image_to_string(im)) From rosuav at gmail.com Wed Dec 16 09:33:36 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 01:33:36 +1100 Subject: Why my image is in bad quality ? In-Reply-To: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> Message-ID: On Thu, Dec 17, 2015 at 1:21 AM, wrote: > I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. > > from pytesseract import image_to_string > from PIL import Image > > im = Image.open("screen.png") > print(im) > im = im.resize((214*20,26*20), Image.ANTIALIAS) > print(image_to_string(im)) If you need to scale by 20x20 to get the text recognition to work, I would recommend using something other than an anti-alias filter. Omit the second argument to use a simpler algorithm; you'll get a blocky result, which might parse more cleanly for you. ChrisA From rxjwg98 at gmail.com Wed Dec 16 09:50:17 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 06:50:17 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: References: Message-ID: <51b673c2-589d-4141-8b80-ef17318a9218@googlegroups.com> On Wednesday, December 16, 2015 at 6:34:21 AM UTC-5, Mark Lawrence wrote: > On 16/12/2015 10:44, Robert wrote: > > Hi, > > > > When I run the following code, there is an error: > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > ================ > > import numpy as np > > import pandas as pd > > from patsy import dmatrices > > from sklearn.linear_model import LogisticRegression > > > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > > > zipped = list(zip(X,y)) > > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > ======================= > > > > I have check 'df' is this type: > > ============= > > type(df) > > Out[25]: pandas.core.frame.DataFrame > > ============= > > > > I cannot figure out where the problem is. Can you help me? > > Thanks. > > > > Error message: > > .......... > > > > > > --------------------------------------------------------------------------- > > ValueError Traceback (most recent call last) > > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > 18 > > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > 20 > > 21 y = np.ravel(y) > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > > --> 297 NA_action, return_type) > > 298 if lhs.shape[1] == 0: > > 299 raise PatsyError("model is missing required outcome variables") > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > > 150 return iter([data]) > > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > > --> 152 NA_action) > > 153 if design_infos is not None: > > 154 return build_design_matrices(design_infos, data, > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > > 55 data_iter_maker, > > 56 eval_env, > > ---> 57 NA_action) > > 58 else: > > 59 return None > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > > 704 factor_states[factor], > > 705 num_columns=num_column_counts[factor], > > --> 706 categories=None) > > 707 else: > > 708 assert factor in cat_levels_contrasts > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > > 86 if self.type == "numerical": > > 87 if not isinstance(num_columns, int): > > ---> 88 raise ValueError("For numerical factors, num_columns " > > 89 "must be an int") > > 90 if categories is not None: > > > > ValueError: For numerical factors, num_columns must be an int > > > > Slap the ValueError into a search engine and the first hit is > https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence Hi, I don't see a solution to my problem. I find the following demo code from https://patsy.readthedocs.org/en/v0.1.0/API-reference.html#patsy.dmatrix It doesn't work either on the Canopy. Does it work on your computer? Thanks, ///////////// demo_data("a", "x", nlevels=3) Out[134]: {'a': ['a1', 'a2', 'a3', 'a1', 'a2', 'a3'], 'x': array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788])} mat = dmatrix("a + x", demo_data("a", "x", nlevels=3)) From jorge.conrado at cptec.inpe.br Wed Dec 16 10:19:26 2015 From: jorge.conrado at cptec.inpe.br (jorge.conrado at cptec.inpe.br) Date: Wed, 16 Dec 2015 13:19:26 -0200 Subject: geostationary satellite data Message-ID: <53c3ebdd7e47e30a80bc0982568ff829@cptec.inpe.br> Hi, I dowmloaded some data from the Mirador NASA site: http://mirador.gsfc.nasa.gov/cgi-bin/mirador/presentNavigation.pl?tree=project&dataset=Global-merged%20IR%20Brightness%20Temperature%20Data&project=TRMM&dataGroup=Ancillary&version=001&CGISESSID=97f4b9244878c87819b2a1144d31e270 Each data have the dimension: 9896 x 3298 byte. I used to read the command : f = open('merg_2015110500_4km-pixel', mode='rb') image = f.read() Please, what can I do to visualize this data. Conrado From ganesh1pal at gmail.com Wed Dec 16 11:09:05 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 16 Dec 2015 21:39:05 +0530 Subject: does the order in which the modules are placed in a file matters ? Message-ID: Iam on python 2.7 and linux .I need to know if we need to place the modules in a particular or it doesn't matter at all order while writing the program For Example import os import shlex import subprocess import time import sys import logging import plaftform.cluster from util import run def main(): """ ---MAIN--- """ if __name__ == '__main__': main() In the above example : 1. Iam guessing may be the python modules like os , shlex etc come first and later the user defined modules like import plaftform.cluster .etc come latter Sorry if my question sounds dump , I was running pep8 and don't see its bothered much about it Regards, Ganesh From rosuav at gmail.com Wed Dec 16 11:14:09 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 03:14:09 +1100 Subject: does the order in which the modules are placed in a file matters ? In-Reply-To: References: Message-ID: On Thu, Dec 17, 2015 at 3:09 AM, Ganesh Pal wrote: > Iam on python 2.7 and linux .I need to know if we need to place the > modules in a particular or it doesn't matter at all > > order while writing the program > > For Example > > import os > import shlex > import subprocess > import time > import sys > import logging > import plaftform.cluster > from util import run The order of the import statements is the order the modules will get loaded up. As a general rule this won't matter; when it comes to standard library modules, you can generally assume that you can put them in any order without it making any difference. It's common to order them in some aesthetically-pleasing way (maybe alphabetical order, or maybe sort them by the length of the name - whatever you like). There is a broad convention that standard library modules get imported first, and modules that are part of the current project get imported afterwards. But even that doesn't usually matter very much. ChrisA From breamoreboy at yahoo.co.uk Wed Dec 16 11:15:47 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 16 Dec 2015 16:15:47 +0000 Subject: geostationary satellite data In-Reply-To: <53c3ebdd7e47e30a80bc0982568ff829@cptec.inpe.br> References: <53c3ebdd7e47e30a80bc0982568ff829@cptec.inpe.br> Message-ID: On 16/12/2015 15:19, jorge.conrado at cptec.inpe.br wrote: > > > Hi, > > > I dowmloaded some data from the Mirador NASA site: > > > http://mirador.gsfc.nasa.gov/cgi-bin/mirador/presentNavigation.pl?tree=project&dataset=Global-merged%20IR%20Brightness%20Temperature%20Data&project=TRMM&dataGroup=Ancillary&version=001&CGISESSID=97f4b9244878c87819b2a1144d31e270 > > > > Each data have the dimension: 9896 x 3298 byte. > > > I used to read the command : > > f = open('merg_2015110500_4km-pixel', mode='rb') > > image = f.read() > > > Please, what can I do to visualize this data. > > > Conrado http://pandas.pydata.org/ http://matplotlib.org/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From carl at oddbird.net Wed Dec 16 11:19:18 2015 From: carl at oddbird.net (Carl Meyer) Date: Wed, 16 Dec 2015 09:19:18 -0700 Subject: does the order in which the modules are placed in a file matters ? In-Reply-To: References: Message-ID: <56718F06.30300@oddbird.net> Hi Ganesh, On 12/16/2015 09:09 AM, Ganesh Pal wrote: > Iam on python 2.7 and linux .I need to know if we need to place the > modules in a particular or it doesn't matter at all > > order while writing the program As you've probably already noticed, it usually doesn't matter to Python (though it can become relevant in certain unusual circular-import cases). Most people will have some opinion about what constitutes good style, though. Opinions tend to look something like these (though details will vary): 1. All imports at the top of the module. 2. Standard library imports, then third-party imports, then local imports. 3. Sometimes the above types of imports are grouped with intervening blank lines. 4. Sometimes imports are alphabetized within those groups. > For Example > > import os > import shlex > import subprocess > import time > import sys > import logging > import plaftform.cluster > from util import run > > > def main(): > """ ---MAIN--- """ > > if __name__ == '__main__': > main() > > In the above example : > > 1. Iam guessing may be the python modules like os , shlex etc come > first and later the user defined modules like import > plaftform.cluster .etc come latter > > Sorry if my question sounds dump , I was running pep8 and don't see > its bothered much about it AFAIK the pep8 module doesn't care about import order. If you'd like to enforce an import order in your project, you can look at isort. [1] Carl [1] https://pypi.python.org/pypi/isort -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: OpenPGP digital signature URL: From lorenzofsutton at gmail.com Wed Dec 16 11:24:43 2015 From: lorenzofsutton at gmail.com (Lorenzo Sutton) Date: Wed, 16 Dec 2015 17:24:43 +0100 Subject: Tk alternative to askopenfilename and askdirectory? In-Reply-To: References: Message-ID: <5671904B.9060408@gmail.com> On 16/12/2015 14:18, Ulli Horlacher wrote: > Is there an alternative to Tk's askopenfilename() and askdirectory()? > > I want to select a files and directories within one widget, but > askopenfilename() let me only select files and askdirectory() let me only > select directories. > > I guess it would help if you could provide some information on your use case and what you want to achieve ;) Lorenzo. From fsn761304 at gmail.com Wed Dec 16 11:33:59 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 08:33:59 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> Message-ID: <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> On Wednesday, December 16, 2015 at 6:33:56 PM UTC+4, Chris Angelico wrote: > On Thu, Dec 17, 2015 at 1:21 AM, wrote: > > I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. > > > > from pytesseract import image_to_string > > from PIL import Image > > > > im = Image.open("screen.png") > > print(im) > > im = im.resize((214*20,26*20), Image.ANTIALIAS) > > print(image_to_string(im)) > > If you need to scale by 20x20 to get the text recognition to work, I > would recommend using something other than an anti-alias filter. Omit > the second argument to use a simpler algorithm; you'll get a blocky > result, which might parse more cleanly for you. > > ChrisA It didn't help to recognize words, the main problem is that image is inclined to the left, like backslash. From fsn761304 at gmail.com Wed Dec 16 11:35:36 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 08:35:36 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> Message-ID: <320725eb-4e0f-45d7-a1fb-a20b0a0c412d@googlegroups.com> On Wednesday, December 16, 2015 at 8:34:15 PM UTC+4, fsn7... at gmail.com wrote: > On Wednesday, December 16, 2015 at 6:33:56 PM UTC+4, Chris Angelico wrote: > > On Thu, Dec 17, 2015 at 1:21 AM, wrote: > > > I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. > > > > > > from pytesseract import image_to_string > > > from PIL import Image > > > > > > im = Image.open("screen.png") > > > print(im) > > > im = im.resize((214*20,26*20), Image.ANTIALIAS) > > > print(image_to_string(im)) > > > > If you need to scale by 20x20 to get the text recognition to work, I > > would recommend using something other than an anti-alias filter. Omit > > the second argument to use a simpler algorithm; you'll get a blocky > > result, which might parse more cleanly for you. > > > > ChrisA > > It didn't help to recognize words, the main problem is that image is inclined to the left, like backslash. ...and sometimes there are green horizontal lines above the image. From rosuav at gmail.com Wed Dec 16 11:41:07 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 03:41:07 +1100 Subject: Why my image is in bad quality ? In-Reply-To: <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> Message-ID: On Thu, Dec 17, 2015 at 3:33 AM, wrote: > On Wednesday, December 16, 2015 at 6:33:56 PM UTC+4, Chris Angelico wrote: >> On Thu, Dec 17, 2015 at 1:21 AM, wrote: >> > I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. >> > >> > from pytesseract import image_to_string >> > from PIL import Image >> > >> > im = Image.open("screen.png") >> > print(im) >> > im = im.resize((214*20,26*20), Image.ANTIALIAS) >> > print(image_to_string(im)) >> >> If you need to scale by 20x20 to get the text recognition to work, I >> would recommend using something other than an anti-alias filter. Omit >> the second argument to use a simpler algorithm; you'll get a blocky >> result, which might parse more cleanly for you. >> >> ChrisA > > It didn't help to recognize words, the main problem is that image is inclined to the left, like backslash. Interesting. I'm not sure what exactly is going on, as I can't see your image or the result, but is it possible that the text is getting wrapped? Try printing it to a file, then pulling the file up in a text editor with word wrap disabled. Maybe it'll look different. ChrisA From D.Strohl at F5.com Wed Dec 16 11:42:01 2015 From: D.Strohl at F5.com (Dan Strohl) Date: Wed, 16 Dec 2015 16:42:01 +0000 Subject: does the order in which the modules are placed in a file matters ? In-Reply-To: References: Message-ID: For the general modules it doesn't matter, however using if you are using any non-standard packages, and If there are duplicate names in any of the modules and if you import them with a "*" (as some packages suggest), it can cause you to end up referring to an object you were not intending to. For example, if you have found a package called "foo", and the instructions on it are to import it as: from foo import * Then you have another package called "bar" with the same instructions... so now you have: from foo import * from bar import * In both of these there is a class called "snafu", when you do this: from foo import * from bar import * SITUATION = snafu() You are going to get bar.snafu(), not foo.snafu() This can of course be gotten around by doing: import foo import bar SITUATION = foo.snafu() (or a number of other approaches using "as" etc...) Note, using * is dis-recommended, though pretty often done, for more information on using *, see: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package Dan Strohl -----Original Message----- From: Python-list [mailto:python-list-bounces+d.strohl=f5.com at python.org] On Behalf Of Chris Angelico Sent: Wednesday, December 16, 2015 8:14 AM Cc: python-list at python.org Subject: Re: does the order in which the modules are placed in a file matters ? On Thu, Dec 17, 2015 at 3:09 AM, Ganesh Pal wrote: > Iam on python 2.7 and linux .I need to know if we need to place the > modules in a particular or it doesn't matter at all > > order while writing the program > > For Example > > import os > import shlex > import subprocess > import time > import sys > import logging > import plaftform.cluster > from util import run The order of the import statements is the order the modules will get loaded up. As a general rule this won't matter; when it comes to standard library modules, you can generally assume that you can put them in any order without it making any difference. It's common to order them in some aesthetically-pleasing way (maybe alphabetical order, or maybe sort them by the length of the name - whatever you like). There is a broad convention that standard library modules get imported first, and modules that are part of the current project get imported afterwards. But even that doesn't usually matter very much. ChrisA -- https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Wed Dec 16 11:49:18 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 03:49:18 +1100 Subject: does the order in which the modules are placed in a file matters ? In-Reply-To: References: Message-ID: On Thu, Dec 17, 2015 at 3:42 AM, Dan Strohl wrote: > For the general modules it doesn't matter, however using if you are using any non-standard packages, and If there are duplicate names in any of the modules and if you import them with a "*" (as some packages suggest), it can cause you to end up referring to an object you were not intending to. > > [chomp] > > Note, using * is dis-recommended, though pretty often done, for more information on using *, see: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package This is exactly why (well, one of the reasons why) star imports are generally not recommended. There are a small number of modules that have promised to keep their namespaces clean in order to make this viable, but even there, it has issues of confusion. There are a few good places to use star imports, such as when you wrap one module in another; I would STRONGLY recommend against using two star imports in a single file, without being VERY sure of what you're doing. ChrisA From fsn761304 at gmail.com Wed Dec 16 12:01:28 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 09:01:28 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> Message-ID: <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> On Wednesday, December 16, 2015 at 8:41:23 PM UTC+4, Chris Angelico wrote: > On Thu, Dec 17, 2015 at 3:33 AM, wrote: > > On Wednesday, December 16, 2015 at 6:33:56 PM UTC+4, Chris Angelico wrote: > >> On Thu, Dec 17, 2015 at 1:21 AM, wrote: > >> > I tried also another code (see below) and without scaling by 20 quality of recognition was very bad. > >> > > >> > from pytesseract import image_to_string > >> > from PIL import Image > >> > > >> > im = Image.open("screen.png") > >> > print(im) > >> > im = im.resize((214*20,26*20), Image.ANTIALIAS) > >> > print(image_to_string(im)) > >> > >> If you need to scale by 20x20 to get the text recognition to work, I > >> would recommend using something other than an anti-alias filter. Omit > >> the second argument to use a simpler algorithm; you'll get a blocky > >> result, which might parse more cleanly for you. > >> > >> ChrisA > > > > It didn't help to recognize words, the main problem is that image is inclined to the left, like backslash. > > Interesting. I'm not sure what exactly is going on, as I can't see > your image or the result, but is it possible that the text is getting > wrapped? Try printing it to a file, then pulling the file up in a text > editor with word wrap disabled. Maybe it'll look different. > > ChrisA When I saved image to a directory it was ok (quality) and recognition was good. (there are commented string, which saves into dictory: #image.save("saved.png") ) It seems I did something wrong with image buffer. From paul.hermeneutic at gmail.com Wed Dec 16 12:01:35 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Wed, 16 Dec 2015 10:01:35 -0700 Subject: Windows 10 and PYODBC In-Reply-To: References: Message-ID: On Dec 15, 2015 1:32 PM, "William Abdo" wrote: > > issue 25875 created > I put it in the wrong area the first time. > First time bug tracker user errors. My apologies, William. I thought bugs.python.org would be the right place to put it. I was wrong. From pkpearson at nowhere.invalid Wed Dec 16 12:04:00 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 16 Dec 2015 17:04:00 GMT Subject: geostationary satellite data References: Message-ID: On Wed, 16 Dec 2015 13:19:26 -0200, jorge.conrado at cptec.inpe.br wrote: > > I dowmloaded some data from the Mirador NASA site: > > http://mirador.gsfc.nasa.gov/cgi-bin/mirador/presentNavigation.pl?tree=project&dataset=Global-merged%20IR%20Brightness%20Temperature%20Data&project=TRMM&dataGroup=Ancillary&version=001&CGISESSID=97f4b9244878c87819b2a1144d31e270 > > Each data have the dimension: 9896 x 3298 byte. > > I used to read the command : > > f = open('merg_2015110500_4km-pixel', mode='rb') > > image = f.read() > > Please, what can I do to visualize this data. You provide a URL to a web page, but you're opening a file. Can you tell us what kind of file you downloaded? I grabbed a random file from that site, and it arrived with the name "merg_2015120123_4km-pixel.Z". After I ran "uncompress" on it, it was named "merg_2015120123_4km-pixel", which looks much like your filename, so I guess this is what you've done. When I dump it as bytes, I get a lot of this: 00000100 ff ff c0 c0 c1 c2 c2 c2 c2 c3 c3 c3 c3 c4 c4 c3 00000110 c3 c3 c1 c1 c0 c0 ff ff ff ff ff ff ff ff c1 c1 00000120 c3 c4 c4 c4 c3 c3 c3 c3 c1 ff ff ff ff ff ff ff 00000130 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff 00000140 ff ff ff ff ff ff ff c0 c0 c1 c3 c3 c3 c3 c4 c4 00000150 c4 c4 c4 c3 c3 c3 c4 c4 c3 c3 c3 c3 c3 c3 c3 c3 00000160 c4 c4 c4 c4 c4 c5 c5 c6 c7 c7 c7 c7 c5 c5 c5 c6 00000170 c6 c6 c6 c6 c4 c4 c4 c4 c4 c3 c3 c3 c3 c3 c3 c3 00000180 c2 c2 c2 c3 c3 c3 c4 c4 c4 c4 c4 c4 c4 c5 c5 c6 00000190 c6 c6 c6 c6 c6 c7 c7 c7 c7 c7 c7 c7 c7 c7 c7 c7 000001a0 c7 c7 c7 c8 c8 c8 c8 c8 c9 c9 c9 c9 c9 c9 c9 c9 The file is 65274016 bytes long. You claim the dimensions are 9896 x 3298, but that comes out to half that number (32637008), so I'll bet the real dimensions are 9896 x 6596, with one byte per pixel. I think this image format is called "raw". I haven't the time and expertise to settle this for you, but the solution is probably going to look something like this: >>> rawdata = open("merg_2015120123_4km-pixel", "rb").read() >>> from PIL import Image >>> img = Image.fromstring("L", (9896, 6596), rawdata) >>> img.save("temp.png") -- To email me, substitute nowhere->runbox, invalid->com. From rosuav at gmail.com Wed Dec 16 12:08:02 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 04:08:02 +1100 Subject: geostationary satellite data In-Reply-To: References: Message-ID: On Thu, Dec 17, 2015 at 4:04 AM, Peter Pearson wrote: > The file is 65274016 bytes long. You claim the dimensions are > 9896 x 3298, but that comes out to half that number (32637008), so I'll > bet the real dimensions are 9896 x 6596, with one byte per pixel. > I think this image format is called "raw". It could be 16 bits per pixel. Without knowing a lot more about the source of the image and its format, it's hard to say with any certainty. ChrisA From framstag at rus.uni-stuttgart.de Wed Dec 16 12:08:23 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Wed, 16 Dec 2015 17:08:23 +0000 (UTC) Subject: Tk alternative to askopenfilename and askdirectory? References: Message-ID: Lorenzo Sutton wrote: > On 16/12/2015 14:18, Ulli Horlacher wrote: > > Is there an alternative to Tk's askopenfilename() and askdirectory()? > > > > I want to select a files and directories within one widget, but > > askopenfilename() let me only select files and askdirectory() let me only > > select directories. > > > > > > I guess it would help if you could provide some information on your use > case and what you want to achieve ;) A (Windows) user shall upload files and/or directories. For this, he needs to select them. In the current implementation, the user has to decide first whether he wants to upload a file or a directory. I want to eliminate this step. http://fex.rus.uni-stuttgart.de/fop/rC2meOrd/X-20151216180501.png drag&drop works only for files with ASCII filenames. -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From fsn761304 at gmail.com Wed Dec 16 12:17:55 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 09:17:55 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> Message-ID: ...here is the bad image: http://wikisend.com/download/748118/saved.png From pkpearson at nowhere.invalid Wed Dec 16 12:30:06 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 16 Dec 2015 17:30:06 GMT Subject: geostationary satellite data References: Message-ID: On Thu, 17 Dec 2015 04:08:02 +1100, Chris Angelico wrote: > On Thu, Dec 17, 2015 at 4:04 AM, Peter Pearson > wrote: >> The file is 65274016 bytes long. You claim the dimensions are >> 9896 x 3298, but that comes out to half that number (32637008), so I'll >> bet the real dimensions are 9896 x 6596, with one byte per pixel. >> I think this image format is called "raw". > > It could be 16 bits per pixel. Without knowing a lot more about the > source of the image and its format, it's hard to say with any > certainty. Agreed. It's annoying when an agency goes to the trouble of making huge datasets available online, but fails to identify the format. But the 16-bits-per-pixel hypothesis is unlikely, given that each byte tends to echo its predecessor: 0000130 ffff ffff ffff ffff ffff ffff ffff ffff 0000140 ffff ffff ffff c0ff c1c0 c3c3 c3c3 c4c4 0000150 c4c4 c3c4 c3c3 c4c4 c3c3 c3c3 c3c3 c3c3 0000160 c4c4 c4c4 c5c4 c6c5 c7c7 c7c7 c5c5 c6c5 When you decompose this data file as a one-byte-per-pixel, 9896 x 6596 image, the resulting image shows two nearly identical strips, one above the other. That suggests interlacing, except that the top strip has some "bites" missing that aren't missing from the bottom strip. My best guess is that it's just two images glued together, maybe taken at different wavelengths. -- To email me, substitute nowhere->runbox, invalid->com. From rosuav at gmail.com Wed Dec 16 12:37:26 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 04:37:26 +1100 Subject: geostationary satellite data In-Reply-To: References: Message-ID: On Thu, Dec 17, 2015 at 4:30 AM, Peter Pearson wrote: > Agreed. It's annoying when an agency goes to the trouble of making > huge datasets available online, but fails to identify the format. > > But the 16-bits-per-pixel hypothesis is unlikely, given that each > byte tends to echo its predecessor: > > 0000130 ffff ffff ffff ffff ffff ffff ffff ffff > 0000140 ffff ffff ffff c0ff c1c0 c3c3 c3c3 c4c4 > 0000150 c4c4 c3c4 c3c3 c4c4 c3c3 c3c3 c3c3 c3c3 > 0000160 c4c4 c4c4 c5c4 c6c5 c7c7 c7c7 c5c5 c6c5 Hmm. With just a few exceptions. Maybe it's two channels or something - is that what you mean by "taken at different wavelengths"? Definitely it's begging for format identification from the source. ChrisA From pkpearson at nowhere.invalid Wed Dec 16 12:53:18 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 16 Dec 2015 17:53:18 GMT Subject: geostationary satellite data References: Message-ID: On Thu, 17 Dec 2015 04:37:26 +1100, Chris Angelico wrote: > On Thu, Dec 17, 2015 at 4:30 AM, Peter Pearson > wrote: >> Agreed. It's annoying when an agency goes to the trouble of making >> huge datasets available online, but fails to identify the format. >> >> But the 16-bits-per-pixel hypothesis is unlikely, given that each >> byte tends to echo its predecessor: >> >> 0000130 ffff ffff ffff ffff ffff ffff ffff ffff >> 0000140 ffff ffff ffff c0ff c1c0 c3c3 c3c3 c4c4 >> 0000150 c4c4 c3c4 c3c3 c4c4 c3c3 c3c3 c3c3 c3c3 >> 0000160 c4c4 c4c4 c5c4 c6c5 c7c7 c7c7 c5c5 c6c5 > > Hmm. With just a few exceptions. Maybe it's two channels or something > - is that what you mean by "taken at different wavelengths"? Yes; but as described below, I now think they're taken at different times. > Definitely it's begging for format identification from the source. Agreed, again. But it's hard to set this kind of problem aside. I split it into two images, thusly: >>> half = len(rawdata)/2 >>> Image.fromstring("L", (9896, 3298), rawdata[0:half]).save("temp3.png") >>> Image.fromstring("L", (9896, 3298), rawdata[half:]).save("temp4.png") Flipping between the resulting two images, one sees slight displacements of the large-scale swirly structures, so I'm pretty sure the two images correspond to slightly different times. (I use the current GOES West northern-hemisphere image as my desktop, so I'm pretty familiar with the movements of atmospheric swirly thingies.) This feels solved-enough to set aside now. -- To email me, substitute nowhere->runbox, invalid->com. From george.trojan at noaa.gov Wed Dec 16 13:22:40 2015 From: george.trojan at noaa.gov (George Trojan) Date: Wed, 16 Dec 2015 18:22:40 +0000 Subject: Python 3.1 test issue Message-ID: <5671ABF0.3040500@noaa.gov> I installed Python 3.1 on RHEL 7.2. The command make test hangs (or takes a lot of time) on test_subprocess. [396/397] test_subprocess ^C Test suite interrupted by signal SIGINT. 5 tests omitted: test___all__ test_distutils test_site test_socket test_warnings 381 tests OK. 4 tests altered the execution environment: test___all__ test_distutils test_site test_warnings 11 tests skipped: test_devpoll test_kqueue test_msilib test_ossaudiodev test_startfile test_tix test_tk test_ttk_guionly test_winreg test_winsound test_zipfile64 make: *** [test] Error 1 CPU was at 100% all the time for process gtrojan 15758 8907 94 17:29 pts/6 00:06:47 /home/gtrojan/Downloads/Python-3.5.1/python -R -bb -E -Wdefault -Werror::BytesWarning -X faulthandler -m test.regrtest --slaveargs [["test_socket", 0, false], {"huntrleaks": false, "match_tests": null, "failfast": false, "output_on_failure": false, "use_resources": ["curses", "network", "decimal", "cpu", "subprocess", "urlfetch"], "pgo": false, "timeout": null}] gtrojan 22889 336 0 17:36 pts/11 00:00:00 grep --color=auto 15758 Is this a problem? George From robin.koch at t-online.de Wed Dec 16 13:57:54 2015 From: robin.koch at t-online.de (Robin Koch) Date: Wed, 16 Dec 2015 19:57:54 +0100 Subject: geostationary satellite data In-Reply-To: References: Message-ID: Am 16.12.2015 um 18:30 schrieb Peter Pearson: > On Thu, 17 Dec 2015 04:08:02 +1100, Chris Angelico wrote: >> >> It could be 16 bits per pixel. Without knowing a lot more about the >> source of the image and its format, it's hard to say with any >> certainty. > > Agreed. It's annoying when an agency goes to the trouble of making > huge datasets available online, but fails to identify the format. http://www.cpc.ncep.noaa.gov/products/global_precip/html/README says (among other things): | Each record is a 9896 x 3298 Fortran array of IR brightness | temperatures that have been scaled to fit into 1-byte by subtracting | "75" from each datum. Therefore it is necessary for the user to add a | value of "75" to each data value when using the data. HTH a little, -- Robin Koch From tjreedy at udel.edu Wed Dec 16 15:07:52 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Dec 2015 15:07:52 -0500 Subject: Python 3.1 test issue In-Reply-To: <5671ABF0.3040500@noaa.gov> References: <5671ABF0.3040500@noaa.gov> Message-ID: On 12/16/2015 1:22 PM, George Trojan wrote: > I installed Python 3.1 on RHEL 7.2. According to the output below, you installed 3.5.1. Much better than the years old 3.1. > The command make test hangs (or > takes a lot of time on test_subprocess > [396/397] test_subprocess This indicates that everything up to this point passed, else there would be '/1' or higher after '397'. > ^C > Test suite interrupted by signal SIGINT. There is at least one test that normally take a couple of minutes, but see below. > 5 tests omitted: > test___all__ test_distutils test_site test_socket test_warnings > 381 tests OK. > 4 tests altered the execution environment: > test___all__ test_distutils test_site test_warnings > 11 tests skipped: > test_devpoll test_kqueue test_msilib test_ossaudiodev > test_startfile test_tix test_tk test_ttk_guionly test_winreg > test_winsound test_zipfile64 > make: *** [test] Error 1 > > CPU was at 100% all the time for process > > gtrojan 15758 8907 94 17:29 pts/6 00:06:47 > /home/gtrojan/Downloads/Python-3.5.1/python -R -bb -E -Wdefault > -Werror::BytesWarning -X faulthandler -m test.regrtest --slaveargs Running 'python -m test -h' displays a long help messages. ('-m test' abbreviates '-m test.regrtest' on 3.x.) Option '--slaveargs ARGS' is listed without anything said about the meaning of ARGS. I reformatted the ARGS list to make it more readable. > [["test_socket", 0, false], This appears to pass arguments to a specific test, test_socket. I would guess this is done by setting sys.argv. This is the first I knew about this. What follows of a dict of options. Most could have been set with normal --option flags. Most are the defaults. > {"huntrleaks": false, > "match_tests": null, > "failfast": false, > "output_on_failure": false, > "use_resources": > ["curses", "network", "decimal", "cpu", "subprocess", "urlfetch"], > "pgo": false, > "timeout": null > } > ] The relevant non-default is 'use_resources'. In particular, 'cpu' runs 'certain CPU-heavy tests', and 'subprocess' runs all subprocess tests. I ran both 'python -m test -usubprocess test_subprocess' and 'python -m test -ucpu -usubprocess test_subprocess and both took about the same time and less than a minute. The only thing that puzzles me is that I don't see '"randomize": true' in the dict above, but test_subprocess is 317 in the default alphabetical order, not 396. You might try re-running with defaults: python -m test. -- Terry Jan Reedy From bc at freeuk.com Wed Dec 16 16:36:02 2015 From: bc at freeuk.com (BartC) Date: Wed, 16 Dec 2015 21:36:02 +0000 Subject: Why my image is in bad quality ? In-Reply-To: References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> Message-ID: On 16/12/2015 17:17, fsn761304 at gmail.com wrote: > ...here is the bad image: http://wikisend.com/download/748118/saved.png > This is 3000x600 pixels; what was the original size? (150x30?) What does the original look like? You need to test step by step to see at what point it goes wrong. You're scaling by 20 (which is a massive amount); what happens when scaling by 1? And anti-alias is turned off? (Which might let you see by how many pixels each successive line is out and could give a clue.) It does seem as though something is going amiss with recognising the image dimensions, or you've inadvertently applied a 'shear' or 'slant' transformation. (Maybe you can apply a reverse transform to fix it!) -- Bartc From fsn761304 at gmail.com Wed Dec 16 16:53:38 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Wed, 16 Dec 2015 13:53:38 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> Message-ID: <2c67af3c-6954-4398-81c8-0459025bc5c7@googlegroups.com> On Thursday, December 17, 2015 at 1:36:55 AM UTC+4, BartC wrote: > On 16/12/2015 17:17, fsn761304 at gmail.com wrote: > > ...here is the bad image: http://wikisend.com/download/748118/saved.png > > > > This is 3000x600 pixels; what was the original size? (150x30?) > > What does the original look like? > > You need to test step by step to see at what point it goes wrong. You're > scaling by 20 (which is a massive amount); what happens when scaling by > 1? And anti-alias is turned off? (Which might let you see by how many > pixels each successive line is out and could give a clue.) > > It does seem as though something is going amiss with recognising the > image dimensions, or you've inadvertently applied a 'shear' or 'slant' > transformation. (Maybe you can apply a reverse transform to fix it!) > > -- > Bartc Original size: 150x30 Original image the same, but without skew (usual upright letters). When scaling by less than 20 recognition quality is bad (in another code, which doesn't use buffer, screenshot, but loads image from a directory). Antialias makes no difference. Shear, slant - ok, show me how. From gordon at panix.com Wed Dec 16 17:12:02 2015 From: gordon at panix.com (John Gordon) Date: Wed, 16 Dec 2015 22:12:02 +0000 (UTC) Subject: error reading api with urllib References: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Message-ID: In <9aa21642-765b-4666-8c66-a6dab9928c37 at googlegroups.com> simian336 at gmail.com writes: > Bad Request > b'' That probably means you aren't using one of the recognized methods (i.e. GET, POST, etc.) It doesn't look like you are specifying one of these methods on your Request object. Try doing that. (It works in your browser because it defaults to GET automatically.) -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From bc at freeuk.com Wed Dec 16 18:20:59 2015 From: bc at freeuk.com (BartC) Date: Wed, 16 Dec 2015 23:20:59 +0000 Subject: Why my image is in bad quality ? In-Reply-To: <2c67af3c-6954-4398-81c8-0459025bc5c7@googlegroups.com> References: <424a0169-fe5b-4650-9673-46d265290c30@googlegroups.com> <94c84373-db80-43cd-a705-a89e695e140a@googlegroups.com> <0f56d024-0193-4d28-97ac-7d71c806f379@googlegroups.com> <2c67af3c-6954-4398-81c8-0459025bc5c7@googlegroups.com> Message-ID: On 16/12/2015 21:53, fsn761304 at gmail.com wrote: > On Thursday, December 17, 2015 at 1:36:55 AM UTC+4, BartC wrote: >> You need to test step by step to see at what point it goes wrong. You're >> scaling by 20 (which is a massive amount); what happens when scaling by >> 1? And anti-alias is turned off? (Which might let you see by how many >> pixels each successive line is out and could give a clue.) >> >> It does seem as though something is going amiss with recognising the >> image dimensions, or you've inadvertently applied a 'shear' or 'slant' >> transformation. (Maybe you can apply a reverse transform to fix it!) >> >> -- >> Bartc > > Original size: 150x30 > Original image the same, but without skew (usual upright letters). > When scaling by less than 20 recognition quality is bad (in another code, which doesn't use buffer, screenshot, but loads image from a directory). > Antialias makes no difference. > Shear, slant - ok, show me how. I've played with a 150x30 reduced image. The best I can do is apply a shift that makes the letters slant the other way, but at only half the angle. Trying to get them upright makes them wobbly. (I did this with some code - not Python - that read each pixel and stored it at a shifted position. But this is because I'm not familiar with manipulation programs.) So whatever's gone wrong might be more complex. You should forget about recognition quality, and find out what it is that's applying the skew (another name for shear or slant). That seems to be being applied before the scaling, which is giving the 'steps' in the sloping edges. -- Bartc From ian.g.kelly at gmail.com Wed Dec 16 18:22:49 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 16 Dec 2015 16:22:49 -0700 Subject: error reading api with urllib In-Reply-To: References: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Message-ID: On Tue, Dec 15, 2015 at 7:46 PM, Simian wrote: > I added > > except urllib.error.HTTPError as e: > print('HTTP Errpr') > print('Error code: ', e.code) > > to my try and I recieve... > > 400: ('Bad Request', > 'Bad request syntax or unsupported method'), > > but processing the string with a browser works fine. Have you tried requesting the same URL with curl? From ian.g.kelly at gmail.com Wed Dec 16 18:24:54 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 16 Dec 2015 16:24:54 -0700 Subject: error reading api with urllib In-Reply-To: References: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Message-ID: On Wed, Dec 16, 2015 at 3:12 PM, John Gordon wrote: > In <9aa21642-765b-4666-8c66-a6dab9928c37 at googlegroups.com> simian336 at gmail.com writes: > >> Bad Request >> b'' > > > That probably means you aren't using one of the recognized methods > (i.e. GET, POST, etc.) > > It doesn't look like you are specifying one of these methods on your > Request object. Try doing that. > > (It works in your browser because it defaults to GET automatically.) urllib.request.Request also defaults to GET unless the request includes data, in which case it defaults to POST. I would be more inclined to suspect a problem with the stored procedure being called. From futurewavewebdevelopment at gmail.com Wed Dec 16 19:03:35 2015 From: futurewavewebdevelopment at gmail.com (Bruce Whealton) Date: Wed, 16 Dec 2015 16:03:35 -0800 (PST) Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python Message-ID: I watched one training video that discussed Python and Tkinter. Like many similar tutorials from online training sites, I was left scratching my head. What seems to be blatantly missing is how this would be distributed. In the first mentioned tutorial from Lynda.com the Tkinter app was related to a web page. However, the browser cannot run Python Bytecode or Python Scripts. Surely, one is going to want to create GUI apps for users that are not Python Developers. I would not think to ask someone to install Python on their system and make sure it is added to the path. Maybe it is not so hard for the non-technical, average users. I would want to package in some way so that when launched, it installs whatever is needed on the end user's computer. How is this done? Are there common practices for this? Thanks, Bruce From rantingrickjohnson at gmail.com Wed Dec 16 19:28:00 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Wed, 16 Dec 2015 16:28:00 -0800 (PST) Subject: Tk alternative to askopenfilename and askdirectory? In-Reply-To: References: Message-ID: On Wednesday, December 16, 2015 at 7:19:25 AM UTC-6, Ulli Horlacher wrote: > Is there an alternative to Tk's askopenfilename() and askdirectory()? > > I want to select a files and directories within one widget, but > askopenfilename() let me only select files and askdirectory() let me only > select directories. Oh i understand. What you opine for is something like: askOpenFileOrDir() -- which displays a dialog from which a file or directory can be selected by the user. From auriocus at gmx.de Wed Dec 16 19:29:00 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Thu, 17 Dec 2015 01:29:00 +0100 Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: Am 17.12.15 um 01:03 schrieb Bruce Whealton: > I watched one training video that discussed Python and Tkinter. Like many similar tutorials from online training sites, I was left scratching my head. > > What seems to be blatantly missing is how this would be distributed. In the first mentioned tutorial from Lynda.com the Tkinter app was related to a web page. However, the browser cannot run Python Bytecode or Python Scripts. > > Surely, one is going to want to create GUI apps for users that are not Python Developers. I would not think to ask someone to install Python on their system and make sure it is added to the path. Maybe it is not so hard for the non-technical, average users. > > I would want to package in some way so that when launched, it installs whatever is needed on the end user's computer. How is this done? > Are there common practices for this? > Thanks, > Bruce > On option is pyinstaller or py2exe, which converts a Python script + dependencies into a single file (single directory) executable. Sometimes you must give them hints what to include, but in general it works well. It may create very large packages (if you include numpy/scipy/matplotlib, you'll end up with ~60 MB) Christian From rantingrickjohnson at gmail.com Wed Dec 16 19:45:31 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Wed, 16 Dec 2015 16:45:31 -0800 (PST) Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: On Wednesday, December 16, 2015 at 6:03:55 PM UTC-6, Bruce Whealton wrote: > Surely, one is going to want to create GUI apps for users > that are not Python Developers. I would not think to ask > someone to install Python on their system and make sure it > is added to the path. Maybe it is not so hard for the non- > technical, average users. > > I would want to package in some way so that when launched, > it installs whatever is needed on the end user's computer. > How is this done? Are there common practices for this? Your assumptions are correct! In fact, in a language that was "supposedly" designed to be an "applications language" (eat your heart out D'Aprano!!!), one would think that distributing apps would not only be obvious, but also intuitive! ALAS, THE CRUEL REALITIES OF INTERPRETED LANGUAGES SLAPS YOU IN THE PASTEY WHITE FACE! Unlike a true "applications language", like say, um, *JAVA*, one cannot simply compile an executable and distribute it in a teeny tiny binary form, no, with Python, the end user must either (1) have Python on his machine already, (2) download Python, or (3) you must package a Python interpreter along with your script (and dependencies) -- which will end up being a very large file just to run (what is in most cases) a very small script. BOO-HISS! But the good news is that, Python ships on many machines already. But of course, you're seeking more consistency in your distribution QA than the "wild guess" and the fickle nature of "lady luck". Many 3rd party libraries exist to solve your distribution issue. Google probably knows about all (or at least most) of them. From pavlos.parissis at gmail.com Wed Dec 16 20:16:11 2015 From: pavlos.parissis at gmail.com (Pavlos Parissis) Date: Thu, 17 Dec 2015 02:16:11 +0100 Subject: asyncio for UNIX socket Message-ID: <56720CDB.70600@gmail.com> Hi, I am trying to write UNIX socket client which sends 1 cmd and saves the received data to a file. Based on what I found on documentation I came up with:: import asyncio class UnixProtocol(asyncio.Protocol): def __init__(self, loop): self.cmd = 'show stat\n' self.loop = loop self.data = [] def connection_made(self, transport): transport.write(self.cmd.encode()) print('Data sent: {!r}'.format(self.message)) def data_received(self, data): print('Data received: {!r}'.format(data)) self.data.append(data.decode()) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') if self.data: with open('/tmp/somedata', 'w') as fp: fp.writelines(self.data) self.loop.stop() loop = asyncio.get_event_loop() s_file = '/run/haproxy/admin1.sock' coro = loop.create_unix_connection(lambda: UnixProtocol(loop), s_file) loop.run_until_complete(coro) loop.run_forever() loop.close() I am not sure if the above is the proper way to do the job. Am I doing the right thing to write the data to the file when peer closes the connection? Thanks, Pavlos -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 819 bytes Desc: OpenPGP digital signature URL: From ben+python at benfinney.id.au Wed Dec 16 20:20:39 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 17 Dec 2015 12:20:39 +1100 Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python References: Message-ID: <85io3x3m6w.fsf@benfinney.id.au> Bruce Whealton writes: > What seems to be blatantly missing is how this would be distributed. Distributing programs so that recipients can run them is an ongoing problem. Operating systems arenecessarily involved, and since not every recipient uses the exact same configuration of the exact same version of the exact same operating system, the means of getting your program installed and working on their computer will differn significantly. > In the first mentioned tutorial from Lynda.com the Tkinter app was > related to a web page. However, the browser cannot run Python Bytecode > or Python Scripts. Web applications are attractive for developers in large part because web standards are hard-won oases of compatibility across different operating systems. It is no accident that operating system vendors (Microsoft, Apple, Google, etc.) keep trying to carve out attractive incompatible features and areas of their system, to ensure some applications using those non-standard features will only run smoothly on the operating system controlled by that vendor. > Surely, one is going to want to create GUI apps for users that are not > Python Developers. Indeed, and toolkits like Tkinter make this refreshingly easy to do in a way that works across all mainstream operating systems today. What is not standardised is installation of software for end users. > I would want to package in some way so that when launched, it installs > whatever is needed on the end user's computer. How is this done? This is the ?bootstrap? problem: a Python program is only useful once there is a Python interpreter installed and working on the recipient's system. You still need to get the appropriate version of Python installed on that recipient's operating system. You'll need to know your target audience, make decisions about the set of operating systems you want to support, and build a package for each one. > Are there common practices for this? Common to all mainstream operating systems? No, installation of software is one major area that makes operating systems incompatible. For GNU+Linux systems: Up-to-date Python is easily installed as a dependency of your package. Target the version(s) of Python you know your recipients will have, and declare a dependency in the operating system package you make. For OS X: There is an old, minimal Python installation, which is probably too old for you to target. I am not aware of a good dependency resolution system; you'll need to get the latest stable Python onto the recipient's system with their help. For iOS: I'm not aware of a good way to install Python programs on iOS. For Android: There is a decent dependency system, but again I'm not aware of a good standard way to have a Python program install onto Android. For MS Windows: There is definitely no good dependency resolution system for you to use. You'll need to bundle a Python interpreter with your program as a single installable file. This makes your program much larger and redundant with any other such program on the system; this is what Microsoft has doomed developers to work with. -- \ ?If we have to give up either religion or education, we should | `\ give up education.? ?William Jennings Bryan, 1923-01 | _o__) | Ben Finney From denis.akhiyarov at gmail.com Wed Dec 16 20:21:42 2015 From: denis.akhiyarov at gmail.com (Denis Akhiyarov) Date: Wed, 16 Dec 2015 17:21:42 -0800 (PST) Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: On Wednesday, December 16, 2015 at 6:45:50 PM UTC-6, Rick Johnson wrote: > On Wednesday, December 16, 2015 at 6:03:55 PM UTC-6, Bruce Whealton wrote: > > > Surely, one is going to want to create GUI apps for users > > that are not Python Developers. I would not think to ask > > someone to install Python on their system and make sure it > > is added to the path. Maybe it is not so hard for the non- > > technical, average users. > > > > I would want to package in some way so that when launched, > > it installs whatever is needed on the end user's computer. > > How is this done? Are there common practices for this? > > > Your assumptions are correct! In fact, in a language that was "supposedly" designed to be an "applications language" (eat your heart out D'Aprano!!!), one would think that distributing apps would not only be obvious, but also intuitive! > > ALAS, THE CRUEL REALITIES OF INTERPRETED LANGUAGES SLAPS YOU IN THE PASTEY WHITE FACE! > > Unlike a true "applications language", like say, um, *JAVA*, one cannot simply compile an executable and distribute it in a teeny tiny binary form, no, with Python, the end user must either (1) have Python on his machine already, (2) download Python, or (3) you must package a Python interpreter along with your script (and dependencies) -- which will end up being a very large file just to run (what is in most cases) a very small script. > > BOO-HISS! > > But the good news is that, Python ships on many machines already. But of course, you're seeking more consistency in your distribution QA than the "wild guess" and the fickle nature of "lady luck". > > Many 3rd party libraries exist to solve your distribution issue. Google probably knows about all (or at least most) of them. if you did not notice Java/.NET ship with runtime VMs as well. Even C/C++ have some requirements depending on the platform. We should all switch to assembly to avoid any dependencies and port our code to each platform without hesitation. From nobody at nowhere.invalid Wed Dec 16 20:27:31 2015 From: nobody at nowhere.invalid (Nobody) Date: Thu, 17 Dec 2015 01:27:31 +0000 Subject: Why my image is in bad quality ? References: Message-ID: On Wed, 16 Dec 2015 06:04:37 -0800, fsn761304 wrote: > pixbufObj = Gdk.pixbuf_get_from_window(window, x, y, width, height) ... > image = Image.frombuffer("RGB", (width, height), > pixbufObj.get_pixels(), 'raw', 'RGB', 0, 1) The second-to-last argument should probably be Gdk.pixbuf_get_rowstride() rather than 0. From josef.pktd at gmail.com Wed Dec 16 20:57:01 2015 From: josef.pktd at gmail.com (Josef Pktd) Date: Wed, 16 Dec 2015 17:57:01 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: <51b673c2-589d-4141-8b80-ef17318a9218@googlegroups.com> References: <51b673c2-589d-4141-8b80-ef17318a9218@googlegroups.com> Message-ID: On Wednesday, December 16, 2015 at 9:50:35 AM UTC-5, Robert wrote: > On Wednesday, December 16, 2015 at 6:34:21 AM UTC-5, Mark Lawrence wrote: > > On 16/12/2015 10:44, Robert wrote: > > > Hi, > > > > > > When I run the following code, there is an error: > > > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > > > > ================ > > > import numpy as np > > > import pandas as pd > > > from patsy import dmatrices > > > from sklearn.linear_model import LogisticRegression > > > > > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > > > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > > > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > > > > > zipped = list(zip(X,y)) > > > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > > > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > > ======================= > > > > > > I have check 'df' is this type: > > > ============= > > > type(df) > > > Out[25]: pandas.core.frame.DataFrame > > > ============= > > > > > > I cannot figure out where the problem is. Can you help me? > > > Thanks. > > > > > > Error message: > > > .......... > > > > > > > > > --------------------------------------------------------------------------- > > > ValueError Traceback (most recent call last) > > > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > > > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > 18 > > > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > > 20 > > > 21 y = np.ravel(y) > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > > > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > > > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > > > --> 297 NA_action, return_type) > > > 298 if lhs.shape[1] == 0: > > > 299 raise PatsyError("model is missing required outcome variables") > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > > > 150 return iter([data]) > > > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > > > --> 152 NA_action) > > > 153 if design_infos is not None: > > > 154 return build_design_matrices(design_infos, data, > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > > > 55 data_iter_maker, > > > 56 eval_env, > > > ---> 57 NA_action) > > > 58 else: > > > 59 return None > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > > > 704 factor_states[factor], > > > 705 num_columns=num_column_counts[factor], > > > --> 706 categories=None) > > > 707 else: > > > 708 assert factor in cat_levels_contrasts > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > > > 86 if self.type == "numerical": > > > 87 if not isinstance(num_columns, int): > > > ---> 88 raise ValueError("For numerical factors, num_columns " > > > 89 "must be an int") > > > 90 if categories is not None: > > > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > > Slap the ValueError into a search engine and the first hit is > > https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q This was fixed in patsy 0.4.1 as discussed in this statsmodels thread. You need to upgrade patsy from 0.4.0. AFAIR, the type checking was too strict and broke with recent numpy versions. Josef > > > > -- > > My fellow Pythonistas, ask not what our language can do for you, ask > > what you can do for our language. > > > > Mark Lawrence > > Hi, > I don't see a solution to my problem. I find the following demo code from > > https://patsy.readthedocs.org/en/v0.1.0/API-reference.html#patsy.dmatrix > > It doesn't work either on the Canopy. Does it work on your computer? > Thanks, > > ///////////// > demo_data("a", "x", nlevels=3) > Out[134]: > {'a': ['a1', 'a2', 'a3', 'a1', 'a2', 'a3'], > 'x': array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, > -0.97727788])} > > mat = dmatrix("a + x", demo_data("a", "x", nlevels=3)) From rxjwg98 at gmail.com Wed Dec 16 21:37:34 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 18:37:34 -0800 (PST) Subject: Help on error " ValueError: For numerical factors, num_columns must be an int " In-Reply-To: References: <51b673c2-589d-4141-8b80-ef17318a9218@googlegroups.com> Message-ID: On Wednesday, December 16, 2015 at 8:57:30 PM UTC-5, Josef Pktd wrote: > On Wednesday, December 16, 2015 at 9:50:35 AM UTC-5, Robert wrote: > > On Wednesday, December 16, 2015 at 6:34:21 AM UTC-5, Mark Lawrence wrote: > > > On 16/12/2015 10:44, Robert wrote: > > > > Hi, > > > > > > > > When I run the following code, there is an error: > > > > > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > > > > > > > ================ > > > > import numpy as np > > > > import pandas as pd > > > > from patsy import dmatrices > > > > from sklearn.linear_model import LogisticRegression > > > > > > > > X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25, > > > > 3.5,4.0,4.25,4.5,4.75,5.0,5.5] > > > > y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1] > > > > > > > > zipped = list(zip(X,y)) > > > > df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > > > > > > y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > > > ======================= > > > > > > > > I have check 'df' is this type: > > > > ============= > > > > type(df) > > > > Out[25]: pandas.core.frame.DataFrame > > > > ============= > > > > > > > > I cannot figure out where the problem is. Can you help me? > > > > Thanks. > > > > > > > > Error message: > > > > .......... > > > > > > > > > > > > --------------------------------------------------------------------------- > > > > ValueError Traceback (most recent call last) > > > > C:\Users\rj\pyprj\stackoverflow_logisticregression0.py in () > > > > 17 df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f']) > > > > 18 > > > > ---> 19 y, X = dmatrices('p_or_f ~ study_hrs', df, return_type="dataframe") > > > > 20 > > > > 21 y = np.ravel(y) > > > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type) > > > > 295 eval_env = EvalEnvironment.capture(eval_env, reference=1) > > > > 296 (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env, > > > > --> 297 NA_action, return_type) > > > > 298 if lhs.shape[1] == 0: > > > > 299 raise PatsyError("model is missing required outcome variables") > > > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type) > > > > 150 return iter([data]) > > > > 151 design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env, > > > > --> 152 NA_action) > > > > 153 if design_infos is not None: > > > > 154 return build_design_matrices(design_infos, data, > > > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action) > > > > 55 data_iter_maker, > > > > 56 eval_env, > > > > ---> 57 NA_action) > > > > 58 else: > > > > 59 return None > > > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action) > > > > 704 factor_states[factor], > > > > 705 num_columns=num_column_counts[factor], > > > > --> 706 categories=None) > > > > 707 else: > > > > 708 assert factor in cat_levels_contrasts > > > > > > > > C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories) > > > > 86 if self.type == "numerical": > > > > 87 if not isinstance(num_columns, int): > > > > ---> 88 raise ValueError("For numerical factors, num_columns " > > > > 89 "must be an int") > > > > 90 if categories is not None: > > > > > > > > ValueError: For numerical factors, num_columns must be an int > > > > > > > > > > Slap the ValueError into a search engine and the first hit is > > > https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q > > This was fixed in patsy 0.4.1 as discussed in this statsmodels thread. > You need to upgrade patsy from 0.4.0. > > AFAIR, the type checking was too strict and broke with recent numpy versions. > > Josef > > > > > > > > -- > > > My fellow Pythonistas, ask not what our language can do for you, ask > > > what you can do for our language. > > > > > > Mark Lawrence > > > > Hi, > > I don't see a solution to my problem. I find the following demo code from > > > > https://patsy.readthedocs.org/en/v0.1.0/API-reference.html#patsy.dmatrix > > > > It doesn't work either on the Canopy. Does it work on your computer? > > Thanks, > > > > ///////////// > > demo_data("a", "x", nlevels=3) > > Out[134]: > > {'a': ['a1', 'a2', 'a3', 'a1', 'a2', 'a3'], > > 'x': array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, > > -0.97727788])} > > > > mat = dmatrix("a + x", demo_data("a", "x", nlevels=3)) Thanks. It is right. From rxjwg98 at gmail.com Wed Dec 16 21:48:16 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 18:48:16 -0800 (PST) Subject: How can I get/save Pandas DataFrame help content? Message-ID: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Hi, When I use Enthought/Canopy, help(DataFrame) has so much content that it exceeds the display buffer, i.e. its head is cut off as I go up to see it. I would like to know whether there is a way similar to Linux redirection to save the help DataFrame content to a file? I have search on-line Pandas DataFrame web page. Surprisingly, it has much less content than help(DataFrame) command. If there is no way to save the content to a file, do you know where I can get the full help DataFrame content on a web page? Thanks, From rosuav at gmail.com Wed Dec 16 21:56:00 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 13:56:00 +1100 Subject: How can I get/save Pandas DataFrame help content? In-Reply-To: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Message-ID: On Thu, Dec 17, 2015 at 1:48 PM, Robert wrote: > Hi, > > When I use Enthought/Canopy, help(DataFrame) has so much content that it > exceeds the display buffer, i.e. its head is cut off as I go up to see it. > I would like to know whether there is a way similar to Linux redirection to > save the help DataFrame content to a file? If you use command-line Python (by just running 'python' or 'python3' in your shell), you should be able to use help() with a More pager. ChrisA From rxjwg98 at gmail.com Wed Dec 16 22:20:52 2015 From: rxjwg98 at gmail.com (Robert) Date: Wed, 16 Dec 2015 19:20:52 -0800 (PST) Subject: How can I get/save Pandas DataFrame help content? In-Reply-To: References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Message-ID: On Wednesday, December 16, 2015 at 9:56:23 PM UTC-5, Chris Angelico wrote: > On Thu, Dec 17, 2015 at 1:48 PM, Robert wrote: > > Hi, > > > > When I use Enthought/Canopy, help(DataFrame) has so much content that it > > exceeds the display buffer, i.e. its head is cut off as I go up to see it. > > I would like to know whether there is a way similar to Linux redirection to > > save the help DataFrame content to a file? > > If you use command-line Python (by just running 'python' or 'python3' > in your shell), you should be able to use help() with a More pager. > > ChrisA Thanks for this useful idea. I have tried with: help(DataFrame) | more NameError Traceback (most recent call last) in () ----> 1 help(DataFrame) | more NameError: name 'more' is not defined //////////// It is possible I misunderstand your method. Could you give me a little more description on it? From rosuav at gmail.com Wed Dec 16 22:30:37 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 17 Dec 2015 14:30:37 +1100 Subject: How can I get/save Pandas DataFrame help content? In-Reply-To: References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Message-ID: On Thu, Dec 17, 2015 at 2:20 PM, Robert wrote: > On Wednesday, December 16, 2015 at 9:56:23 PM UTC-5, Chris Angelico wrote: >> On Thu, Dec 17, 2015 at 1:48 PM, Robert wrote: >> > Hi, >> > >> > When I use Enthought/Canopy, help(DataFrame) has so much content that it >> > exceeds the display buffer, i.e. its head is cut off as I go up to see it. >> > I would like to know whether there is a way similar to Linux redirection to >> > save the help DataFrame content to a file? >> >> If you use command-line Python (by just running 'python' or 'python3' >> in your shell), you should be able to use help() with a More pager. >> >> ChrisA > > Thanks for this useful idea. > I have tried with: > > help(DataFrame) | more > NameError Traceback (most recent call last) > in () > ----> 1 help(DataFrame) | more > > NameError: name 'more' is not defined > //////////// > It is possible I misunderstand your method. Could you give me a little more > description on it? Sorry for the confusion. You don't need to explicitly request the pager; the default interpreter configuration should include that. ChrisA From eryksun at gmail.com Wed Dec 16 22:39:42 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 16 Dec 2015 21:39:42 -0600 Subject: cannot open file with non-ASCII filename In-Reply-To: References: <20151214221751.GM12472@rus.uni-stuttgart.de> Message-ID: On Tue, Dec 15, 2015 at 11:04 AM, Ulli Horlacher wrote: > > Ehhh... I started Python programming some weeks ago and I know nearly > nothing about Windows. I am a UNIX and VMS guy :-) You should feel right at home, then. The Windows NT kernel was designed and implemented by a team of former DEC engineers led by David Cutler, who was one of the principle architects of VMS. There's an old joke that W[indows] NT is VMS + 1. Actually, you'd probably only notice a slight resemblance if you were coding a driver [1]. Microsoft discourages using the native NT API in user mode. Windows client DLLs such as kernel32.dll usually implement an API function in one of three ways, or in combination: using the native runtime library and loader functions (Rtl* & Ldr* in ntdll.dll) calling system services such as Nt* public APIs (ntdll.dll => ntoskrnl.exe) NtUser* & NtGdi* private APIs (user32.dll, gdi32.dll => win32k.sys) using a local procedure call (via ALPC or a driver) to a subsystem process such as csrss.exe - Windows client/server runtime conhost.exe - console host services.exe - service control manager lsass.exe - local security authority smss.exe - session manager But this is all an implementation detail. The API could be implemented in a totally different way in a totally different environment, such as running WINE on Linux. [1]: http://windowsitpro.com/windows-client/windows-nt-and-vms-rest-story From steve+comp.lang.python at pearwood.info Wed Dec 16 23:09:03 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 17 Dec 2015 15:09:03 +1100 Subject: How can I get/save Pandas DataFrame help content? References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Message-ID: <56723561$0$1596$c3e8da3$5496439d@news.astraweb.com> On Thursday 17 December 2015 13:48, Robert wrote: > Hi, > > When I use Enthought/Canopy, help(DataFrame) has so much content that it > exceeds the display buffer, i.e. its head is cut off as I go up to see it. Step 1: report this as a bug to Enthought and/or the Python bug tracker. help(DataFrame) should automatically choose a pager such as `less` on Linux or equivalent (`more` I think?) on Windows. Step 2: in the meantime, while you wait for Enthought to fix this, you can try any of these: (a) open the regular Python interactive interpreter (do you need help with that?); once you have the >>> prompt, import the module that DataFrame comes from, then run help: import whatever help(whatever.DataFrame) The regular interactive interpreter ought to automatically pick a pager. If it doesn't, that's a bug. (b) At the shell prompt (most likely a $ or # prompt) run: pydoc whatever.DataFrame if necessarily piping it to the pager or file of your choice using your shell's normal redirection syntax, e.g.: pydoc whatever.DataFrame | less (Remember, this is at the shell $ prompt, not the Python >>> prompt.) (c) If your OS can't find "pydoc", try this instead: python -m pydoc whatever.DataFrame -- Steve From __peter__ at web.de Thu Dec 17 04:27:27 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Dec 2015 10:27:27 +0100 Subject: How can I get/save Pandas DataFrame help content? References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> Message-ID: Robert wrote: > Hi, > > When I use Enthought/Canopy, help(DataFrame) has so much content that it > exceeds the display buffer, i.e. its head is cut off as I go up to see it. > I would like to know whether there is a way similar to Linux redirection > to save the help DataFrame content to a file? > > I have search on-line Pandas DataFrame web page. Surprisingly, it has much > less content than help(DataFrame) command. > > If there is no way to save the content to a file, do you know where I can > get the full help DataFrame content on a web page? On the commandline start a webserver with python -m pydoc -p 8000 and then point your browser to http://localhost:8000/pandas.core.frame.html#DataFrame From motoom at xs4all.nl Thu Dec 17 06:01:32 2015 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 17 Dec 2015 12:01:32 +0100 Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: > On 2015-12-17, at 01:03, Bruce Whealton wrote: > > I would want to package in some way so that when launched, it installs whatever is needed on the end user's computer. How is this done? You might want to watch https://www.youtube.com/watch?v=wsczq6j3_bA (Brandon Rhodes: The Day of the EXE Is Upon Us - PyCon 2014). "It was once quite painful to build your Python app as a single .exe file. Support forums filled with lamentations as users struggled with primitive tools. But today, two separate tools exist for compiling your Python to real machine language! Come learn about how one of the biggest problems in commercial and enterprise software has now been solved and how you can benefit from this achievement. Slides can be found at: https://speakerdeck.com/pycon2014 and https://github.com/PyCon/2014-slides" Greetings, From fsn761304 at gmail.com Thu Dec 17 06:31:00 2015 From: fsn761304 at gmail.com (fsn761304 at gmail.com) Date: Thu, 17 Dec 2015 03:31:00 -0800 (PST) Subject: Why my image is in bad quality ? In-Reply-To: References: Message-ID: <87686db2-0c75-44ec-9748-23649a482197@googlegroups.com> On Thursday, December 17, 2015 at 5:27:28 AM UTC+4, Nobody wrote: > On Wed, 16 Dec 2015 06:04:37 -0800, fsn761304 wrote: > > > pixbufObj = Gdk.pixbuf_get_from_window(window, x, y, width, height) ... > > image = Image.frombuffer("RGB", (width, height), > > pixbufObj.get_pixels(), 'raw', 'RGB', 0, 1) > > The second-to-last argument should probably be Gdk.pixbuf_get_rowstride() > rather than 0. No, this: image = Image.frombuffer("RGB", (width, height), pixbufObj.get_pixels(), 'raw', 'RGB', Gdk.pixbuf_get_rowstride(), 1) doesn't work: AttributeError: 'gi.repository.Gdk' object has no attribute 'pixbuf_get_rowstride' From sk at skaiser.at Thu Dec 17 08:03:25 2015 From: sk at skaiser.at (Siegfried Kaiser) Date: Thu, 17 Dec 2015 14:03:25 +0100 Subject: python 3.4, os.walk does not walk into cdroms Message-ID: <20151217140325.ea1ee8525eb617d113f0207f@skaiser.at> Hello all, I have a problem with os.walk - it does not walk into a mounted cdrom, I do not see the cdrom in the walk at all. What can I do to walk into cdrom? Thanks, Siegfried -- Siegfried Kaiser From trkaplan24 at gmail.com Thu Dec 17 08:28:23 2015 From: trkaplan24 at gmail.com (trkaplan24 at gmail.com) Date: Thu, 17 Dec 2015 05:28:23 -0800 (PST) Subject: Hangman Code. Message-ID: Hello, I created a python code for a simple hangman game. Was wondering if anyone could edit to help me make it multiplayer so when one person guesses a letter incorrectly, the next player can then guess a letter. import time player1 = raw_input("What is your name Player 1? ") player2 = raw_input("What is your name Player 2? ") print "Hello, " + player1, "You get to go first!" print "Hello, " + player2, "Wait for your turn!" print "\n" time.sleep(1) print "Start guessing..." time.sleep(0.5) word = "hockey" guesses = '' turns = 10 while turns > 0: failed = 0 for char in word: if char in guesses: print char, else: print "_", failed += 1 if failed == 0: print "\nYou won" break print guess = raw_input("guess a character:") guesses += guess if guess not in word: turns -= 1 print "Wrong\n" print "You have", + turns, 'guesses left' if turns == 0: print "You Lose\n" Thank you! From breamoreboy at yahoo.co.uk Thu Dec 17 08:56:22 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 Dec 2015 13:56:22 +0000 Subject: python 3.4, os.walk does not walk into cdroms In-Reply-To: <20151217140325.ea1ee8525eb617d113f0207f@skaiser.at> References: <20151217140325.ea1ee8525eb617d113f0207f@skaiser.at> Message-ID: On 17/12/2015 13:03, Siegfried Kaiser wrote: > Hello all, > > I have a problem with os.walk - it does not walk into a mounted cdrom, I do not see the cdrom in the walk at all. > What can I do to walk into cdrom? > > Thanks, > Siegfried > Please give us. 1) Your OS. 2) Your code. 3) How you tried to run it. 4) Exactly what happened. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From framstag at rus.uni-stuttgart.de Thu Dec 17 08:58:13 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 17 Dec 2015 13:58:13 +0000 (UTC) Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python References: Message-ID: Rick Johnson wrote: > Unlike a true "applications language", like say, um, *JAVA*, one cannot > simply compile an executable and distribute it in a teeny tiny binary > form, no, with Python Of course you can! If have done this with pyinstaller. This creates a standalone Windows executable you can distribute. Example: http://fex.rus.uni-stuttgart.de:8080/fexit.html -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From denismfmcmahon at gmail.com Thu Dec 17 09:12:01 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 17 Dec 2015 14:12:01 -0000 (UTC) Subject: Hangman Code. References: Message-ID: On Thu, 17 Dec 2015 05:28:23 -0800, trkaplan24 wrote: > Hello, I created a python code for a simple hangman game. Was wondering > if anyone could edit to help me make it multiplayer so when one person > guesses a letter incorrectly, the next player can then guess a letter. First you need to prompt for the number of players, and store this in a variable. Next you need a variable to keep track of the current player. Set this to 1 at the start of the program, because we're humans and we like to be player 1 ... player n, not player 0 ... player n-1. Use the current player variable value to prompt for the next player. After each player takes a turn, add 1 to the current player. If this is greater than the number of players, set it back to 1. -- Denis McMahon, denismfmcmahon at gmail.com From framstag at rus.uni-stuttgart.de Thu Dec 17 09:14:39 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Thu, 17 Dec 2015 14:14:39 +0000 (UTC) Subject: Tk alternative to askopenfilename and askdirectory? References: Message-ID: Rick Johnson wrote: > Oh i understand. What you opine for is something like: askOpenFileOrDir() > -- which displays a dialog from which a file or directory can be selected > by the user. Yes, exactly! Now: how? -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From robert.kern at gmail.com Thu Dec 17 10:15:56 2015 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 17 Dec 2015 15:15:56 +0000 Subject: How can I get/save Pandas DataFrame help content? In-Reply-To: <56723561$0$1596$c3e8da3$5496439d@news.astraweb.com> References: <9109f5a6-f6c7-4651-995e-2e8813c1f647@googlegroups.com> <56723561$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2015-12-17 04:09, Steven D'Aprano wrote: > On Thursday 17 December 2015 13:48, Robert wrote: > >> Hi, >> >> When I use Enthought/Canopy, help(DataFrame) has so much content that it >> exceeds the display buffer, i.e. its head is cut off as I go up to see it. > > > Step 1: report this as a bug to Enthought and/or the Python bug tracker. > help(DataFrame) should automatically choose a pager such as `less` on Linux > or equivalent (`more` I think?) on Windows. I suspect that he is using the embedded IPython console in the Canopy IDE, so it's more of an issue that help() knows that it's not in a true terminal so it doesn't page. If he had been using python at the terminal, help() would have indeed used the appropriate terminal pager. Robert, in the IPython console, you can also use a special syntax to get the content. The IPython console widget does know how to page this: In [1]: pandas.DataFrame? http://ipython.readthedocs.org/en/stable/interactive/reference.html#dynamic-object-information -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From oscar.j.benjamin at gmail.com Thu Dec 17 10:30:02 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 17 Dec 2015 15:30:02 +0000 Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: On 17 December 2015 at 00:03, Bruce Whealton wrote: > I watched one training video that discussed Python and Tkinter. Like many similar tutorials from online training sites, I was left scratching my head. > > What seems to be blatantly missing is how this would be distributed. In the first mentioned tutorial from Lynda.com the Tkinter app was related to a web page. However, the browser cannot run Python Bytecode or Python Scripts. > > Surely, one is going to want to create GUI apps for users that are not Python Developers. I would not think to ask someone to install Python on their system and make sure it is added to the path. Maybe it is not so hard for the non-technical, average users. > > I would want to package in some way so that when launched, it installs whatever is needed on the end user's computer. How is this done? > Are there common practices for this? There are different general approaches in this area. One possibility is to ship an installer. Another is to try and ship a complete single file executable. For the single-file executable you have pyinstaller/py2exe/py2app etc. If you're user can be expected to install the software before running it then in the basic case it is not too hard. Python itself comes with a graphical installer for Windows and is already installed on every other OS. If you can assume that Python is installed then you can distribute your application simply as a zip file but with a .py(z)(w) file extension. See here: https://www.python.org/dev/peps/pep-0441/ A Windows user should then be able to simply double click the .pyz file and have it run. I'm not sure how that works on a MAC but on Linux you can preface the zip file with a shebang make it executable and it will run from the terminal and from any file-browser if it knows how to run executable files. Another option for Windows although it is relatively new is that as of Python 3.5 there is an embedded distribution of Python that is intended to be shipped as part of an application installer and installed local to the application. This is new and I haven't heard anyone using it and don't know if any tools exist to help actually creating an installer using it. -- Oscar From wxjmfauth at gmail.com Thu Dec 17 11:28:36 2015 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 17 Dec 2015 08:28:36 -0800 (PST) Subject: How does one distribute Tkinter or Qt GUI apps Developed in Python In-Reply-To: References: Message-ID: Le jeudi 17 d?cembre 2015 16:30:41 UTC+1, Oscar Benjamin a ?crit?: > ... > Another option for Windows although it is relatively new is that as of > Python 3.5 there is an embedded distribution of Python that is > intended to be shipped as part of an application installer and > installed local to the application. This is new and I haven't heard > anyone using it and don't know if any tools exist to help actually > creating an installer using it. > D:\>cd py351embed D:\py351embed>python.exe Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for e in sys.path: print(e) ... D:\py351embed\python35.zip D:\py351embed\DLLs D:\py351embed\lib D:\py351embed >>> >>> quit() D:\py351embed> jmf From simian336 at gmail.com Thu Dec 17 14:29:02 2015 From: simian336 at gmail.com (Simian) Date: Thu, 17 Dec 2015 11:29:02 -0800 (PST) Subject: error reading api with urllib In-Reply-To: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> References: <9aa21642-765b-4666-8c66-a6dab9928c37@googlegroups.com> Message-ID: <8a7a75fc-d023-4f83-ab78-2f30d286ad7d@googlegroups.com> I will try adding the get. I have not used curl. I also forgot to mention that the code runs against another server, though a slightly different version number. Thanks to you both. Simian From breamoreboy at yahoo.co.uk Thu Dec 17 18:05:07 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 Dec 2015 23:05:07 +0000 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? Message-ID: The culprit character is hidden between "Issue #" and "20540" at line 400 of C:\Python35\Lib\multiprocessing\connection.py. https://bugs.python.org/issue20540 and https://hg.python.org/cpython/rev/125c24f47f3c refers. I'm asking as I've just spent 30 minutes tracking down why my debug code would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4. -- 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 Dec 17 18:14:21 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 17 Dec 2015 16:14:21 -0700 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Thu, Dec 17, 2015 at 4:05 PM, Mark Lawrence wrote: > The culprit character is hidden between "Issue #" and "20540" at line 400 of > C:\Python35\Lib\multiprocessing\connection.py. > https://bugs.python.org/issue20540 and > https://hg.python.org/cpython/rev/125c24f47f3c refers. > > I'm asking as I've just spent 30 minutes tracking down why my debug code > would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4. Probably not, but that's inside a comment, so whether the character is U+202F or U+0020 shouldn't make any difference in how the code runs. That seems like a Unicode bug if it does. From rosuav at gmail.com Thu Dec 17 18:18:56 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 10:18:56 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 10:05 AM, Mark Lawrence wrote: > The culprit character is hidden between "Issue #" and "20540" at line 400 of > C:\Python35\Lib\multiprocessing\connection.py. > https://bugs.python.org/issue20540 and > https://hg.python.org/cpython/rev/125c24f47f3c refers. > > I'm asking as I've just spent 30 minutes tracking down why my debug code > would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4. I'm curious as to why this character should bomb your code at all - it's in a comment. Is it that your program was expecting ASCII, or is it something about that particular character? Here's a quick listing of the CPython standard library files that aren't ASCII: rosuav at sikorsky:~/cpython/Lib$ find -name \*.py -not -wholename \*test\* -exec file {} \;|grep UTF-8 ./encodings/punycode.py: Python script, UTF-8 Unicode text executable ./encodings/koi8_t.py: Python script, UTF-8 Unicode text executable ./msilib/__init__.py: Python script, UTF-8 Unicode text executable ./shlex.py: Python script, UTF-8 Unicode text executable ./http/client.py: Python script, UTF-8 Unicode text executable ./distutils/command/bdist_msi.py: Python script, UTF-8 Unicode text executable ./multiprocessing/connection.py: Python script, UTF-8 Unicode text executable ./functools.py: Python script, UTF-8 Unicode text executable ./heapq.py: Python script, UTF-8 Unicode text executable ./email/message.py: Python script, UTF-8 Unicode text executable ./getopt.py: Python script, UTF-8 Unicode text executable ./urllib/request.py: Python script, UTF-8 Unicode text executable ./sre_compile.py: Python script, UTF-8 Unicode text executable ./sqlite3/dbapi2.py: Python script, UTF-8 Unicode text executable ./sqlite3/__init__.py: Python script, UTF-8 Unicode text executable Does your program bomb on any of these? ChrisA From breamoreboy at yahoo.co.uk Thu Dec 17 19:02:25 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 18 Dec 2015 00:02:25 +0000 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On 17/12/2015 23:18, Chris Angelico wrote: > On Fri, Dec 18, 2015 at 10:05 AM, Mark Lawrence wrote: >> The culprit character is hidden between "Issue #" and "20540" at line 400 of >> C:\Python35\Lib\multiprocessing\connection.py. >> https://bugs.python.org/issue20540 and >> https://hg.python.org/cpython/rev/125c24f47f3c refers. >> >> I'm asking as I've just spent 30 minutes tracking down why my debug code >> would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4. > > I'm curious as to why this character should bomb your code at all - > it's in a comment. Is it that your program was expecting ASCII, or is > it something about that particular character? > I'm playing with ASTs and using the stdlib as test data. I was trying to avoid going down this particular route, but... A lot of it is down to Windows, as the actual complaint is:- six.print_(source) File "C:\Python35\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u202f' in position 407: character maps to And as usual I've answered my own question. The cp1252 shows even if my console is set to 65001, *BUT* I'm piping the output to file as it's so much faster. Having taken five minutes to run the code without the pipe everything runs to completion. I suppose the original question still holds, but I for one certainly won't be losing any sleep over it. Talking of which, good night all :) -- 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 Dec 17 19:16:49 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 11:16:49 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 11:02 AM, Mark Lawrence wrote: > A lot of it is down to Windows, as the actual complaint is:- > > six.print_(source) > File "C:\Python35\lib\encodings\cp1252.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_table)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u202f' in > position 407: character maps to > > And as usual I've answered my own question. The cp1252 shows even if my > console is set to 65001, *BUT* I'm piping the output to file as it's so much > faster. Having taken five minutes to run the code without the pipe > everything runs to completion. > > I suppose the original question still holds, but I for one certainly won't > be losing any sleep over it. Talking of which, good night all :) Oh. Windows. Suddenly it all makes sense. Python source code is (as of 3.0) Unicode text, and is assumed to be stored as UTF-8 if not otherwise specified. If Windows can't handle that, too bad for Windows. ChrisA From bearmingo at gmail.com Fri Dec 18 00:12:28 2015 From: bearmingo at gmail.com (bearmingo) Date: Thu, 17 Dec 2015 21:12:28 -0800 (PST) Subject: cannot open file with non-ASCII filename In-Reply-To: References: Message-ID: <4797ae88-3341-49a9-b046-de2a31d6ad40@googlegroups.com> Usually I put #!-*-coding=utf-8-*- at each py file. It's ok to open file in local system. From tjreedy at udel.edu Fri Dec 18 01:36:12 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Dec 2015 01:36:12 -0500 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On 12/17/2015 6:18 PM, Chris Angelico wrote: > On Fri, Dec 18, 2015 at 10:05 AM, Mark Lawrence wrote: >> The culprit character is hidden between "Issue #" and "20540" at line 400 of >> C:\Python35\Lib\multiprocessing\connection.py. >> https://bugs.python.org/issue20540 and >> https://hg.python.org/cpython/rev/125c24f47f3c refers. >> >> I'm asking as I've just spent 30 minutes tracking down why my debug code >> would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4. > > I'm curious as to why this character should bomb your code at all - > it's in a comment. Is it that your program was expecting ASCII, or is > it something about that particular character? > > Here's a quick listing of the CPython standard library files that aren't ASCII: Last I knew, Guido still wanted stdlib files to be all-ascii, especially possibly in special cases. There is no good reason I can think of for there to be an invisible non-ascii space in a comment. It strikes me as most likely an accident (typo) that should be fixed. I suspect the same of most of the following. Perhaps you should file an issue (and patch?) on the tracker. > rosuav at sikorsky:~/cpython/Lib$ find -name \*.py -not -wholename > \*test\* -exec file {} \;|grep UTF-8 > ./encodings/punycode.py: Python script, UTF-8 Unicode text executable > ./encodings/koi8_t.py: Python script, UTF-8 Unicode text executable > ./msilib/__init__.py: Python script, UTF-8 Unicode text executable > ./shlex.py: Python script, UTF-8 Unicode text executable > ./http/client.py: Python script, UTF-8 Unicode text executable > ./distutils/command/bdist_msi.py: Python script, UTF-8 Unicode text executable > ./multiprocessing/connection.py: Python script, UTF-8 Unicode text executable > ./functools.py: Python script, UTF-8 Unicode text executable > ./heapq.py: Python script, UTF-8 Unicode text executable > ./email/message.py: Python script, UTF-8 Unicode text executable > ./getopt.py: Python script, UTF-8 Unicode text executable > ./urllib/request.py: Python script, UTF-8 Unicode text executable > ./sre_compile.py: Python script, UTF-8 Unicode text executable > ./sqlite3/dbapi2.py: Python script, UTF-8 Unicode text executable > ./sqlite3/__init__.py: Python script, UTF-8 Unicode text executable > > Does your program bomb on any of these? > > ChrisA > -- Terry Jan Reedy From tjreedy at udel.edu Fri Dec 18 01:37:43 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Dec 2015 01:37:43 -0500 Subject: cannot open file with non-ASCII filename In-Reply-To: <4797ae88-3341-49a9-b046-de2a31d6ad40@googlegroups.com> References: <4797ae88-3341-49a9-b046-de2a31d6ad40@googlegroups.com> Message-ID: On 12/18/2015 12:12 AM, bearmingo wrote: > Usually I put > #!-*-coding=utf-8-*- > at each py file. > It's ok to open file in local system. That declaration only applies to the content of the file, not its name on the filesystem. -- Terry Jan Reedy From rosuav at gmail.com Fri Dec 18 01:51:32 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 17:51:32 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 5:36 PM, Terry Reedy wrote: > Last I knew, Guido still wanted stdlib files to be all-ascii, especially > possibly in special cases. There is no good reason I can think of for there > to be an invisible non-ascii space in a comment. It strikes me as most > likely an accident (typo) that should be fixed. I suspect the same of most > of the following. Perhaps you should file an issue (and patch?) on the > tracker. You're probably right on that one. Here's others - and the script I used to find them. import os for root, dirs, files in os.walk("."): if "test" in root: continue for fn in files: if not fn.endswith(".py"): continue if "test" in fn: continue with open(os.path.join(root,fn),"rb") as f: for l,line in enumerate(f): try: line.decode("ascii") continue # Ignore the ASCII lines except UnicodeDecodeError: line = line.rstrip(b"\n") try: line = line.decode("UTF-8") except UnicodeDecodeError: line = repr(line) # If it's not UTF-8 either, show it as b'...' print("%s:%d: %s" % (fn,l,line)) shlex.py:37: self.wordchars += ('????????????????????????????????' shlex.py:38: '??????????????????????????????') functools.py:7: # and ?ukasz Langa . heapq.py:34: [explanation by Fran?ois Pinard] getopt.py:21: # Peter ?strand added gnu_getopt(). sre_compile.py:26: (0x69, 0x131), # i? sre_compile.py:28: (0x73, 0x17f), # s? sre_compile.py:30: (0xb5, 0x3bc), # ?? sre_compile.py:32: (0x345, 0x3b9, 0x1fbe), # \u0345?? sre_compile.py:34: (0x390, 0x1fd3), # ?? sre_compile.py:36: (0x3b0, 0x1fe3), # ?? sre_compile.py:38: (0x3b2, 0x3d0), # ?? sre_compile.py:40: (0x3b5, 0x3f5), # ?? sre_compile.py:42: (0x3b8, 0x3d1), # ?? sre_compile.py:44: (0x3ba, 0x3f0), # ?? sre_compile.py:46: (0x3c0, 0x3d6), # ?? sre_compile.py:48: (0x3c1, 0x3f1), # ?? sre_compile.py:50: (0x3c2, 0x3c3), # ?? sre_compile.py:52: (0x3c6, 0x3d5), # ?? sre_compile.py:54: (0x1e61, 0x1e9b), # ?? sre_compile.py:56: (0xfb05, 0xfb06), # ?? punycode.py:2: Written by Martin v. L?wis. koi8_t.py:2: # http://ru.wikipedia.org/wiki/???-8 __init__.py:0: # Copyright (C) 2005 Martin v. L?wis client.py:737: a Date representing the file?s last-modified time, a client.py:739: containing a guess at the file?s type. See also the bdist_msi.py:0: # Copyright (C) 2005, 2006 Martin von L?wis connection.py:399: # Issue #?20540: concatenate before sending, to avoid delays due message.py:531: filename=('utf-8', '', Fu?baller.ppt')) message.py:533: filename='Fu?baller.ppt')) request.py:181: * geturl() ? return the URL of the resource retrieved, commonly used to request.py:184: * info() ? return the meta-information of the page, such as headers, in the request.py:188: * getcode() ? return the HTTP status code of the response. Raises URLError dbapi2.py:2: # Copyright (C) 2004-2005 Gerhard H?ring __init__.py:2: # Copyright (C) 2005 Gerhard H?ring They're nearly all comments. A few string literals. I would be inclined to ASCIIfy the apostrophes, dashes, and the connection.py space that started this thread. People's names, URLs, and demonstrative characters I'm more inclined to leave. Agreed? ChrisA From storchaka at gmail.com Fri Dec 18 02:12:50 2015 From: storchaka at gmail.com (Serhiy Storchaka) Date: Fri, 18 Dec 2015 09:12:50 +0200 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On 18.12.15 08:51, Chris Angelico wrote: > On Fri, Dec 18, 2015 at 5:36 PM, Terry Reedy wrote: >> Last I knew, Guido still wanted stdlib files to be all-ascii, especially >> possibly in special cases. There is no good reason I can think of for there >> to be an invisible non-ascii space in a comment. It strikes me as most >> likely an accident (typo) that should be fixed. I suspect the same of most >> of the following. Perhaps you should file an issue (and patch?) on the >> tracker. > > You're probably right on that one. Here's others - and the script I > used to find them. > > import os > for root, dirs, files in os.walk("."): > if "test" in root: continue > for fn in files: > if not fn.endswith(".py"): continue > if "test" in fn: continue > with open(os.path.join(root,fn),"rb") as f: > for l,line in enumerate(f): > try: > line.decode("ascii") > continue # Ignore the ASCII lines > except UnicodeDecodeError: > line = line.rstrip(b"\n") > try: line = line.decode("UTF-8") > except UnicodeDecodeError: line = repr(line) # If > it's not UTF-8 either, show it as b'...' > print("%s:%d: %s" % (fn,l,line)) > > > shlex.py:37: self.wordchars += ('????????????????????????????????' > shlex.py:38: '??????????????????????????????') > functools.py:7: # and ?ukasz Langa . > heapq.py:34: [explanation by Fran?ois Pinard] > getopt.py:21: # Peter ?strand added gnu_getopt(). > sre_compile.py:26: (0x69, 0x131), # i? > sre_compile.py:28: (0x73, 0x17f), # s? > sre_compile.py:30: (0xb5, 0x3bc), # ?? > sre_compile.py:32: (0x345, 0x3b9, 0x1fbe), # \u0345?? > sre_compile.py:34: (0x390, 0x1fd3), # ?? > sre_compile.py:36: (0x3b0, 0x1fe3), # ?? > sre_compile.py:38: (0x3b2, 0x3d0), # ?? > sre_compile.py:40: (0x3b5, 0x3f5), # ?? > sre_compile.py:42: (0x3b8, 0x3d1), # ?? > sre_compile.py:44: (0x3ba, 0x3f0), # ?? > sre_compile.py:46: (0x3c0, 0x3d6), # ?? > sre_compile.py:48: (0x3c1, 0x3f1), # ?? > sre_compile.py:50: (0x3c2, 0x3c3), # ?? > sre_compile.py:52: (0x3c6, 0x3d5), # ?? > sre_compile.py:54: (0x1e61, 0x1e9b), # ?? > sre_compile.py:56: (0xfb05, 0xfb06), # ?? > punycode.py:2: Written by Martin v. L?wis. > koi8_t.py:2: # http://ru.wikipedia.org/wiki/???-8 > __init__.py:0: # Copyright (C) 2005 Martin v. L?wis > client.py:737: a Date representing the file?s last-modified time, a > client.py:739: containing a guess at the file?s type. See also the > bdist_msi.py:0: # Copyright (C) 2005, 2006 Martin von L?wis > connection.py:399: # Issue #?20540: concatenate before > sending, to avoid delays due > message.py:531: filename=('utf-8', '', Fu?baller.ppt')) > message.py:533: filename='Fu?baller.ppt')) > request.py:181: * geturl() ? return the URL of the resource > retrieved, commonly used to > request.py:184: * info() ? return the meta-information of the > page, such as headers, in the > request.py:188: * getcode() ? return the HTTP status code of the > response. Raises URLError > dbapi2.py:2: # Copyright (C) 2004-2005 Gerhard H?ring > __init__.py:2: # Copyright (C) 2005 Gerhard H?ring > > They're nearly all comments. A few string literals. > > I would be inclined to ASCIIfy the apostrophes, dashes, and the > connection.py space that started this thread. People's names, URLs, > and demonstrative characters I'm more inclined to leave. Agreed? Agreed. Please open an issue. Using non-ASCII apostrophes and like in docstrings may be considered a bug. From rosuav at gmail.com Fri Dec 18 02:43:24 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 18:43:24 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 6:12 PM, Serhiy Storchaka wrote: > Agreed. Please open an issue. > > Using non-ASCII apostrophes and like in docstrings may be considered a bug. http://bugs.python.org/issue25899 Also noticed this. Is this a markup error? Lib/urllib/request.py:190: Note that *None& may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). It looks fine on the web: https://docs.python.org/3/library/urllib.request.html ChrisA From rosuav at gmail.com Fri Dec 18 02:43:26 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 18:43:26 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 6:12 PM, Serhiy Storchaka wrote: > Agreed. Please open an issue. > > Using non-ASCII apostrophes and like in docstrings may be considered a bug. http://bugs.python.org/issue25899 Also noticed this. Is this a markup error? Lib/urllib/request.py:190: Note that *None& may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). It looks fine on the web: https://docs.python.org/3/library/urllib.request.html ChrisA From zachary.ware+pylist at gmail.com Fri Dec 18 03:32:30 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 18 Dec 2015 02:32:30 -0600 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 1:43 AM, Chris Angelico wrote: > On Fri, Dec 18, 2015 at 6:12 PM, Serhiy Storchaka wrote: >> Agreed. Please open an issue. >> >> Using non-ASCII apostrophes and like in docstrings may be considered a bug. > > http://bugs.python.org/issue25899 > > Also noticed this. Is this a markup error? > > Lib/urllib/request.py:190: > Note that *None& may be returned if no handler handles the request (though > the default installed global OpenerDirector uses UnknownHandler to ensure > this never happens). The '&' is a typo; it should have been '*'. > It looks fine on the web: > https://docs.python.org/3/library/urllib.request.html Because what's on the web has no relation to the docstring :) -- Zach From auriocus at gmx.de Fri Dec 18 03:32:43 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Fri, 18 Dec 2015 09:32:43 +0100 Subject: Tk alternative to askopenfilename and askdirectory? In-Reply-To: References: Message-ID: Am 16.12.15 um 14:18 schrieb Ulli Horlacher: > Is there an alternative to Tk's askopenfilename() and askdirectory()? > > I want to select a files and directories within one widget, but > askopenfilename() let me only select files and askdirectory() let me only > select directories. Tk calls out into the native file manager to perform the file/open operation (on Win&Mac, on Unix it brings it's own). Unfortunately, these dialogs do not have an option to select both directories and files. This means you would have to do your own. You wouldn't need to start from scratch, however - Schelte Bron has created a very nice dialog as a replacement for the (oldfashioned, dull) standard dialog in Tk: http://wiki.tcl.tk/15897 It would be feasible to tweak it a bit to allow for directory and file selection. It is written in Tcl, however, but that is not a problem in itself, you could call it from Python in a similar way that tk_getOpenFile is implemented. Concerning your drag&drop problem, it is only possible if you go for a Tk main window, then you could use TkDND. It is not in the standard install, but it can be bundled *without installation*, because Tcl extensions use a mechanism called stubs, which ensures broad binary compatibility. The only drawback: you will not have a single .py file, but since on Windows you deliver using pyinstaller, that should not be an issue. Christian From storchaka at gmail.com Fri Dec 18 03:33:46 2015 From: storchaka at gmail.com (Serhiy Storchaka) Date: Fri, 18 Dec 2015 10:33:46 +0200 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On 18.12.15 09:43, Chris Angelico wrote: > On Fri, Dec 18, 2015 at 6:12 PM, Serhiy Storchaka wrote: >> Agreed. Please open an issue. >> >> Using non-ASCII apostrophes and like in docstrings may be considered a bug. > > http://bugs.python.org/issue25899 Thanks. > Also noticed this. Is this a markup error? > > Lib/urllib/request.py:190: > Note that *None& may be returned if no handler handles the request (though > the default installed global OpenerDirector uses UnknownHandler to ensure > this never happens). Looks as just a typo. From jfong at ms4.hinet.net Fri Dec 18 03:41:43 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Fri, 18 Dec 2015 00:41:43 -0800 (PST) Subject: Problem on ctypes arguments in a DLL function Message-ID: <2331461b-cf4c-479c-8380-ddea3b7e7878@googlegroups.com> I am trying to use the libusb-win32 v1.2.6.0 with Win7. I wrote a test program(showing below) but stuck with a strange problem. Here is the result: ---------------------------- D:\Work\Python34>python Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import libusb_u2aTest as u2a 0x10c4 0x1 Traceback (most recent call last): File "", line 1, in File "D:\Work\Python34\libusb_u2aTest.py", line 364, in pHDL = _lib.usb_open(pDevice) ValueError: Procedure probably called with too many arguments (4 bytes in excess ) >>> ----------------- I replace the troubled line with a "pass" to make the loading success, then to check the type of "pDevice", it's correct. >>> u2a.pDevice It seems no reason that this call can be in trouble:-( Any hint was appreciated. Thanks ahead. libusb_u2aTest.py listing: ----------------------------- from ctypes import * _lib = windll.LoadLibrary("C:\\Windows\\System32\\libusb0.dll") _PATH_MAX = 512 ### Data structures... class _usb_device_descriptor(Structure): _fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bcdUSB', c_uint16), ('bDeviceClass', c_uint8), ('bDeviceSubClass', c_uint8), ('bDeviceProtocol', c_uint8), ('bMaxPacketSize0', c_uint8), ('idVendor', c_uint16), ('idProduct', c_uint16), ('bcdDevice', c_uint16), ('iManufacturer', c_uint8), ('iProduct', c_uint8), ('iSerialNumber', c_uint8), ('bNumConfigurations', c_uint8)] class _usb_device(Structure): pass class _usb_bus(Structure): pass _usb_device._fields_ = [('next', POINTER(_usb_device)), ('prev', POINTER(_usb_device)), ('filename', c_int8 * _PATH_MAX), ('bus', POINTER(_usb_bus)), ('descriptor', _usb_device_descriptor), #('config', POINTER(_usb_config_descriptor)), # not implemented yet ('config', POINTER(c_int)), # to ease this test ('dev', c_void_p), ('devnum', c_uint8), ('num_children', c_ubyte), ('children', POINTER(POINTER(_usb_device)))] _usb_bus._fields_ = [('next', POINTER(_usb_bus)), ('prev', POINTER(_usb_bus)), ('dirname', c_char * _PATH_MAX), ('devices', POINTER(_usb_device)), ('location', c_uint32), ('root_dev', POINTER(_usb_device))] _usb_dev_handle = c_void_p ### Function prototype... # struct usb_bus *usb_get_busses(void); _lib.usb_get_busses.restype = POINTER(_usb_bus) # usb_dev_handle *usb_open(struct usb_device *dev); _lib.usb_open.argtypes = [POINTER(_usb_device)] _lib.usb_open.restype = _usb_dev_handle ### Test start... _lib.usb_init() _lib.usb_find_busses() _lib.usb_find_devices() pBus = _lib.usb_get_busses() if bool(pBus): pDevice = pBus[0].devices if bool(pDevice): print(hex(pDevice[0].descriptor.idVendor)) print(hex(pDevice[0].descriptor.idProduct)) if pDevice[0].descriptor.idVendor == 0x10c4 and \ pDevice[0].descriptor.idProduct == 0x0001: pHDL = _lib.usb_open(pDevice) # <--this line is in trouble From ridwanibrahim97 at yahoo.com Fri Dec 18 03:44:49 2015 From: ridwanibrahim97 at yahoo.com (IBRAHIM ARANSIOLA RIDWAN) Date: Fri, 18 Dec 2015 09:44:49 +0100 Subject: installation error Message-ID: <225949.79337.bm@smtp208.mail.bf1.yahoo.com> Hi, My name is ridwan and I have a problem with installing the version 3.5.1 on my windows 10 system. My question is those python have specified compatibility issues or I downloaded the wrong version for my operating system, or do I need to change my system settings in some aspect. Thank you in anticipation of your favourable response . Sent from Mail for Windows 10 From framstag at rus.uni-stuttgart.de Fri Dec 18 04:27:32 2015 From: framstag at rus.uni-stuttgart.de (Ulli Horlacher) Date: Fri, 18 Dec 2015 09:27:32 +0000 (UTC) Subject: Tk alternative to askopenfilename and askdirectory? References: Message-ID: Christian Gollwitzer wrote: > Tk calls out into the native file manager to perform the file/open > operation (on Win&Mac, on Unix it brings it's own). This means, on Windows the user gets a "well known" file/directory browser? Then this is an important feature! Anything new and unknown is bad for a standard Windows user. > scratch, however - Schelte Bron has created a very nice dialog as a > replacement for the (oldfashioned, dull) standard dialog in Tk: > > http://wiki.tcl.tk/15897 > > It would be feasible to tweak it a bit to allow for directory and file > selection. It is written in Tcl Oh boy, last time, I hacked with Tcl was in 1993 :-} I remember Tcl as a horrible programming language. > Concerning your drag&drop problem, it is only possible if you go for a > Tk main window, then you could use TkDND. It is not in the standard > install, but it can be bundled *without installation*, because Tcl > extensions use a mechanism called stubs, which ensures broad binary > compatibility. The only drawback: you will not have a single .py file, > but since on Windows you deliver using pyinstaller, that should not be > an issue. Ok, I put it on my TODO-List :-) IF I have some day some spare time... -- Ullrich Horlacher Server und Virtualisierung Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de Universitaet Stuttgart Tel: ++49-711-68565868 Allmandring 30a Fax: ++49-711-682357 70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/ From rosuav at gmail.com Fri Dec 18 04:33:00 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 18 Dec 2015 20:33:00 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 7:32 PM, Zachary Ware wrote: > On Fri, Dec 18, 2015 at 1:43 AM, Chris Angelico wrote: >> On Fri, Dec 18, 2015 at 6:12 PM, Serhiy Storchaka wrote: >>> Agreed. Please open an issue. >>> >>> Using non-ASCII apostrophes and like in docstrings may be considered a bug. >> >> http://bugs.python.org/issue25899 >> >> Also noticed this. Is this a markup error? >> >> Lib/urllib/request.py:190: >> Note that *None& may be returned if no handler handles the request (though >> the default installed global OpenerDirector uses UnknownHandler to ensure >> this never happens). > > The '&' is a typo; it should have been '*'. > >> It looks fine on the web: >> https://docs.python.org/3/library/urllib.request.html > > Because what's on the web has no relation to the docstring :) Wasn't sure if it was getting extracted from there. Looking at help(urllib.request.urlopen) just shows the markup as-is, so I couldn't be sure. Should that be a separate tracker issue? ChrisA From steve at pearwood.info Fri Dec 18 04:46:53 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Dec 2015 20:46:53 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? References: Message-ID: <5673d60e$0$1586$c3e8da3$5496439d@news.astraweb.com> On Fri, 18 Dec 2015 10:05 am, Mark Lawrence asked: "Should stdlib files contain 'narrow non breaking space' U+202F?" Absolutely it should. What better way to ensure that the interpreter works correctly with Unicode than to use Unicode in the std lib? -- Steven From steve at pearwood.info Fri Dec 18 04:49:32 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Dec 2015 20:49:32 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? References: Message-ID: <5673d6ac$0$1612$c3e8da3$5496439d@news.astraweb.com> On Fri, 18 Dec 2015 05:51 pm, Chris Angelico wrote: > I would be inclined to ASCIIfy the apostrophes, dashes, and the > connection.py space that started this thread. People's names, URLs, > and demonstrative characters I'm more inclined to leave. Agreed? No. -- Steven From steve at pearwood.info Fri Dec 18 04:51:14 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Dec 2015 20:51:14 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? References: Message-ID: <5673d713$0$1612$c3e8da3$5496439d@news.astraweb.com> On Fri, 18 Dec 2015 11:02 am, Mark Lawrence wrote: > A lot of it is down to Windows, as the actual complaint is:- > > six.print_(source) Looks like a bug in six to me. See, without Unicode comments in the std lib, you never would have found that bug. -- Steven From steve at pearwood.info Fri Dec 18 04:51:24 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Dec 2015 20:51:24 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? References: Message-ID: <5673d71d$0$1612$c3e8da3$5496439d@news.astraweb.com> On Fri, 18 Dec 2015 06:12 pm, Serhiy Storchaka wrote: > Using non-ASCII apostrophes and like in docstrings may be considered a > bug. Absolutely not a bug. In Python 3, docstrings are Unicode, not bytes, and can contain any valid (or even invalid) Unicode code points, including non-characters. -- Steven From eryksun at gmail.com Fri Dec 18 05:24:51 2015 From: eryksun at gmail.com (eryk sun) Date: Fri, 18 Dec 2015 04:24:51 -0600 Subject: Problem on ctypes arguments in a DLL function In-Reply-To: <2331461b-cf4c-479c-8380-ddea3b7e7878@googlegroups.com> References: <2331461b-cf4c-479c-8380-ddea3b7e7878@googlegroups.com> Message-ID: On Fri, Dec 18, 2015 at 2:41 AM, wrote: > ValueError: Procedure probably called with too many arguments (4 bytes in excess The function's calling convention is x86 cdecl (CDLL, caller stack cleanup), but you're using the x86 stdcall convention (WinDLL, callee stack cleanup). For a 64-bit process they're actually the same, but you're using 32-bit Python, so you have to pay attention to the convention. > _lib = windll.LoadLibrary("C:\\Windows\\System32\\libusb0.dll") It should simply be _lib = CDLL('libusb0') windll/WinDLL is the wrong calling convention. Everything else is just a waste of keystrokes. windll.LoadLibrary is an inferior way to call WinDLL, since it can't pass constructor arguments such as use_errno or use_last_error. The System32 directory is on the DLL search path, and Windows will add the .dll extension for you. The calling convention is declared in the header file lusb0_usb.h [1]. For example: struct usb_bus *usb_get_busses(void); Notice there's no mention of __stdcall there, so it's using the default cdecl convention. > _usb_dev_handle = c_void_p You'll be better off using class _usb_dev_handle(Structure): pass _usb_dev_handle_p = POINTER(_usb_dev_handle) This provides stronger type safety. c_void_p is too permissive. It's easier to debug a ctypes ArgumentError than a memory access violation or data corruption. [1]: http://sourceforge.net/p/libusb-win32/code/413/tree/trunk/libusb/src/lusb0_usb.h From eryksun at gmail.com Fri Dec 18 05:35:37 2015 From: eryksun at gmail.com (eryk sun) Date: Fri, 18 Dec 2015 04:35:37 -0600 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: <5673d713$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <5673d713$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Dec 18, 2015 at 3:51 AM, Steven D'Aprano wrote: > On Fri, 18 Dec 2015 11:02 am, Mark Lawrence wrote: > >> A lot of it is down to Windows, as the actual complaint is:- >> >> six.print_(source) > > Looks like a bug in six to me. > > See, without Unicode comments in the std lib, you never would have found > that bug. I think Mark said he's piping the output. In this case it's not looking at the current console/terminal encoding. Instead it defaults to the platform's preferred encoding. On Windows that's the system ANSI encoding, such as codepage 1252. You can set PYTHONIOENCODING=UTF-8 to override this for stdin, stdout, and stderr. From jfong at ms4.hinet.net Fri Dec 18 06:15:56 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Fri, 18 Dec 2015 03:15:56 -0800 (PST) Subject: Problem on ctypes arguments in a DLL function In-Reply-To: References: <2331461b-cf4c-479c-8380-ddea3b7e7878@googlegroups.com> Message-ID: <054c6154-fc64-438a-8c4f-4c0b576d0c63@googlegroups.com> eryk sun at 2015/12/18 UTC+8 6:26:02PM wrote? > The function's calling convention is x86 cdecl (CDLL, caller stack > cleanup), but you're using the x86 stdcall convention (WinDLL, callee > stack cleanup). For a 64-bit process they're actually the same, but > you're using 32-bit Python, so you have to pay attention to the > convention. > > > _lib = windll.LoadLibrary("C:\\Windows\\System32\\libusb0.dll") > > It should simply be > > _lib = CDLL('libusb0') > > windll/WinDLL is the wrong calling convention. Everything else is just > a waste of keystrokes. windll.LoadLibrary is an inferior way to call > WinDLL, since it can't pass constructor arguments such as use_errno or > use_last_error. The System32 directory is on the DLL search path, and > Windows will add the .dll extension for you. > > The calling convention is declared in the header file lusb0_usb.h [1]. > For example: > > struct usb_bus *usb_get_busses(void); > > Notice there's no mention of __stdcall there, so it's using the > default cdecl convention. Hi! eryk, thank you very much. No idea how long I will take to get out of this gutter if not have your hint. I should pay more attention on keyword __stdcall in the header file. > > _usb_dev_handle = c_void_p > > You'll be better off using > > class _usb_dev_handle(Structure): > pass > > _usb_dev_handle_p = POINTER(_usb_dev_handle) > > This provides stronger type safety. c_void_p is too permissive. It's > easier to debug a ctypes ArgumentError than a memory access violation > or data corruption. > > [1]: http://sourceforge.net/p/libusb-win32/code/413/tree/trunk/libusb/src/lusb0_usb.h I think I am still in the kindergarten, not enter the gate of python school yet:-( much things to learn. From breamoreboy at yahoo.co.uk Fri Dec 18 08:12:42 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 18 Dec 2015 13:12:42 +0000 Subject: installation error In-Reply-To: <225949.79337.bm@smtp208.mail.bf1.yahoo.com> References: <225949.79337.bm@smtp208.mail.bf1.yahoo.com> Message-ID: On 18/12/2015 08:44, IBRAHIM ARANSIOLA RIDWAN via Python-list wrote: > > Hi, > My name is ridwan and I have a problem with installing the version 3.5.1 on my windows 10 system. > My question is those python have specified compatibility issues or I downloaded the wrong version for my operating system, or do I need to change my system settings in some aspect. > Thank you in anticipation of your favourable response . > Sent from Mail for Windows 10 > I am not aware of any issues with Windows 10 which I'm running myself. Is your system 32 or 64 bit? Which file did you download? You should not need to touch any system settings to install Python. Now please describe exactly what you tried to do and eactly what went wrong. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From andylockran at gmail.com Fri Dec 18 10:29:08 2015 From: andylockran at gmail.com (Andy Loughran) Date: Fri, 18 Dec 2015 07:29:08 -0800 (PST) Subject: Python Packaging and being a good testing citizen Message-ID: <26045c11-0ceb-46f2-a164-d90727a6acec@googlegroups.com> Hey guys, I wrote a python package to deal with heatmiser's protocol when communicating with devices over TCP. It would be good to wrap some tests around it as I know the core elements won't change - but need to add support for different devices and different connection methods. One thing has been bugging me, and that is that pyserial works differently on python2 to python3 due to accepting/rejecting strings in place of the new bytes datatype. I'm not sure how best to test this, so I'm looking for advice: https://www.andyloughran.co.uk/2015/12/16/python-testing/ Regards, Andy From george.trojan at noaa.gov Fri Dec 18 14:09:09 2015 From: george.trojan at noaa.gov (George Trojan) Date: Fri, 18 Dec 2015 19:09:09 +0000 Subject: Python 3.1 test issue In-Reply-To: References: Message-ID: <567459D5.7000300@noaa.gov> On 12/16/2015 8:07 PM, Terry Reedy wrote: > On 12/16/2015 1:22 PM, George Trojan wrote: >> I installed Python 3.1 on RHEL 7.2. > > According to the output below, you installed 3.5.1. Much better than > the years old 3.1. > This was not my only mistake. I ran the test on Fedora 19, not RHEL 7.2. >> The command make test hangs (or >> takes a lot of time on test_subprocess >> [396/397] test_subprocess > >> [["test_socket", 0, false], > > This appears to pass arguments to a specific test, test_socket. I > would guess this is done by setting sys.argv. This is the first I knew > about this. What follows of a dict of options. Most could have been > set with normal --option flags. Most are the defaults. > > > {"huntrleaks": false, > > "match_tests": null, > > "failfast": false, > > "output_on_failure": false, > > "use_resources": >> ["curses", "network", "decimal", "cpu", "subprocess", "urlfetch"], >> "pgo": false, > > "timeout": null > > } > > ] > > The relevant non-default is 'use_resources'. In particular, 'cpu' > runs 'certain CPU-heavy tests', and 'subprocess' runs all subprocess > tests. I ran both 'python -m test -usubprocess test_subprocess' and > 'python -m test -ucpu -usubprocess test_subprocess > and both took about the same time and less than a minute. > > The only thing that puzzles me is that I don't see '"randomize": true' > in the dict above, but test_subprocess is 317 in the default > alphabetical order, not 396. > > You might try re-running with defaults: python -m test. Thanks, after several trials I settled for command ("make test" hangs for Python3.4.1 too): dilbert at gtrojan> /usr/local/src/Python-3.4.1/python Lib/test/test_socket.py which was the culprit. After checking the code, I found that creating RDS socket did not raise an exception. >>> import socket >>> s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) >>> It does on other RH based systems (Centos, RHEL, Fedora != 19). FC 19 has /proc/sys/net/rds, other systems don't. So this is probably not a Python issue, but buggy implementation of RDS. George From tjreedy at udel.edu Fri Dec 18 16:56:05 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Dec 2015 16:56:05 -0500 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: <5673d6ac$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <5673d6ac$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 12/18/2015 4:49 AM, Steven D'Aprano wrote: > On Fri, 18 Dec 2015 05:51 pm, Chris Angelico wrote: > >> I would be inclined to ASCIIfy the apostrophes, dashes, and the >> connection.py space that started this thread. People's names, URLs, >> and demonstrative characters I'm more inclined to leave. Agreed? > > No. No in the sense of a blanket rule. But in at least some cases, yes. In idlelib/README.txt, ' somehow got changed to the a latin-1 encoded slanted apostrophe (by Notepad++ I think) when I edited the file. Since IDLE *assumes* that the file is ascii-only and does not specify an encoding, display failed on Serhiy's non-Windows system. Issue 25905. I changed it back. Other accidents should be fixed. Guido also wants syntax chars and identifiers in stdlib code kept to ascii only for universal readability. Maybe that will change someday. -- Terry Jan Reedy From marko at pacujo.net Fri Dec 18 17:16:45 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 19 Dec 2015 00:16:45 +0200 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? References: <5673d6ac$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8760zvjtbm.fsf@elektro.pacujo.net> Terry Reedy : > Guido also wants syntax chars and identifiers in stdlib code kept to > ascii only for universal readability. Readability, or writability? Most people would have no idea how to produce the characters with their keyboards. Marko From p_s_d_a_s_i_l_v_a_ns at netcabo.pt Fri Dec 18 17:19:27 2015 From: p_s_d_a_s_i_l_v_a_ns at netcabo.pt (Paulo da Silva) Date: Fri, 18 Dec 2015 22:19:27 +0000 Subject: issues References: Message-ID: ?s 22:44 de 04-12-2015, Anna Szaharcsuk escreveu: > Hello there, > > I was trying to install PyCharm, but didn't worked and needed interpreter. > the computer advised to install the python for windows. > I don't know PyCharm but it is likely it needs python. Did you install python? You may need to install it from https://www.python.org/downloads/windows/ You may also need to check if you need python 2, python 3 or both. They are different. HTH Paulo From rosuav at gmail.com Fri Dec 18 18:58:39 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 19 Dec 2015 10:58:39 +1100 Subject: Should stdlib files contain 'narrow non breaking space' U+202F? In-Reply-To: <8760zvjtbm.fsf@elektro.pacujo.net> References: <5673d6ac$0$1612$c3e8da3$5496439d@news.astraweb.com> <8760zvjtbm.fsf@elektro.pacujo.net> Message-ID: On Sat, Dec 19, 2015 at 9:16 AM, Marko Rauhamaa wrote: > Terry Reedy : > >> Guido also wants syntax chars and identifiers in stdlib code kept to >> ascii only for universal readability. > > Readability, or writability? Most people would have no idea how to > produce the characters with their keyboards. Most of the non-ASCII in the CPython source is people's names, which will simply be copied and pasted from somewhere. ChrisA From malitician at gmail.com Fri Dec 18 22:15:15 2015 From: malitician at gmail.com (malitician at gmail.com) Date: Fri, 18 Dec 2015 19:15:15 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: good explanation Steven but can you please do more by posting the exact code as it relate to the question please? From vadodsantos at gmail.com Fri Dec 18 22:15:53 2015 From: vadodsantos at gmail.com (Osvaldo Dias dos Santos) Date: Sat, 19 Dec 2015 04:15:53 +0100 Subject: IDLE 3.5.1 quits unexpectedly (portuguese keyboard) Message-ID: Hi, Pressing the tilde key my iMac portuguese keyboard quits IDLE unexpectedly (along with any associated files I may be working on, including code). The keyboard image is attached. The tilde key is the second orange one from the top. This key is very important in this language, because pressing it together with the shift key, the caret ( ^ ) symbol is entered. So, if I try to enter a caret and press the shift and the tilde key to do it, IDLE quits and any unsaved file information (even code) is lost. Then Apple crash report window opens, but if I click the reopen button nothing happens, IDLE does not reopen. Python 3.5.1 OS X 10.11.2 (El Capitan) Anyone may help ? Thank you, Kind regards, Osvaldo From nobody at nowhere.invalid Sat Dec 19 02:53:45 2015 From: nobody at nowhere.invalid (Nobody) Date: Sat, 19 Dec 2015 07:53:45 +0000 Subject: python 3.4, os.walk does not walk into cdroms References: Message-ID: On Thu, 17 Dec 2015 14:03:25 +0100, Siegfried Kaiser wrote: > I have a problem with os.walk - it does not walk into a mounted cdrom, I > do not see the cdrom in the walk at all. > What can I do to walk into cdrom? 1. Are you sure that the directory tree contains the actual mount point, not just a symlink to it? os.walk() doesn't follow symlinks unless followlinks=True is given explicitly. 2. Have you tried using the onerror= parameter to report errors? The default is to silently ignore errors from os.listdir(). From breamoreboy at yahoo.co.uk Sat Dec 19 09:47:08 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 19 Dec 2015 14:47:08 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On 19/12/2015 03:15, malitician at gmail.com wrote: > good explanation Steven but can you please do more by posting the exact code as it relate to the question please? > Please show us the code that you've written and we'll help, we do not 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 redysangco at gmail.com Sat Dec 19 12:45:38 2015 From: redysangco at gmail.com (Renato Emanuel Dysangco) Date: Sat, 19 Dec 2015 09:45:38 -0800 Subject: v3.5.1 - msi download Message-ID: hello is an **.msi* version of your *Python 3.5.1 (32 bit)* in the pipeline soon? thanks for your time From skybuck2000 at hotmail.com Sat Dec 19 12:56:17 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Sat, 19 Dec 2015 18:56:17 +0100 Subject: (Execution) Termination bit, Alternation bit. Message-ID: Hello, I'd like to see instruction execution enhanced with the following two ideas: 1. A termination bit, and a terminator pointer. 2. A alternation bit, and a alternate pointer. The purpose of these bits is as follows: Before a processor/core executes an instruction both bits are examined. 1. If the termination bit is set the instruction is not executed and instead the processor sets the instruction pointer to the termination pointer. 2. If the alternation bit is set the instruction is not executed and instead the processor sets the instruction pointer to the alternation pointer. The idea behind this is support multi threading/parallelism better. The idea is that Thread A could terminate Thread B immediately so that Thread B does not continue execution. The idea is also that Thread A could influence Thread B to start executing a different path. Hopefully these bits are enough for operating systems to add support for this. Some issues remaining could be items pushed on the stack. Perhaps operating system can deal with that, or perhaps compiler or perhaps some other special instructions or software methods can be added. Hopefully operating systems can include data structures per thread that can be loaded into the core, and into these bits and pointers so that it becomes active. During a context switch these bits and pointers should be loaded accordingly. So these two bits and these two pointers become part of the context. I think these two features would be usefull to make multi-threading more responsive and faster reaction time to changes/events occuring. (Eventually it would be nice if these low level features would end up in high level languages like Python ;)) Bye, Skybuck. From PointedEars at web.de Sat Dec 19 13:32:00 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 19 Dec 2015 19:32 +0100 Subject: Installing PyCharm on Windows (was: issues) References: Message-ID: <32971984.pfH099DPo1@PointedEars.de> Anna Szaharcsuk wrote: > I was trying to install PyCharm, but didn't worked and needed interpreter. > the computer advised to install the python for windows. Not ?the python for windows? (that would be some species of snake), but _Python_ for _Windows_, the programming language interpreter. Just do as ?the computer advised?. > Can you help me, please, PyCharm stillnot working...allways gives a > message for repair, after- the repair successful and again message for > repair... Have you installed Python first? If no, it cannot work (and please think about this: What good is an IDE/editor for a programming language if you do not also have the interpreter/compiler?). It says so in the ?Quick Start Guide? in the ?PyCharm 5.0 Help?, currently to be found on the PyCharm Web site under ?Docs & Demos?: Have you tried to install Python ? 3.4.4rc1 on Windows XP? If yes, it cannot work; you need Python < 3.4.4rc1 instead (and you should seriously consider upgrading Windows or even better, to switch to a real operating system, like GNU/Linux ? many of the latter come for free and give you more freedom than Windows): Before your next posting, please read -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From haazik_dawood at hotmail.com Sat Dec 19 17:09:25 2015 From: haazik_dawood at hotmail.com (Abdul Basit) Date: Sun, 20 Dec 2015 03:09:25 +0500 Subject: Please help Message-ID: I am receiving this error while installing python interpreter version 3.5.1 (32 bit) Error is " This program cannot start because api-ms-win-crt-runtime-l1-1-0.dll is missing from your computer" I reinstalled this file but again this error message What should I do to remove this issue kindly help me Regards Abdul Basit From iiswayzii at gmail.com Sat Dec 19 17:21:29 2015 From: iiswayzii at gmail.com (Amaan Hussain) Date: Sat, 19 Dec 2015 23:21:29 +0100 Subject: Error Message-ID: Hello. I get an error saying "api-ms-win-crt-runtime-l1-1-0.dll is missing" Can you tell me how to fix this. Thanks From malitician at gmail.com Sat Dec 19 18:19:56 2015 From: malitician at gmail.com (malitician at gmail.com) Date: Sat, 19 Dec 2015 15:19:56 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> you are absolutely correct Mark i'm a beginner in python and from the original question and test case given above i wrote this class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance +=amount def withdraw(self, amount): self.balance -= amount my_account = BankAccount(90) my_account.withdraw(1000) if my_account.balance < 4: print('invalid transaction') class MinimumBalanceAccount(BankAccount): def __init__(self, MinimumBalance=4): self.minbalance = MinimumBalance after executing this i got this TEST SOLUTION ERROR which i don't know what it means {"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000065"}} -910 invalid transaction SO please what is wrong with my code, does it not meet the requirement of the "test case" given above in the question? Thanks in advance From breamoreboy at yahoo.co.uk Sat Dec 19 19:41:12 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Dec 2015 00:41:12 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> Message-ID: On 19/12/2015 23:19, malitician at gmail.com wrote: > you are absolutely correct Mark > i'm a beginner in python and from the original question and test case given above i wrote this > > class BankAccount(object): > def __init__(self, initial_balance=0): > self.balance = initial_balance > def deposit(self, amount): > self.balance +=amount > def withdraw(self, amount): > self.balance -= amount > my_account = BankAccount(90) > my_account.withdraw(1000) > if my_account.balance < 4: > print('invalid transaction') > class MinimumBalanceAccount(BankAccount): > def __init__(self, MinimumBalance=4): > self.minbalance = MinimumBalance > > after executing this i got this TEST SOLUTION ERROR which i don't know what it means > > {"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000065"}} > -910 > invalid transaction > > SO please what is wrong with my code, does it not meet the requirement of the "test case" given above in the question? > Thanks in advance > It's a start but you've still left things out. If I run your code as given above it outputs "invalid transaction", exactly as expected. So how are you running the code? Where does the extra output you give above come from, presumably the "test case", whatever that might be? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From torriem at gmail.com Sat Dec 19 20:09:01 2015 From: torriem at gmail.com (Michael Torrie) Date: Sat, 19 Dec 2015 18:09:01 -0700 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> Message-ID: <5675FFAD.3040902@gmail.com> On 12/19/2015 05:41 PM, Mark Lawrence wrote: > On 19/12/2015 23:19, malitician at gmail.com wrote: >> you are absolutely correct Mark >> i'm a beginner in python and from the original question and test case given above i wrote this >> >> class BankAccount(object): >> def __init__(self, initial_balance=0): >> self.balance = initial_balance >> def deposit(self, amount): >> self.balance +=amount >> def withdraw(self, amount): >> self.balance -= amount >> my_account = BankAccount(90) >> my_account.withdraw(1000) >> if my_account.balance < 4: >> print('invalid transaction') ^^^^^^^^^^^^^^^^^^ This code probably belongs in the withdraw() method. >> class MinimumBalanceAccount(BankAccount): >> def __init__(self, MinimumBalance=4): >> self.minbalance = MinimumBalance >> >> after executing this i got this TEST SOLUTION ERROR which i don't know what it means >> >> {"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000065"}} >> -910 >> invalid transaction >> >> SO please what is wrong with my code, does it not meet the requirement of the "test case" given above in the question? >> Thanks in advance >> > > It's a start but you've still left things out. If I run your code as > given above it outputs "invalid transaction", exactly as expected. So > how are you running the code? Where does the extra output you give > above come from, presumably the "test case", whatever that might be? While the output is as we'd expect, the program's logic is probably wrong. Would not you want to put that logic in the withdraw method to prevent an invalid transaction? From breamoreboy at yahoo.co.uk Sat Dec 19 20:51:36 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Dec 2015 01:51:36 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5675FFAD.3040902@gmail.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> <5675FFAD.3040902@gmail.com> Message-ID: On 20/12/2015 01:09, Michael Torrie wrote: > On 12/19/2015 05:41 PM, Mark Lawrence wrote: >> On 19/12/2015 23:19, malitician at gmail.com wrote: >>> you are absolutely correct Mark >>> i'm a beginner in python and from the original question and test case given above i wrote this >>> >>> class BankAccount(object): >>> def __init__(self, initial_balance=0): >>> self.balance = initial_balance >>> def deposit(self, amount): >>> self.balance +=amount >>> def withdraw(self, amount): >>> self.balance -= amount >>> my_account = BankAccount(90) >>> my_account.withdraw(1000) >>> if my_account.balance < 4: >>> print('invalid transaction') > ^^^^^^^^^^^^^^^^^^ > This code probably belongs in the withdraw() method. > >>> class MinimumBalanceAccount(BankAccount): >>> def __init__(self, MinimumBalance=4): >>> self.minbalance = MinimumBalance >>> >>> after executing this i got this TEST SOLUTION ERROR which i don't know what it means >>> >>> {"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000065"}} >>> -910 >>> invalid transaction >>> >>> SO please what is wrong with my code, does it not meet the requirement of the "test case" given above in the question? >>> Thanks in advance >>> >> >> It's a start but you've still left things out. If I run your code as >> given above it outputs "invalid transaction", exactly as expected. So >> how are you running the code? Where does the extra output you give >> above come from, presumably the "test case", whatever that might be? > > While the output is as we'd expect, the program's logic is probably > wrong. Would not you want to put that logic in the withdraw method to > prevent an invalid transaction? > Frankly I've no idea on the grounds that I simply cannot be bothered to look, and at this time of the night/early morning I'm not inclined to play guessing games. Perhaps the OP would be kind enough to provide the requirements and his/her code in one hit, the answer can be one hit, and we happily move on to Boxing day. -- 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 Dec 19 22:44:59 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 20 Dec 2015 14:44:59 +1100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: Message-ID: On Sun, Dec 20, 2015 at 1:27 PM, Dennis Lee Bieber wrote: > On Sat, 19 Dec 2015 18:56:17 +0100, "Skybuck Flying" > declaimed the following: > >>Hello, >> >>I'd like to see instruction execution enhanced with the following two ideas: >> >>1. A termination bit, and a terminator pointer. >>2. A alternation bit, and a alternate pointer. >> > Don't see it here... You've just enabled leaving lots of corrupted data > structures in the system... (Imagine your "termination" branch is taken > after a call that allocated a 500MB block of memory, but before the call > that returns that memory to the system). Honestly, I wouldn't bother responding to this kind of thing here on python-list. There's nothing about Python in the entire post. It's a CPU-level feature that "might" be able to be adopted eventually by the implementation of languages like Python. If I were to hazard a guess, I would say that a feature like this would migrate first through CPU discussions, then through C compilers, then to PyPy, and finally might end up in CPython, if it got widespread use. But until it gets at least to the PyPy level, it's not of much interest here. (Even then, it'll be an obscure feature on a very specific platform, and probably of only cursory interest.) If this really IS worth doing, there'll be OS programmers all over it for years before it ever affects Python. ChrisA From josef.pktd at gmail.com Sat Dec 19 23:32:16 2015 From: josef.pktd at gmail.com (Josef Pktd) Date: Sat, 19 Dec 2015 20:32:16 -0800 (PST) Subject: Installing PyCharm on Windows (was: issues) In-Reply-To: <32971984.pfH099DPo1@PointedEars.de> References: <32971984.pfH099DPo1@PointedEars.de> Message-ID: On Saturday, December 19, 2015 at 1:32:27 PM UTC-5, Thomas 'PointedEars' Lahn wrote: > Anna Szaharcsuk wrote: > > > I was trying to install PyCharm, but didn't worked and needed interpreter. > > the computer advised to install the python for windows. > > Not ?the python for windows? (that would be some species of snake), but > _Python_ for _Windows_, the programming language interpreter. Just do as > ?the computer advised?. > > > Can you help me, please, PyCharm stillnot working...allways gives a > > message for repair, after- the repair successful and again message for > > repair... > > Have you installed Python first? If no, it cannot work (and please think > about this: What good is an IDE/editor for a programming language if you do > not also have the interpreter/compiler?). It says so in the ?Quick Start > Guide? in the ?PyCharm 5.0 Help?, currently to be found on the PyCharm Web > site under ?Docs & Demos?: > > > > Have you tried to install Python ? 3.4.4rc1 on Windows XP? If yes, it > cannot work; you need Python < 3.4.4rc1 instead (and you should seriously > consider upgrading Windows or even better, to switch to a real operating > system, like GNU/Linux ? many of the latter come for free and give you more > freedom than Windows): Thanks for the tip, I will switch away from Windows when I have an extra year to figure out weird things in other operating systems. So far I never managed more than two weeks in a Linux virtual machine before never opening it again. Josef PS: loyal Windows user since Windows 95, currently considering whether to upgrade from 7 and 8 to 10. PPS: The mainstream: Python and Windows ("it's not just for 'hackers'"): http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html https://www.netmarketshare.com/operating-system-market-share.aspx?qprid=10&qpcustomd=0 PPPS: Scientific Python mailing list have been free of snide remarks about Windows users for a while, but not of real problems with Windows (or OSX or Linux) PPPPS: Windows 10 with Computer as a Service following Apple will lock in many users again to "everything Microsoft", but without the monopoly. > > > > Before your next posting, please read > > > > -- > PointedEars > > Twitter: @PointedEars2 > Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Sun Dec 20 03:28:44 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 20 Dec 2015 09:28:44 +0100 Subject: Installing PyCharm on Windows References: <32971984.pfH099DPo1@PointedEars.de> Message-ID: <2632865.Kq7QuO2XSa@PointedEars.de> Josef Pktd wrote: ^^^^^^^^^^ I doubt that is your real name. > On Saturday, December 19, 2015 at 1:32:27 PM UTC-5, Thomas 'PointedEars' > Lahn wrote: >> Have you tried to install Python ? 3.4.4rc1 on Windows XP? If yes, it >> cannot work; you need Python < 3.4.4rc1 instead (and you should seriously >> consider upgrading Windows or even better, to switch to a real operating >> system, like GNU/Linux ? many of the latter come for free and give you >> more freedom than Windows): > > Thanks for the tip, I will switch away from Windows when I have an extra > year to figure out weird things in other operating systems. Ordinary people (as opposed to tech-savvy people) have been known to set up a current Linux distribution in a day and get accustomed to it in a week. Those ?weird things? you are talking about are merely something that needs a little getting used to if you had gotten used to Windows. Of course, not all people are (still) that flexible in their thinking. > So far I never managed more than two weeks in a Linux virtual machine > before never opening it again. Your problem alone. > PPS: The mainstream: Python and Windows ("it's not just for 'hackers'"): Non-Windows operating systems are not just for hackers since more than a decade. They are for reasonably smart people, though, who would not give up at the first sign of trouble. And who cares about the mainstream opinion? > http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html Thank you so much for providing that valuable reference. I am sure nobody here knew :-> > https://www.netmarketshare.com/operating-system-market-share.aspx?qprid=10&qpcustomd=0 A million flies can be wrong. > PPPS: Scientific Python mailing list have been free of snide remarks about > Windows users for a while, but not of real problems with Windows (or OSX > or Linux) Thanks to you that would have changed if this were a ?scientific Python mailing list?. Mine was not a snide remark, but the truth. Those other operating systems I was talking about do give users more freedom. For example, the freedom to use it on as many different machines as you like without an extra license, to see the source code, to modify it, and to redistribute the modification including an attribution to yourself. > PPPPS: Windows 10 with Computer as a Service following Apple will lock in > many users again to "everything Microsoft", but without the monopoly. If people are made dependent on a single vendor, how is that not attempting to attain a monopoly? Anyhow, *I* was not intending to start an OS flame war, but to point out that in my experience Python is easier to handle on other OSes than Windows, so it is a contingency that should be considered. As you indicated, that does not mean that one has to abandon Windows for booting the computer. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From steve at pearwood.info Sun Dec 20 04:23:00 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Dec 2015 20:23:00 +1100 Subject: Installing PyCharm on Windows References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> Message-ID: <56767376$0$1596$c3e8da3$5496439d@news.astraweb.com> On Sun, 20 Dec 2015 07:28 pm, Thomas 'PointedEars' Lahn wrote: > Josef Pktd wrote: > ^^^^^^^^^^ > I doubt that is your real name. So what? I doubt "PointedEars" is your real name, but you don't see me making a big deal out of it. You're welcome to call yourself by any reasonable moniker. -- Steven From rosuav at gmail.com Sun Dec 20 04:57:14 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 20 Dec 2015 20:57:14 +1100 Subject: Installing PyCharm on Windows In-Reply-To: <56767376$0$1596$c3e8da3$5496439d@news.astraweb.com> References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> <56767376$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Dec 20, 2015 at 8:23 PM, Steven D'Aprano wrote: > On Sun, 20 Dec 2015 07:28 pm, Thomas 'PointedEars' Lahn wrote: > >> Josef Pktd wrote: >> ^^^^^^^^^^ >> I doubt that is your real name. > > > So what? I doubt "PointedEars" is your real name, but you don't see me > making a big deal out of it. You're welcome to call yourself by any > reasonable moniker. Also, I see no reason to believe it isn't. An abbreviation, perhaps, but I have a middle name, and my first name is longer than "Chris", yet I don't get in strife for not using my "real name". ChrisA From denismfmcmahon at gmail.com Sun Dec 20 06:04:50 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 20 Dec 2015 11:04:50 -0000 (UTC) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Sat, 12 Dec 2015 01:05:01 -0800, Harbey Leke wrote: > Create a class called BankAccount > > .Create a constructor that takes in an integer and assigns this to a > `balance` property. > > .Create a method called `deposit` that takes in cash deposit amount and > updates the balance accordingly. > > .Create a method called `withdraw` that takes in cash withdrawal amount > and updates the balance accordingly. if amount is greater than balance > return `"invalid transaction"` > > .Create a subclass MinimumBalanceAccount of the BankAccount class > > Please i need help on this i am a beginer into python programming. It sounds like you're taking a python course. Your course should have taught you all you need to carry out this programming task before setting this exercise. If you have not been paying attention, have failed to attend some sessions, or have not been keeping up with the course in some way, that might explain your difficulty. Perhaps you should approach the course tutors and ask for some remedial assistance. Alternatively, if you have so far been a fully attending, attentive and straight A student on this course, perhaps they are setting exercises for which they have not previously provided the necessary tuition. If that is the case, I suggest you ask them to reimburse your course fees, and then go and find better tutors. -- Denis McMahon, denismfmcmahon at gmail.com From skybuck2000 at hotmail.com Sun Dec 20 06:25:30 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Sun, 20 Dec 2015 12:25:30 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: "Richard Damon" wrote in message news:QHody.3724$Bz5.3354 at fx04.iad... On 12/19/15 9:03 PM, Skybuck Flying wrote: > It could be usefull if the instruction pointer/return address that was > pushed onto the stack when the interrupt handler was called can be > modified by the interrupt handler so that when it returns the modified > instruction pointer is popped from the stack. > > This would assume: > > 1. To be interrupted processor pushed it's own instruction pointer onto > the stack. > 2. To be interrupted processor pops it's own instruction pointer from > stack. > > Bye, > Skybuck. " It would be an unusual machine where you couldn't modify the return address on the stack to change the address you return to. " This does make me wonder how Windows 7 terminates threads/processes/hanging applications. Apperently there is some kind of mechanism for this. Perhaps it's not fully exposed to application developers or perhaps in a somewhat more complex way via all kinds of APIs ? An example of how to terminate threads/processes instantly on Windows 7 could be interesting. Bye, Skybuck. From rosuav at gmail.com Sun Dec 20 06:29:14 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 20 Dec 2015 22:29:14 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Sun, Dec 20, 2015 at 10:04 PM, Denis McMahon wrote: > It sounds like you're taking a python course. Your course should have > taught you all you need to carry out this programming task before setting > this exercise. > > Alternatively, if you have so far been a fully attending, attentive and > straight A student on this course, perhaps they are setting exercises for > which they have not previously provided the necessary tuition. There is a half-and-half possibility, too; sometimes a course will give you a challenge, and *then* introduce you to the techniques necessary for solving it (after letting you have a shot at it on your own). I don't like that style, myself, but it does exist, so it may be worth skimming forward a few sections in the course to see what it teaches next. But frankly, I doubt that's what's going on here. ChrisA From shlyoko at gmail.com Sun Dec 20 07:34:40 2015 From: shlyoko at gmail.com (Emil Natan) Date: Sun, 20 Dec 2015 12:34:40 +0000 Subject: return from function Message-ID: I'm completely new to Python. I have the following function to find the parent for domain. It removes the left most label from the name and then checks if SOA record exists for the reminder, if not it calls itself recursively removing another label and checking again for SOA record. It works well for 'co.uk' and 'amazon.co.uk' for example. It does not return the expected value 'uk' when invoked for ' amazon1.co1.uk', though the print command before the return prints what is expected. Can someone explain why? Thanks. >>> find_parent_domain('amazon.co1.uk.') Test for parent domain co1.uk. NXDOMAIN: invoke find_parent_domain recursively Test for parent domain uk. the parent domain we use is: uk. >>> import dns.resolver from dns.exception import DNSException def find_parent_domain(domainname): if domainname == '.': parent_domain = None return parent_domain parent_domain = domainname.partition('.')[2] try: print('Test for parent domain %s' % parent_domain) z = dns.resolver.query(parent_domain, 'SOA') print('the parent domain we use is: %s' % parent_domain) return parent_domain except dns.resolver.NXDOMAIN: print('NXDOMAIN: invoke find_parent_domain recursively') find_parent_domain(parent_domain) except dns.resolver.NoAnswer: print('NoAnswer: invoke find_parent_domain recursively') find_parent_domain(parent_domain) From stephane at wirtel.be Sun Dec 20 09:15:13 2015 From: stephane at wirtel.be (Stephane Wirtel) Date: Sun, 20 Dec 2015 15:15:13 +0100 Subject: Deadline for PythonFOSDEM 2016 is today. Message-ID: <20151220141513.GA2026@sg1> Just inform you that the deadline for the CfP of the PythonFOSDEM will finish this evening. If you have a last talk to submit, please do it. Call For Proposals ================== This is the official call for sessions for the Python devroom at FOSDEM 2016. FOSDEM is the Free and Open source Software Developers' European Meeting, a free and non-commercial two-day week-end that offers open source contributors a place to meet, share ideas and collaborate. FOSDEM is in Brussels in Belgium on 30th January. It's the biggest event in Europe with +5000 hackers, +400 speakers. For this edition, Python will be represented by its Community. If you want to discuss with a lot of Python Users, it's the place to be! Important dates =============== * Submission deadlines: 2015-12-20 * Acceptance notifications: 2015-12-24 Practical ========= * The duration for talks will be 30 minutes, including presentations and questions and answers. * Presentation can be recorded and streamed, sending your proposal implies giving permission to be recorded. * A mailing list for the Python devroom is available for discussions about devroom organisation. You can register at this address: https://lists.fosdem.org/listinfo/python-devroom How to submit ============= All submissions are made in the Pentabarf event planning tool at https://penta.fosdem.org/submission/FOSDEM16 When submitting your talk in Pentabarf, make sure to select the Python devroom as the Track. Of course, if you already have a user account, please reuse it. Questions ========= Any questions, please sned an email to info AT python-fosdem DOT org Thank you for submitting your sessions and see you soon in Brussels to talk about Python. If you want to keep informed for this edition, you can follow our twitter account @PythonFOSDEM. * FOSDEM 2016: https://fosdem.org/2016 * Python Devroom: http://python-fosdem.org * Twitter: https://twitter.com/PythonFOSDEM Thank you so much, Stephane -- St?phane Wirtel - http://wirtel.be - @matrixise From josef.pktd at gmail.com Sun Dec 20 12:15:28 2015 From: josef.pktd at gmail.com (Josef Pktd) Date: Sun, 20 Dec 2015 09:15:28 -0800 (PST) Subject: Installing PyCharm on Windows In-Reply-To: <2632865.Kq7QuO2XSa@PointedEars.de> References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> Message-ID: <52076a04-4803-4cd5-b86a-65d8fdc81aea@googlegroups.com> On Sunday, December 20, 2015 at 3:29:34 AM UTC-5, Thomas 'PointedEars' Lahn wrote: > Josef Pktd wrote: > ^^^^^^^^^^ > I doubt that is your real name. But it's the name I used for almost all of my Python open source development, and can be easily googled. except I misspelled my "name" josef-pkt when I set up my github account. > > > On Saturday, December 19, 2015 at 1:32:27 PM UTC-5, Thomas 'PointedEars' > > Lahn wrote: > >> Have you tried to install Python ? 3.4.4rc1 on Windows XP? If yes, it > >> cannot work; you need Python < 3.4.4rc1 instead (and you should seriously > >> consider upgrading Windows or even better, to switch to a real operating > >> system, like GNU/Linux ? many of the latter come for free and give you > >> more freedom than Windows): > > > > Thanks for the tip, I will switch away from Windows when I have an extra > > year to figure out weird things in other operating systems. > > Ordinary people (as opposed to tech-savvy people) have been known to set up > a current Linux distribution in a day and get accustomed to it in a week. > Those ?weird things? you are talking about are merely something that needs a > little getting used to if you had gotten used to Windows. Of course, not > all people are (still) that flexible in their thinking. Maybe I don't **want** to be this flexible because I allocate my "flexibility" to other things (instead of, for example, figuring out how packaging and paths work on Linux). > > > So far I never managed more than two weeks in a Linux virtual machine > > before never opening it again. > > Your problem alone. If I have a problem, then I assume many other Windows users will also have problems, if they are even willing to try. > > > PPS: The mainstream: Python and Windows ("it's not just for 'hackers'"): > > Non-Windows operating systems are not just for hackers since more than a > decade. They are for reasonably smart people, though, who would not give up > at the first sign of trouble. > > And who cares about the mainstream opinion? I do! Almost all economists and econometricians that I know are using Windows. And I was working for many years on open software to get to a stage where they can use Python instead of commercial packages like GAUSS, Stata or Matlab. The main target group are not programmers or users with a computer science background. > > > http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html > > Thank you so much for providing that valuable reference. I am sure nobody > here knew :-> > > > https://www.netmarketshare.com/operating-system-market-share.aspx?qprid=10&qpcustomd=0 > > A million flies can be wrong. > > > > > PPPS: Scientific Python mailing list have been free of snide remarks about > > Windows users for a while, but not of real problems with Windows (or OSX > > or Linux) > > Thanks to you that would have changed if this were a ?scientific Python > mailing list?. I complained a few times on the mailing lists when the response to a question by a Windows users was to switch to Linux. It's not helpful in almost all cases, and now the standard response for setup problems is to use Anaconda or WinPython. I also found it silly if Software Carpentry courses use exclusively Linux in the course and people are then surprised that users go back to their office and their Windows machine, and their commercial software, ignoring most of what they learned. > > Mine was not a snide remark, but the truth. Those other operating systems I > was talking about do give users more freedom. For example, the freedom to > use it on as many different machines as you like without an extra license, > to see the source code, to modify it, and to redistribute the modification > including an attribution to yourself. "Richtige M?nner nehmen Pitralon" everything else is "unreal" I'm writing BSD licensed software, but I never felt the urge to change more than a few options in the operating system, and was never interested in the "freedom" to fix the kernel (and I was never interested in fixing my car either). Josef PS: I learned a lot from this mailing list when I started with Python 12 to 15 years ago. But either the mailing list or my perception has changed in that I see now several or many comments that ignore that there are many users and developers using Python without an explicit programming background. > > > PPPPS: Windows 10 with Computer as a Service following Apple will lock in > > many users again to "everything Microsoft", but without the monopoly. > > If people are made dependent on a single vendor, how is that not attempting > to attain a monopoly? > > Anyhow, *I* was not intending to start an OS flame war, but to point out > that in my experience Python is easier to handle on other OSes than Windows, > so it is a contingency that should be considered. As you indicated, that > does not mean that one has to abandon Windows for booting the computer. > > -- > PointedEars > > Twitter: @PointedEars2 > Please do not cc me. / Bitte keine Kopien per E-Mail. From ganesh1pal at gmail.com Sun Dec 20 12:30:27 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Sun, 20 Dec 2015 23:00:27 +0530 Subject: How to ignore error with anon-zero exit status Message-ID: def run_scanner(): """ Mount /filesystems and run scanner """ for cmd in [" mount /filesystems ", " scanner_start"]: try: out, err, ret = run(cmd, timeout=3600) if ret != 0: logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret)) return False except Exception as e: logging.exception("Failed to run %s got %s" % (cmd, e)) return False logging.info("Mount /tmp.....Done !!!") time.sleep(30) Iam on python 2.6 and Linux , I need you inputs on how to ignore an specific error when the mount fails In general the mount has zero status if it succeeds and anon-zero exit status if it fails. 1.But for one rare case the mount succeeds but returns anon-zero exit status and when we get ?Reading GUID from da0xxx: No such file or directory? error , how to ignore this error and proceed with the above code 2. Also need to add this check only for mount case i.e mount /filesystems and not scanner_start Any recommendations would be appreciated. Regards, Ganesh From python at lucidity.plus.com Sun Dec 20 16:21:07 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 20 Dec 2015 21:21:07 +0000 Subject: Installing PyCharm on Windows In-Reply-To: <2632865.Kq7QuO2XSa@PointedEars.de> References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> Message-ID: <56771BC3.608@lucidity.plus.com> Hello Thomas, On 19/12/15 18:32, Thomas 'PointedEars' Lahn wrote: > (and you should seriously > consider upgrading Windows or even better, to switch to a real operating > system, like GNU/Linux On 20/12/15 08:28, Thomas 'PointedEars' Lahn wrote: > Anyhow, *I* was not intending to start an OS flame war, Really? Specifically telling someone that their OS of choice is "not a real operating system" (without any sort of justification) is not intending to start an OS flame war? Of course that's what you intended to do. The answer to "Python does not work in this way for me" should *never* be "change your operating system". FWIW, I can see that you do indeed have something to add to these discussions but unfortunately you seem to also feel the need to provoke a reaction from people. As a result, anything of value you impart - and there IS something there - gets lost in the noise. If you could just bring yourself to offer your expertise without making direct value judgements on other people's choices, preferences and ability compared to your own, I think your voice would be listened to a lot more and things would be a whole lot easier. This is just friendly advice - I am not _insisting_ that you do anything you do not wish to ;) E. From PointedEars at web.de Sun Dec 20 16:22:05 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 20 Dec 2015 22:22:05 +0100 Subject: Ignore error with non-zero exit status (was: How to ignore error with anon-zero exit status) References: Message-ID: <3883651.fOIMIIEhYO@PointedEars.de> Ganesh Pal wrote: > def run_scanner(): > """ > Mount /filesystems and run scanner > """ > for cmd in [" mount /filesystems ", " scanner_start"]: > try: > out, err, ret = run(cmd, timeout=3600) > if ret != 0: > logging.error("Can't run %s got %s (%d)!" % (cmd, err, > ret)) Python 2.6 (why are you using the oldest Python minor version?) introduced string.format(), so you should use that instead of the old string format operator (?%?): logging.error("Can't run {0}; got {1} ({2:d})!".format(cmd, err, ret)) On the other hand, you do not need the format operator to begin with: logging.error("Can't run %s; got %s (%d)!", cmd, err, ret) > return False > except Exception as e: > logging.exception("Failed to run %s got %s" % (cmd, e)) See above. > return False > logging.info("Mount /tmp.....Done !!!") > time.sleep(30) > > > Iam on python 2.6 and Linux , I need you inputs on how to ignore an > specific error when the mount fails (Polite people would *ask* a *question*.) > In general the mount has zero status if it succeeds and anon-zero exit > status if it fails. (?_a non-zero_?, with a space in-between. ?anon? can be misunderstood as an abbreviation for ?anonymous?.) > 1.But for one rare case the mount succeeds but returns anon-zero exit > status and when we get ?Reading GUID from da0xxx: No such file or > directory? error , how to ignore this error and proceed with the above > code If the non-zero exit status is distinguishable from other non-zero statuses, then you just test for that particular status code. Otherwise, you should simply test if the filesystem has been mounted before you proceed. > 2. Also need to add this check only for mount case i.e mount > /filesystems and not scanner_start Most simple solution for this: Do not use a loop. More "complicated" solution: Use an ?if? statement. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Sun Dec 20 16:54:35 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Dec 2015 08:54:35 +1100 Subject: Installing PyCharm on Windows In-Reply-To: <52076a04-4803-4cd5-b86a-65d8fdc81aea@googlegroups.com> References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> <52076a04-4803-4cd5-b86a-65d8fdc81aea@googlegroups.com> Message-ID: On Mon, Dec 21, 2015 at 4:15 AM, Josef Pktd wrote: >> Mine was not a snide remark, but the truth. Those other operating systems I >> was talking about do give users more freedom. For example, the freedom to >> use it on as many different machines as you like without an extra license, >> to see the source code, to modify it, and to redistribute the modification >> including an attribution to yourself. > > "Richtige M?nner nehmen Pitralon" everything else is "unreal" > > I'm writing BSD licensed software, but I never felt the urge to change more than a few options in the operating system, and was never interested in the "freedom" to fix the kernel (and I was never interested in fixing my car either). > That's true of me, too. I run Debian Linux on most of my systems, and for the overwhelming majority of packages, I simply accept the precompiled binary that's available from their repositories, rather than tinkering with it myself. But the mere possibility that someone recompile their own software forces authors and vendors to remain honest; it's pretty useless adding in nagware or ads if anyone can simply compile them out again. Plus, the general culture of GNU, Linux, *BSD, and similar ecosystems means that when you *do* want to compile your own software, it's really easy. Want to run CPython 3.6 on Windows? Go hunt down a compiler, fiddle around with it, and see if you can get everything to work. Want to run CPython 3.6 on a Debian system? It's probably as simple as: $ sudo apt-get build-dep python3 $ sudo apt-get install mercurial $ hg clone https://hg.python.org/cpython $ cd cpython $ make Want to try out that interesting-looking patch off the bug tracker? Same as the above, plus one little 'patch' command to apply the patch. Either way, you end up with the main "python3" command still being the one that Debian provided, and "./python" running the brand new one you just built. (If you *do* want to replace your system-wide Python, that's just one more command; but it's easy to keep them separate until you're done testing.) I'm not going to force anyone to abandon Windows, but freedom does benefit even people who don't directly exercise it, so I would still encourage people to consider a culture of freedom. ChrisA From rosuav at gmail.com Sun Dec 20 16:56:34 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Dec 2015 08:56:34 +1100 Subject: Ignore error with non-zero exit status (was: How to ignore error with anon-zero exit status) In-Reply-To: <3883651.fOIMIIEhYO@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> Message-ID: On Mon, Dec 21, 2015 at 8:22 AM, Thomas 'PointedEars' Lahn wrote: > Python 2.6 (why are you using the oldest Python minor version?) introduced > string.format(), so you should use that instead of the old string format > operator (?%?): > > logging.error("Can't run {0}; got {1} ({2:d})!".format(cmd, err, ret)) > > Percent formatting isn't going away. There's no need to tell people to abandon it in favour of .format(), unless they actually need a feature of .format(). > On the other hand, you do not need the format operator to begin with: > > logging.error("Can't run %s; got %s (%d)!", cmd, err, ret) > > > See? Another good reason to hang onto percent formatting. ChrisA From PointedEars at web.de Sun Dec 20 17:46:50 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 20 Dec 2015 23:46:50 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> Message-ID: <2062582.Z8LLNUJk5W@PointedEars.de> Chris Angelico wrote: > On Mon, Dec 21, 2015 at 8:22 AM, Thomas 'PointedEars' Lahn > wrote: It is supposed to be an attribution *line*, _not_ an attribution novel. Also, the ?(was: ?)? part is to be removed from the Subject header field value to complete the change of subject in a thread. >> Python 2.6 (why are you using the oldest Python minor version?) >> introduced string.format(), so you should use that instead of the old >> string format operator (?%?): >> >> logging.error("Can't run {0}; got {1} ({2:d})!".format(cmd, err, ret)) >> >> > > Percent formatting isn't going away. There's no need to tell people to > abandon it in favour of .format(), unless they actually need a feature > of .format(). ,- | | [?] | This method of string formatting is the new standard in Python 3, and | should be preferred to the % formatting described in in new code. >> On the other hand, you do not need the format operator to begin with: >> >> logging.error("Can't run %s; got %s (%d)!", cmd, err, ret) >> >> > > See? Another good reason to hang onto percent formatting. Your logic is flawed. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From tjreedy at udel.edu Sun Dec 20 17:46:52 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Dec 2015 17:46:52 -0500 Subject: Installing PyCharm on Windows In-Reply-To: References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> <52076a04-4803-4cd5-b86a-65d8fdc81aea@googlegroups.com> Message-ID: On 12/20/2015 4:54 PM, Chris Angelico wrote: > Want to run CPython 3.6 on Windows? > Go hunt down a compiler, fiddle around with it, and see if > you can get everything to work. No, much easier. Essentially the same steps as below after following the instructions in the devguide to get the 2015 compiler. > Want to run CPython 3.6 on a Debian system? It's probably as simple as: > $ sudo apt-get build-dep python3 I think the equivalent step for windows come later. > $ sudo apt-get install mercurial OK, harder, hunt for Windows hg installer, or TortoiseHg if one likes GUIs front ends as I do. Also get svn. > $ hg clone https://hg.python.org/cpython Essentially same. > $ cd cpython cd cpython/pcbuild > $ make external.bat # for dependencies, which is where svn is needed. I forget command line invocation to build python itself. I use Explorer and doubleclick python?.sln and the file association starts Visual Studio.. There is a windows make.bat for doc building. This all works much better than a few years ago. Many thanks for final tweaks to Zach Ware. > Want to try out that interesting-looking patch off the bug tracker? > Same as the above, plus one little 'patch' command to apply the patch. Ditto for Windows. > I'm not going to force anyone to abandon Windows, but freedom does > benefit even people who don't directly exercise it, so I would still > encourage people to consider a culture of freedom. We have free-as-in-beer Python on Windows *because* people were free, in both senses, to develop it on *nix. -- Terry Jan Reedy From rosuav at gmail.com Sun Dec 20 18:04:10 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Dec 2015 10:04:10 +1100 Subject: Installing PyCharm on Windows In-Reply-To: References: <32971984.pfH099DPo1@PointedEars.de> <2632865.Kq7QuO2XSa@PointedEars.de> <52076a04-4803-4cd5-b86a-65d8fdc81aea@googlegroups.com> Message-ID: On Mon, Dec 21, 2015 at 9:46 AM, Terry Reedy wrote: > On 12/20/2015 4:54 PM, Chris Angelico wrote: > >> Want to run CPython 3.6 on Windows? >> Go hunt down a compiler, fiddle around with it, and see if >> >> you can get everything to work. > > > No, much easier. Essentially the same steps as below after > following the instructions in the devguide to get the 2015 compiler. > >> Want to run CPython 3.6 on a Debian system? It's probably as simple as: > > >> $ sudo apt-get build-dep python3 > > > I think the equivalent step for windows come later. > >> $ sudo apt-get install mercurial > > > OK, harder, hunt for Windows hg installer, or TortoiseHg if one likes GUIs > front ends as I do. Also get svn. > >> $ hg clone https://hg.python.org/cpython > > > Essentially same. > >> $ cd cpython > > > cd cpython/pcbuild > >> $ make > > > external.bat # for dependencies, which is where svn is needed. > > I forget command line invocation to build python itself. I use Explorer and > doubleclick python?.sln and the file association starts Visual Studio.. > There is a windows make.bat for doc building. This all works much better > than a few years ago. Many thanks for final tweaks to Zach Ware. Ah, okay. My information is several years old, as that was the last time I tried a build. Glad that's been improved on; although there's still the problem that the Debian steps are virtually the same as for any other project (just hunt down the source control URL for the project - "git clone git://pike-git.lysator.liu.se/pike.git", or "git clone https://github.com/micropython/micropython", etc, and all the other steps are the same), whereas you need to follow a specific Windows CPython guide. Still, that's a gigantic improvement. Thanks for clarifying. >> Want to try out that interesting-looking patch off the bug tracker? >> Same as the above, plus one little 'patch' command to apply the patch. > > > Ditto for Windows. Right. That's part of the CPython openness, rather than the Debian openness, so that part is just as easy on Windows (once you have a build env set up on each platform). >> I'm not going to force anyone to abandon Windows, but freedom does >> benefit even people who don't directly exercise it, so I would still >> encourage people to consider a culture of freedom. > > > We have free-as-in-beer Python on Windows *because* people were free, in > both senses, to develop it on *nix. Exactly, and a strong example. Back when I maintained several Windows systems around the house (a dwindling number over the years, fortunately), I tended to deploy as much cross-platform open source software as I could. Music player? VLC. CD burning? cdrtools. Etc, etc, etc. Partly because it's good software... partly because it's the *same* good software as I'm using on other platforms. And possible only because of that freedom. Sure, I didn't *compile* any of them - I just took binary blobs - but it was still much better to use free software. ChrisA From rosuav at gmail.com Sun Dec 20 18:09:20 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Dec 2015 10:09:20 +1100 Subject: Ignore error with non-zero exit status In-Reply-To: <2062582.Z8LLNUJk5W@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> Message-ID: On Mon, Dec 21, 2015 at 9:46 AM, Thomas 'PointedEars' Lahn wrote: >> Percent formatting isn't going away. There's no need to tell people to >> abandon it in favour of .format(), unless they actually need a feature >> of .format(). > > ,- > | > | [?] > | This method of string formatting is the new standard in Python 3, and > | should be preferred to the % formatting described in | Operations> in new code. That text doesn't exist in the 3.x documentation: https://docs.python.org/3/library/stdtypes.html#str.format There's a somewhat weaker recommendation here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting But it's been clearly stated that .format is not going to do away with percent formatting, and all language of "new-style formatting" has been removed so as not to cause confusion. ChrisA From rxjwg98 at gmail.com Sun Dec 20 20:33:01 2015 From: rxjwg98 at gmail.com (Robert) Date: Sun, 20 Dec 2015 17:33:01 -0800 (PST) Subject: Can I call a pymc-function directly? Message-ID: Hi, I am new to pymc package. I come across the following tutorial: The example is from: www.map.ox.ac.uk/media/PDF/Patil_et_al_2010.pdf ......... import pymc import numpy as np n = 5*np.ones(4,dtype=int) x = np.array([-.86,-.3,-.05,.73]) alpha = pymc.Normal('alpha',mu=0,tau=.01) beta = pymc.Normal('beta',mu=0,tau=.01) @pymc.deterministic def theta(a=alpha, b=beta): """theta = logit^{-1}(a+b)""" return pymc.invlogit(a+b*x) d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\ observed=True) ....... import pymc import pymc.Matplot import mymodel S = pymc.MCMC(mymodel, db='pickle') S.sample(iter=10000, burn=5000, thin=2) pymc.Matplot.plot(S) import matplotlib.pyplot as plt plt.show() /////// Through the above code runs and plots, I would like to know more detail about function theta. I have tried the following modified code: import pymc import numpy as np n = 5*np.ones(4,dtype=int) x = np.array([-.86,-.3,-.05,.73]) alpha = pymc.Normal('alpha',mu=0,tau=.01) beta = pymc.Normal('beta',mu=0,tau=.01) @pymc.deterministic def theta(a=alpha, b=beta): """theta = logit^{-1}(a+b)""" return pymc.invlogit(a+b*x) p=theta(alpha, beta) print 'p=', p ////////////// It has this error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) C:\Users\rj\pyprj\pymc_mymodel0.py in () 13 return pymc.invlogit(a+b*x) 14 ---> 15 p=theta(alpha, beta) 16 print 'p=', p C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\CommonDeterministics.pyc in __call__(self, *args, **kwargs) 989 {'self': self, 'args': args, 'kwargs': kwargs}, 990 trace=False, --> 991 plot=False) 992 Variable.__call__ = UnboundMethodType(__call__, None, Variable) 993 C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\PyMCObjects.pyc in __init__(self, eval, doc, name, parents, dtype, trace, cache_depth, plot, verbose, jacobians, jacobian_formats) 441 trace=trace, 442 plot=plot, --> 443 verbose=verbose) 444 445 # self._value.force_compute() C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Node.pyc in __init__(self, doc, name, parents, cache_depth, trace, dtype, plot, verbose) 212 self.extended_children = set() 213 --> 214 Node.__init__(self, doc, name, parents, cache_depth, verbose=verbose) 215 216 if self.dtype is None: C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Node.pyc in __init__(self, doc, name, parents, cache_depth, verbose) 127 128 # Initialize --> 129 self.parents = parents 130 131 def _get_parents(self): C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Node.pyc in _set_parents(self, new_parents) 145 146 # Get new lazy function --> 147 self.gen_lazy_function() 148 149 parents = property( C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\PyMCObjects.pyc in gen_lazy_function(self) 452 cache_depth=self._cache_depth) 453 --> 454 self._value.force_compute() 455 456 self._jacobians = {} C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\LazyFunction.pyd in pymc.LazyFunction.LazyFunction.force_compute (pymc\LazyFunction.c:2409)() C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\CommonDeterministics.pyc in eval_fun(self, args, kwargs) 981 982 def eval_fun(self, args=args, kwargs=kwargs): --> 983 return self(*args, **kwargs) 984 return pm.Deterministic(eval_fun, 985 'A Deterministic returning the value of %s(*%s, **%s)' % ( TypeError: 'numpy.ndarray' object is not callable /////////////// >From function syntactically, it seems OK for this function calling(random variables alpha and beta as parameters of theta. p=theta(alpha, beta) Do you know what is wrong with my code and idea (call theta by my code, not a random model like: d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\ observed=True) Thanks, From ganesh1pal at gmail.com Sun Dec 20 21:52:22 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Mon, 21 Dec 2015 08:22:22 +0530 Subject: Ignore error with non-zero exit status (was: How to ignore error with anon-zero exit status) In-Reply-To: <3883651.fOIMIIEhYO@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> Message-ID: > (Polite people would *ask* a *question*.) I am a polite person , sorry if the wording was harsh. > (?_a non-zero_?, with a space in-between. ?anon? can be misunderstood as an > abbreviation for ?anonymous?.) It was a typo. > Most simple solution for this: Do not use a loop. More "complicated" > solution: Use an ?if? statement. I want to stick on to loop and try modifying the code with if. Should I use some comparison operation with if ? From steve at pearwood.info Sun Dec 20 22:01:48 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Dec 2015 14:01:48 +1100 Subject: Catogorising strings into random versus non-random Message-ID: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> I have a large number of strings (originally file names) which tend to fall into two groups. Some are human-meaningful, but not necessarily dictionary words e.g.: baby lions at play saturday_morning12 Fukushima ImpossibleFork (note that some use underscores, others spaces, and some CamelCase) while others are completely meaningless (or mostly so): xy39mGWbosjY 9sjz7s8198ghwt rz4sdko-28dbRW00u Let's call the second group "random" and the first "non-random", without getting bogged down into arguments about whether they are really random or not. I wish to process the strings and automatically determine whether each string is random or not. I need to split the strings into three groups: - those that I'm confident are random - those that I'm unsure about - those that I'm confident are non-random Ideally, I'll get some sort of numeric score so I can tweak where the boundaries fall. Strings are *mostly* ASCII but may include a few non-ASCII characters. Note that false positives (detecting a meaningful non-random string as random) is worse for me than false negatives (miscategorising a random string as non-random). Does anyone have any suggestions for how to do this? Preferably something already existing. I have some thoughts and/or questions: - I think nltk has a "language detection" function, would that be suitable? - If not nltk, are there are suitable language detection libraries? - Is this the sort of problem that neural networks are good at solving? Anyone know a really good tutorial for neural networks in Python? - How about Bayesian filters, e.g. SpamBayes? -- Steven From ben+python at benfinney.id.au Sun Dec 20 22:45:31 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Dec 2015 14:45:31 +1100 Subject: Categorising strings on =?utf-8?Q?meaningful=E2=80=93meaningless?= spectrum (was: Catogorising strings into random versus non-random) References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85vb7s1n38.fsf@benfinney.id.au> Steven D'Aprano writes: > Let's call the second group "random" and the first "non-random", > without getting bogged down into arguments about whether they are > really random or not. I think we should discuss it, even at risk of getting bogged down. As you know better than I, ?random? is not an observable property of the value, but of the process that produced it. So, I don't think ?random? is at all helpful as a descriptor of the criteria you need for discriminating these values. Can you give a better definition of what criteria distinguish the values, based only on their observable properties? You used ?meaningless?; that seems at least more hopeful as a criterion we can use by examining text values. So, what counts as meaningless? > I wish to process the strings and automatically determine whether each > string is random or not. I need to split the strings into three groups: > > - those that I'm confident are random > - those that I'm unsure about > - those that I'm confident are non-random > > Ideally, I'll get some sort of numeric score so I can tweak where the > boundaries fall. Perhaps you could measure Shannon entropy (?expected information value?) as a proxy? Or maybe I don't quite understand the criteria. -- \ ?Actually I made up the term ?object-oriented?, and I can tell | `\ you I did not have C++ in mind.? ?Alan Kay, creator of | _o__) Smalltalk, at OOPSLA 1997 | Ben Finney From eryksun at gmail.com Sun Dec 20 23:04:24 2015 From: eryksun at gmail.com (eryk sun) Date: Sun, 20 Dec 2015 22:04:24 -0600 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: On Sun, Dec 20, 2015 at 10:21 AM, Dennis Lee Bieber wrote: > On Sun, 20 Dec 2015 12:25:30 +0100, "Skybuck Flying" > declaimed the following: >> >>This does make me wonder how Windows 7 terminates threads/processes/hanging >>applications. >> >>Apperently there is some kind of mechanism for this. >> > And if you've done it you'll have seen warnings about possible data > corruption or further misbehavior of the system. The Windows mechanism for queueing a routine to run on another thread is an NT asynchronous procedure call (APC). Here's an old article about NT APCs (Almeida, 2002): http://www.drdobbs.com/184416590 APCs are typically used by kernel-mode code in the I/O system and drivers. A user-mode APC can also be queued to a thread using QueueUserAPC, but it only executes "with permission" when the thread either calls ntdll!NtTestAlert or enters an alertable wait. TerminateThread calls the system function NtTerminateThread, which queues an APC to the thread to call the process manager private function nt!PspExitThread. The thread rundown procedure is briefly as follows: * Notify driver callbacks registered via PsSetCreateThreadNotifyRoutine. * If it's the last thread in the process, wait for all other threads to finish exiting. * Message any debug or termination port. * Run down the Win32 extended thread. * Cancel outstanding I/O operations, timers, and registry notifications. * Run down the kernel thread. * Delete the thread environment block (TEB). * Run down the LPC message stack. * Set the thread ExitStatus and ExitTime. * If it's the last thread in the process, close out the process handle table and section object. * Run down pending APCs. * Queue the thread to be reaped. ExitThread (i.e. ntdll!RtlExitUserThread) calls the loader function ntdll!LdrShutdownThread. This gives all interested DLL entrypoints and TLS initializers an opportunity to do required bookkeeping and resource management for the detaching thread. Then RtlExitUserThread calls NtTerminateThread to let the executive handle the rest. CPython calls the C runtime's _endthreadex, which is recommended in place of calling ExitThread directly, especially if the CRT is linked statically instead of as a DLL. > In both cases the preferred method is for the process/thread ITSELF to call > Exit(Process|Thread) in response to some other signal that it reads. Yes, in C/C++ code. In Python code just return or raise SystemExit to let the interpreter do this for you. Calling either ExitThread or _endthreadex directly is a bad idea. Python's DllMain doesn't handle a DLL_THREAD_DETACH when _endthreadex or ExitThread is called. Thus if you pull the rug out from under the thread, the thread's tstate lock is never released and the interpreter will hang at exit if it isn't a daemon thread. From rosuav at gmail.com Sun Dec 20 23:22:39 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Dec 2015 15:22:39 +1100 Subject: Catogorising strings into random versus non-random In-Reply-To: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Dec 21, 2015 at 2:01 PM, Steven D'Aprano wrote: > I have a large number of strings (originally file names) which tend to fall > into two groups. Some are human-meaningful, but not necessarily dictionary > words e.g.: > > > baby lions at play > saturday_morning12 > Fukushima > ImpossibleFork > > > (note that some use underscores, others spaces, and some CamelCase) while > others are completely meaningless (or mostly so): > > > xy39mGWbosjY > 9sjz7s8198ghwt > rz4sdko-28dbRW00u > > I need to split the strings into three groups: > > - those that I'm confident are random > - those that I'm unsure about > - those that I'm confident are non-random > > Ideally, I'll get some sort of numeric score so I can tweak where the > boundaries fall. The first thing that comes to my mind is poking the string into a search engine and seeing how many results come back. You might need to do some preprocessing to recognize multi-word forms (maybe a handful of recognized cases like snake_case, CamelCase, CamelCasewiththeLittleWordsLeftUnchanged, etc), but doing that manually on the above text gives me: * baby lions at play * saturday morning 12 * fukushima * impossible fork * xy 39 mgwbosjy * 9 sjz 7 s 8198 ghwt * rz 4 sdko 28 dbrw 00 u Putting those into Google without quotes yields: * About 23,800,000 results * About 227,000,000 results * About 32,500,000 results * About 16,400,000 results * About 1,180 results * 7 results * About 30,300 results DuckDuckGo doesn't give a result count, so I skipped it. Yahoo search yielded: * 6,040,000 results * 123,000,000 results * 3,920,000 results * 720,000 results * No results at all * No results at all * 2 results Bing produces much more chaotic results, though: * 34,000,000 RESULTS * 15,600,000 RESULTS * 11,000,000 RESULTS * 1,620,000 RESULTS * 5,720,000 RESULTS * 1,580,000,000 RESULTS * 3,380,000 RESULTS This suggests that search engine results MAY be useful, but in some cases, tweaks may be necessary (I couldn't force Bing to do phrase search, for some reason probably related to my inexperience with it), and also that the boundary between "meaningful" and "non-meaningful" will depend on the engine used (I'd use 1,000,000 as the boundary with Google, but probably 100,000 with Yahoo). You might want to handle numerics differently, too - converting "9" into "nine" could improve the result reliability. How many of these keywords would you be looking up, and would a network transaction (a search engine API call) for each one be too expensive? ChrisA From larry at hastings.org Mon Dec 21 01:36:46 2015 From: larry at hastings.org (Larry Hastings) Date: Sun, 20 Dec 2015 22:36:46 -0800 Subject: [RELEASED] Python 3.4.4 is now available Message-ID: <56779DFE.9040709@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.4. Python 3.4.4 is the last version of Python 3.4.4 with binary installers, and the end of "bugfix" support. After this release, Python 3.4.4 moves into "security fixes only" mode, and future releases will be source-code-only. You can see what's changed in Python 3.4.4 (as compared to previous versions of 3.4) here: https://docs.python.org/3.4/whatsnew/changelog.html#python-3-4-4 And you can download Python 3.4.4 here: https://www.python.org/downloads/release/python-344/ Windows and Mac users: please read the important platform-specific "Notes on this release" section near the end of that page. One final note. 3.4.4 final marks the end of an era: it contains the last Windows installers that will be built by Martin von Loewis. Martin has been the Windows release "Platform Expert" since the Python 2.4 release cycle started more than twelve years ago--in other words, for more than half of Python's entire existence! On behalf of the Python community, and particularly on behalf of the Python release managers, I'd like to thank Martin for his years of service to the community, and for the care and professionalism he brought to his role. It was a pleasure working with him, and we wish him the very best in his future projects. We hope you enjoy Python 3.4.4! Happy holidays, //arry/ From PointedEars at web.de Mon Dec 21 02:51:09 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 08:51:09 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> Message-ID: <2721557.Hpeo4xmTem@PointedEars.de> Chris Angelico wrote: > On Mon, Dec 21, 2015 at 9:46 AM, Thomas 'PointedEars' Lahn > wrote: >>> Percent formatting isn't going away. There's no need to tell people to >>> abandon it in favour of .format(), unless they actually need a feature >>> of .format(). >> >> ,- >> | >> | [?] >> | This method of string formatting is the new standard in Python 3, and >> | should be preferred to the % formatting described in > | Operations> in new code. > > That text doesn't exist in the 3.x documentation: > > https://docs.python.org/3/library/stdtypes.html#str.format Of course it does not. That would be stupid. > There's a somewhat weaker recommendation here: > > https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting AISB. > But it's been clearly stated that .format is not going to do away with > percent formatting, and all language of "new-style formatting" has been > removed so as not to cause confusion. Wishful thinking, twice. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Mon Dec 21 02:54:15 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 08:54:15 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> Message-ID: <38180823.07PURaZOhP@PointedEars.de> Ganesh Pal wrote: [repaired Subject, restored attribution] > Thomas 'PointedEars' Lahn wrote: >> Most simple solution for this: Do not use a loop. More "complicated" >> solution: Use an ?if? statement. > > I want to stick on to loop and try modifying the code with if. Should I > use some comparison operation with if ? Yes. Please see, again, -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From __peter__ at web.de Mon Dec 21 03:24:24 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Dec 2015 09:24:24 +0100 Subject: Catogorising strings into random versus non-random References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a large number of strings (originally file names) which tend to > fall into two groups. Some are human-meaningful, but not necessarily > dictionary words e.g.: > > > baby lions at play > saturday_morning12 > Fukushima > ImpossibleFork > > > (note that some use underscores, others spaces, and some CamelCase) while > others are completely meaningless (or mostly so): > > > xy39mGWbosjY > 9sjz7s8198ghwt > rz4sdko-28dbRW00u > > > Let's call the second group "random" and the first "non-random", without > getting bogged down into arguments about whether they are really random or > not. I wish to process the strings and automatically determine whether > each string is random or not. I need to split the strings into three > groups: > > - those that I'm confident are random > - those that I'm unsure about > - those that I'm confident are non-random > > Ideally, I'll get some sort of numeric score so I can tweak where the > boundaries fall. > > Strings are *mostly* ASCII but may include a few non-ASCII characters. > > Note that false positives (detecting a meaningful non-random string as > random) is worse for me than false negatives (miscategorising a random > string as non-random). > > Does anyone have any suggestions for how to do this? Preferably something > already existing. I have some thoughts and/or questions: > > - I think nltk has a "language detection" function, would that be > suitable? > > - If not nltk, are there are suitable language detection libraries? > > - Is this the sort of problem that neural networks are good at solving? > Anyone know a really good tutorial for neural networks in Python? > > - How about Bayesian filters, e.g. SpamBayes? A dead simple approach -- look at the pairs in real words and calculate the ratio pairs-also-found-in-real-words/num-pairs $ cat score.py import sys WORDLIST = "/usr/share/dict/words" SAMPLE = """\ baby lions at play saturday_morning12 Fukushima ImpossibleFork xy39mGWbosjY 9sjz7s8198ghwt rz4sdko-28dbRW00u """.splitlines() def extract_pairs(text): for i in range(len(text)-1): yield text[i:i+2] def load_pairs(): pairs = set() with open(WORDLIST) as f: for line in f: pairs.update(extract_pairs(line.strip())) return pairs def get_score(text, popular_pairs): m = 0 for i, p in enumerate(extract_pairs(text), 1): if p in popular_pairs: m += 1 return m/i def main(): popular_pairs = load_pairs() for text in sys.argv[1:] or SAMPLE: score = get_score(text, popular_pairs) print("%4.2f %s" % (score, text)) if __name__ == "__main__": main() $ python3 score.py 0.65 baby lions at play 0.76 saturday_morning12 1.00 Fukushima 0.92 ImpossibleFork 0.36 xy39mGWbosjY 0.31 9sjz7s8198ghwt 0.31 rz4sdko-28dbRW00u However: $ python3 -c 'import random, sys; a = list(sys.argv[1]); random.shuffle(a); print("".join(a))' 'baby lions at play' bnsip atl ayba loy $ python3 score.py 'bnsip atl ayba loy' 0.65 bnsip atl ayba loy From steve+comp.lang.python at pearwood.info Mon Dec 21 03:47:43 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 21 Dec 2015 19:47:43 +1100 Subject: Categorising strings on =?UTF-8?B?bWVhbmluZ2Z1bOKAk21lYW5pbmdsZXNz?= spectrum (was: Catogorising strings into random versus non-random) References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5677bcb2$0$2890$c3e8da3$76491128@news.astraweb.com> On Monday 21 December 2015 14:45, Ben Finney wrote: > Steven D'Aprano writes: > >> Let's call the second group "random" and the first "non-random", >> without getting bogged down into arguments about whether they are >> really random or not. > > I think we should discuss it, even at risk of getting bogged down. As > you know better than I, ?random? is not an observable property of the > value, but of the process that produced it. > > So, I don't think ?random? is at all helpful as a descriptor of the > criteria you need for discriminating these values. > > Can you give a better definition of what criteria distinguish the > values, based only on their observable properties? No, not really. This *literally* is a case of "I'll know it when I see it", which suggests that some sort of machine-learning solution (neural network?) may be useful. I can train it on a bunch of strings which I can hand- classify, and let the machine pick out the correlations, then apply it to the rest of the strings. The best I can say is that the "non-random" strings either are, or consist of, mostly English words, names, or things which look like they might be English words, containing no more than a few non-ASCII characters, punctuation, or digits. > You used ?meaningless?; that seems at least more hopeful as a criterion > we can use by examining text values. So, what counts as meaningless? Strings made up of random-looking sequences of characters, like you often see on sites like imgur or tumblr. Characters from non-Latin character sets that I can't read (e.g. Japanese, Korean, Arabic, etc). Jumbled up words, e.g. "python" is non-random, "nyohtp" would be random. [...] > Perhaps you could measure Shannon entropy (?expected information value?) > as > a proxy? Or maybe I don't quite understand the criteria. That's a possibility. At least, it might be able to distinguish some strings, although if I understand correctly, the two strings "python" and "nhoypt" have identical entropy, so this alone won't be sufficient. -- Steve From steve+comp.lang.python at pearwood.info Mon Dec 21 03:57:36 2015 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 21 Dec 2015 19:57:36 +1100 Subject: Catogorising strings into random versus non-random References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5677bf02$0$1530$c3e8da3$5496439d@news.astraweb.com> On Monday 21 December 2015 15:22, Chris Angelico wrote: > On Mon, Dec 21, 2015 at 2:01 PM, Steven D'Aprano > wrote: >> I have a large number of strings (originally file names) which tend to >> fall into two groups. Some are human-meaningful, but not necessarily >> dictionary words e.g.: [...] > The first thing that comes to my mind is poking the string into a > search engine and seeing how many results come back. You might need to > do some preprocessing to recognize multi-word forms (maybe a handful > of recognized cases like snake_case, CamelCase, > CamelCasewiththeLittleWordsLeftUnchanged, etc), I could possibly split the string into "words", based on CamelCase, spaces, hyphens or underscores. That would cover most of the cases. > How many of these keywords would you be looking up, and would a > network transaction (a search engine API call) for each one be too > expensive? Tens or hundreds of thousands of strings, and yes a network transaction probably would be a bit much. I'd rather not have Google or Bing be a dependency :-) -- Steve From animsri13 at gmail.com Mon Dec 21 04:08:09 2015 From: animsri13 at gmail.com (Animesh Srivastava) Date: Mon, 21 Dec 2015 14:38:09 +0530 Subject: No subject Message-ID: While installin python3.5.1 i m getting 0xc000007b error Please reslove it From auriocus at gmx.de Mon Dec 21 04:56:24 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Mon, 21 Dec 2015 10:56:24 +0100 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 21.12.15 um 09:24 schrieb Peter Otten: > Steven D'Aprano wrote: > >> I have a large number of strings (originally file names) which tend to >> fall into two groups. Some are human-meaningful, but not necessarily >> dictionary words e.g.: >> >> >> baby lions at play >> saturday_morning12 >> Fukushima >> ImpossibleFork >> >> >> (note that some use underscores, others spaces, and some CamelCase) while >> others are completely meaningless (or mostly so): >> >> >> xy39mGWbosjY >> 9sjz7s8198ghwt >> rz4sdko-28dbRW00u >> >> >> Let's call the second group "random" and the first "non-random", without >> getting bogged down into arguments about whether they are really random or >> not. I wish to process the strings and automatically determine whether >> each string is random or not. I need to split the strings into three >> groups: >> >> - those that I'm confident are random >> - those that I'm unsure about >> - those that I'm confident are non-random >> >> Ideally, I'll get some sort of numeric score so I can tweak where the >> boundaries fall. >> >> Strings are *mostly* ASCII but may include a few non-ASCII characters. >> >> Note that false positives (detecting a meaningful non-random string as >> random) is worse for me than false negatives (miscategorising a random >> string as non-random). >> >> Does anyone have any suggestions for how to do this? Preferably something >> already existing. I have some thoughts and/or questions: >> >> - I think nltk has a "language detection" function, would that be >> suitable? >> >> - If not nltk, are there are suitable language detection libraries? >> >> - Is this the sort of problem that neural networks are good at solving? >> Anyone know a really good tutorial for neural networks in Python? >> >> - How about Bayesian filters, e.g. SpamBayes? > > A dead simple approach -- look at the pairs in real words and calculate the > ratio > > pairs-also-found-in-real-words/num-pairs Sounds reasonable. Building on this approach, two simple improvements: - calculate the log-likelihood instead, which also makes use of the frequency of the digraphs in the training set - Use trigraphs instead of digraphs - preprocess the string (lowercase), but more sophisticated preprocessing could be an option (i.e. converting under_scores and CamelCase to spaces) The main reason for the low score of the baby lions is the space character, I think - the word list does not contain that much spaces. Maybe one should feed in some long wikipedia article to calculate the digraph/trigraph probabilities ===================================== Apfelkiste:Tests chris$ cat score_my.py from __future__ import division from collections import Counter, defaultdict from math import log import sys WORDLIST = "/usr/share/dict/words" SAMPLE = """\ baby lions at play saturday_morning12 Fukushima ImpossibleFork xy39mGWbosjY 9sjz7s8198ghwt rz4sdko-28dbRW00u """.splitlines() def extract_pairs(text): for i in range(len(text)-1): yield text.lower()[i:i+2] # or len(text)-2 and i:i+3 def load_pairs(): pairs = Counter() with open(WORDLIST) as f: for line in f: pairs.update(extract_pairs(line.strip())) # normalize to sum total_count = sum([pairs[x] for x in pairs]) N = total_count+len(pairs) dist = defaultdict(lambda:1/N, ((x, (pairs[x]+1)/N) for x in pairs)) return dist def get_score(text, dist): ll = 0 for i, x in enumerate(extract_pairs(text), 1): ll += log(dist[x]) return ll / i def main(): pair_dist = load_pairs() for text in sys.argv[1:] or SAMPLE: score = get_score(text, pair_dist) print("%.3g %s" % (score, text)) if __name__ == "__main__": main() Apfelkiste:Tests chris$ python score_my.py -8.74 baby lions at play -7.63 saturday_morning12 -6.38 Fukushima -5.72 ImpossibleFork -10.6 xy39mGWbosjY -12.9 9sjz7s8198ghwt -12.1 rz4sdko-28dbRW00u Apfelkiste:Tests chris$ python score_my.py 'bnsip atl ayba loy' -9.43 bnsip atl ayba loy Apfelkiste:Tests chris$ and using trigraphs: Apfelkiste:Tests chris$ python score_my.py 'bnsip atl ayba loy' -12.5 bnsip atl ayba loy Apfelkiste:Tests chris$ python score_my.py -11.5 baby lions at play -9.88 saturday_morning12 -9.85 Fukushima -7.68 ImpossibleFork -13.4 xy39mGWbosjY -14.2 9sjz7s8198ghwt -14.2 rz4sdko-28dbRW00u ============================== From rakeshravinlr at gmail.com Mon Dec 21 05:33:19 2015 From: rakeshravinlr at gmail.com (rakeshravinlr at gmail.com) Date: Mon, 21 Dec 2015 02:33:19 -0800 (PST) Subject: Python 3.1 test issue In-Reply-To: References: Message-ID: <19e7d857-abc7-47df-a97b-3969a0dedb72@googlegroups.com> On Wednesday, December 16, 2015 at 11:53:14 PM UTC+5:30, George Trojan wrote: > I installed Python 3.1 on RHEL 7.2. The command make test hangs (or > takes a lot of time) on test_subprocess. > > [396/397] test_subprocess > ^C > Test suite interrupted by signal SIGINT. > 5 tests omitted: > test___all__ test_distutils test_site test_socket test_warnings > 381 tests OK. > 4 tests altered the execution environment: > test___all__ test_distutils test_site test_warnings > 11 tests skipped: > test_devpoll test_kqueue test_msilib test_ossaudiodev > test_startfile test_tix test_tk test_ttk_guionly test_winreg > test_winsound test_zipfile64 > make: *** [test] Error 1 > > CPU was at 100% all the time for process > > gtrojan 15758 8907 94 17:29 pts/6 00:06:47 > /home/gtrojan/Downloads/Python-3.5.1/python -R -bb -E -Wdefault > -Werror::BytesWarning -X faulthandler -m test.regrtest --slaveargs > [["test_socket", 0, false], {"huntrleaks": false, "match_tests": null, > "failfast": false, "output_on_failure": false, "use_resources": > ["curses", "network", "decimal", "cpu", "subprocess", "urlfetch"], > "pgo": false, "timeout": null}] > gtrojan 22889 336 0 17:36 pts/11 00:00:00 grep --color=auto 15758 > > Is this a problem? > > George can u help me to convert the folowing test case Input: /home/rebaca/azuki/streams/./tsudpsend /home/rebaca/azuki/streams/ebp/ebp-1250-2.ts 127.0.0.1 500011 2151832|/home/rebaca/azuki/streams/./tsudpsend /home/rebaca/azuki/streams/ebp/ebp-1251-2.ts 127.0.0.1 500012 2151832|/home/rebaca/azuki/streams/./tsudpsend /home/rebaca/azuki/streams/ebp/ebp-1250-2.ts 127.0.0.1 500013 2151832 Output: AZ_HLS_PORT_BASED_VOD_TC6_STL_CMD='{ "TSUDPSEND":[ { "ebp_1250_2_av":"tsudpsend '+ STREAMS_PATH +'/ebp/ebp-1250-2.ts '+ DEVICE_UNDER_TEST +'5000112151832" }, { "ebp_1250_2_v": "tsudpsend '+ STREAMS_PATH+'/ebp/ebp-1250-2.ts '+ DEVICE_UNDER_TEST +' 500012 2151832" },{"ebp_1250_2_a": "tsudpsend '+ STREAMS_PATH +'/ebp/ebp-1250-2.ts '+DEVICE_UNDER_TEST +' 500013 2151832" } ] }' how to get output in the following format when the input is given using python # The following are commands used for pumping the streams. "/home/rebaca/azuki/streams/./tsudpsend"==> this is the path of the tool used for pumping streams. # "/home/rebaca/azuki/streams/ebp/ebp-1250-2.ts" ==> Stream Path # "127.0.0.1" & "500011" ==> Device IP & Port, respectively, to which the stream needs to be pumped. # "2151832" ==> Overall Bitrate of the input stream. please help me if u can From steve at pearwood.info Mon Dec 21 05:36:28 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Dec 2015 21:36:28 +1100 Subject: Catogorising strings into random versus non-random References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5677d62e$0$1605$c3e8da3$5496439d@news.astraweb.com> On Mon, 21 Dec 2015 08:56 pm, Christian Gollwitzer wrote: > Apfelkiste:Tests chris$ python score_my.py > -8.74 baby lions at play > -7.63 saturday_morning12 > -6.38 Fukushima > -5.72 ImpossibleFork > -10.6 xy39mGWbosjY > -12.9 9sjz7s8198ghwt > -12.1 rz4sdko-28dbRW00u > Apfelkiste:Tests chris$ python score_my.py 'bnsip atl ayba loy' > -9.43 bnsip atl ayba loy Thanks Christian and Peter for the suggestion, I'll certainly investigate this further. But the scoring doesn't seem very good. "baby lions at play" is 100% English words, and ought to have a radically different score from (say) xy39mGWbosjY which is extremely non-English like. (How many English words do you know of with W, X, two Y, and J?) And yet they are only two units apart. "baby lions..." is a score almost as negative as the authentic gibberish, while Fukushima (a Japanese word) has a much less negative score. Using trigraphs doesn't change that: > -11.5 baby lions at play > -9.85 Fukushima > -13.4 xy39mGWbosjY So this test appears to find that English-like words are nearly as "random" as actual random strings. But it's certainly worth looking into. -- Steven From auriocus at gmx.de Mon Dec 21 05:53:12 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Mon, 21 Dec 2015 11:53:12 +0100 Subject: Catogorising strings into random versus non-random In-Reply-To: <5677d62e$0$1605$c3e8da3$5496439d@news.astraweb.com> References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> <5677d62e$0$1605$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 21.12.15 um 11:36 schrieb Steven D'Aprano: > On Mon, 21 Dec 2015 08:56 pm, Christian Gollwitzer wrote: > >> Apfelkiste:Tests chris$ python score_my.py >> -8.74 baby lions at play >> -7.63 saturday_morning12 >> -6.38 Fukushima >> -5.72 ImpossibleFork >> -10.6 xy39mGWbosjY >> -12.9 9sjz7s8198ghwt >> -12.1 rz4sdko-28dbRW00u >> Apfelkiste:Tests chris$ python score_my.py 'bnsip atl ayba loy' >> -9.43 bnsip atl ayba loy > > Thanks Christian and Peter for the suggestion, I'll certainly investigate > this further. > > But the scoring doesn't seem very good. "baby lions at play" is 100% English > words, and ought to have a radically different score from (say) > xy39mGWbosjY which is extremely non-English like. (How many English words > do you know of with W, X, two Y, and J?) And yet they are only two units > apart. "baby lions..." is a score almost as negative as the authentic > gibberish, while Fukushima (a Japanese word) has a much less negative > score. It is the spaces, which do not occur in the training wordlist (I mentioned that above, maybe not prominently enough). /usr/share/dict/words contains one word per line. The underscore _ is probably putting the saturday morning low, while the spaces put the babies low. Using trigraphs: Apfelkiste:Tests chris$ python score_my.py -11.5 baby lions at play -9.88 saturday_morning12 -9.85 Fukushima -7.68 ImpossibleFork -13.4 xy39mGWbosjY -14.2 9sjz7s8198ghwt -14.2 rz4sdko-28dbRW00u Apfelkiste:Tests chris$ python score_my.py 'babylionsatplay' -8.74 babylionsatplay Apfelkiste:Tests chris$ python score_my.py 'saturdaymorning12' -8.93 saturdaymorning12 Apfelkiste:Tests chris$ So for the spaces, either use a proper trainig material (some long corpus from Wikipedia or such), with punctuation removed. Then it will catch the correct probabilities at word boundaries. Or preprocess by removing the spaces. Christian From auriocus at gmx.de Mon Dec 21 05:56:05 2015 From: auriocus at gmx.de (Christian Gollwitzer) Date: Mon, 21 Dec 2015 11:56:05 +0100 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> <5677d62e$0$1605$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 21.12.15 um 11:53 schrieb Christian Gollwitzer: > So for the spaces, either use a proper trainig material (some long > corpus from Wikipedia or such), with punctuation removed. Then it will > catch the correct probabilities at word boundaries. Or preprocess by > removing the spaces. > > Christian PS: The real log-likelihood would become -infinity, when some pair does not appear at all in the training set (esp. the numbers, e.g.). I used the 1/total in the defaultdict to mitigate that. You could tweak that value a bit. The larger the corpus, the sharper it will divide by itself, too. Christian From jon+usenet at unequivocal.co.uk Mon Dec 21 07:07:29 2015 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 21 Dec 2015 12:07:29 -0000 (UTC) Subject: return from function References: Message-ID: On 2015-12-20, Emil Natan wrote: > I have the following function to find the parent for domain. It removes the > left most label from the name and then checks if SOA record exists for the > reminder, if not it calls itself recursively removing another label and > checking again for SOA record. It works well for 'co.uk' and 'amazon.co.uk' > for example. It does not return the expected value 'uk' when invoked for ' > amazon1.co1.uk', though the print command before the return prints what is > expected. Can someone explain why? Thanks. You probably want to look at this: https://publicsuffix.org/ > except dns.resolver.NXDOMAIN: > print('NXDOMAIN: invoke find_parent_domain recursively') > find_parent_domain(parent_domain) return find_parent_domain(parent_domain) > except dns.resolver.NoAnswer: > print('NoAnswer: invoke find_parent_domain recursively') > find_parent_domain(parent_domain) return find_parent_domain(parent_domain) From skybuck2000 at hotmail.com Mon Dec 21 07:40:21 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Mon, 21 Dec 2015 13:40:21 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: The original idea I posted is less about sending a signal to another processor. It is more about how to break out of an instruction sequence. Example of problem: Main: while Condition1 do begin while Condition2 do begin while Condition3 do begin Routine1 end end; end; Routine1: while Condition4 do begin while Condition5 do begin Routine2: end; end; Routine2: while Condition6 do begin while Condition7 do begin end; end; Breaking out of these kinds of loops, routines, code currently requires something like: Current cumbersome solution for problem: Main: while Condition1 and not Terminated do begin while Condition2 and not Terminated do begin while Condition3 and not Terminated do begin Routine1 end end; end; Routine1: while Condition4 and not Terminated do begin while Condition5 and not Terminated do begin Routine2: end; end; Routine2: while Condition6 and not Terminated do begin while Condition7 and not Terminated do begin end; end; It can take a long while before all this code exits, plus the Terminated boolean is probably placed on wrong side. It should be on the left side in case the Conditions are actual functions otherwise those would unnecessarily be executed as well. Having something that can immediatly exit all of this code would be a nice feature to have. Perhaps something like an exception block, perhaps it could be called a termination block. Routine1: Result = False Execute while True do begin end; Result = True Termination OnTerminate: begin end; end; return Result Preferrably , optionally this can be omitted/left out. Bye, Skybuck. From breamoreboy at yahoo.co.uk Mon Dec 21 07:49:09 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Dec 2015 12:49:09 +0000 Subject: v3.5.1 - msi download In-Reply-To: References: Message-ID: On 19/12/2015 17:45, Renato Emanuel Dysangco wrote: > hello > > is an **.msi* version of your *Python 3.5.1 (32 bit)* in the pipeline soon? > > thanks for your time > msi files are not being made available for 3.5. -- 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 Dec 21 07:58:02 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Dec 2015 12:58:02 +0000 Subject: Ignore error with non-zero exit status In-Reply-To: <2721557.Hpeo4xmTem@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> Message-ID: On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> But it's been clearly stated that .format is not going to do away with >> percent formatting, and all language of "new-style formatting" has been >> removed so as not to cause confusion. > > Wishful thinking, twice. > http://www.gossamer-threads.com/lists/python/dev/969817 -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From PointedEars at web.de Mon Dec 21 08:19:51 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 14:19:51 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> Message-ID: <2726691.rQGQ7FqzaZ@PointedEars.de> Mark Lawrence wrote: > On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >> Chris Angelico wrote: >>> But it's been clearly stated that .format is not going to do away with >>> percent formatting, and all language of "new-style formatting" has been >>> removed so as not to cause confusion. >> >> Wishful thinking, twice. > > http://www.gossamer-threads.com/lists/python/dev/969817 What is this supposed to be evidence of? -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Mon Dec 21 08:23:10 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Dec 2015 00:23:10 +1100 Subject: Ignore error with non-zero exit status In-Reply-To: <2726691.rQGQ7FqzaZ@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> Message-ID: On Tue, Dec 22, 2015 at 12:19 AM, Thomas 'PointedEars' Lahn wrote: > Mark Lawrence wrote: > >> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>> Chris Angelico wrote: >>>> But it's been clearly stated that .format is not going to do away with >>>> percent formatting, and all language of "new-style formatting" has been >>>> removed so as not to cause confusion. >>> >>> Wishful thinking, twice. >> >> http://www.gossamer-threads.com/lists/python/dev/969817 > > What is this supposed to be evidence of? Proof that percent formatting isn't planned for deprecation, much less removal. There is strong support for it in certain quarters of python-dev. It's a fully supported language feature, not an old and outmoded feature that is kept solely for backward compatibility (as "old-style classes" are in Python 2.7 - you can still use them, but as of Python 3, only "new-style classes" exist). ChrisA From vlastimil.brom at gmail.com Mon Dec 21 08:25:28 2015 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 21 Dec 2015 14:25:28 +0100 Subject: Catogorising strings into random versus non-random In-Reply-To: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2015-12-21 4:01 GMT+01:00 Steven D'Aprano : > I have a large number of strings (originally file names) which tend to fall > into two groups. Some are human-meaningful, but not necessarily dictionary > words e.g.: > > > baby lions at play > saturday_morning12 > Fukushima > ImpossibleFork > > > (note that some use underscores, others spaces, and some CamelCase) while > others are completely meaningless (or mostly so): > > > xy39mGWbosjY > 9sjz7s8198ghwt > rz4sdko-28dbRW00u > > > Let's call the second group "random" and the first "non-random", without > getting bogged down into arguments about whether they are really random or > not. I wish to process the strings and automatically determine whether each > string is random or not. I need to split the strings into three groups: > > - those that I'm confident are random > - those that I'm unsure about > - those that I'm confident are non-random > > Ideally, I'll get some sort of numeric score so I can tweak where the > boundaries fall. > > Strings are *mostly* ASCII but may include a few non-ASCII characters. > > Note that false positives (detecting a meaningful non-random string as > random) is worse for me than false negatives (miscategorising a random > string as non-random). > > Does anyone have any suggestions for how to do this? Preferably something > already existing. I have some thoughts and/or questions: > > - I think nltk has a "language detection" function, would that be suitable? > > - If not nltk, are there are suitable language detection libraries? > > - Is this the sort of problem that neural networks are good at solving? > Anyone know a really good tutorial for neural networks in Python? > > - How about Bayesian filters, e.g. SpamBayes? > > > > > -- > Steven > > -- > https://mail.python.org/mailman/listinfo/python-list Hi, as you probably already know, NLTK could be helpful for some parts of this task; if you can handle the most likely "word" splitting involved by underscores, CamelCase etc., you could try to tag the parts of speech of the words and interpret for the results according to your needs. In the online demo http://text-processing.com/demo/tag/ your sample (with different approaches to splitt the words) yields: baby/NN lions/NNS at/IN play/VB saturday/NN morning/NN 12/CD Fukushima/NNP Impossible/JJ Fork/NNP xy39mGWbosjY/-None- 9sjz7s8198ghwt/-None- rz4sdko/-None- -/: 28dbRW00u/-None- or with more splittings on case or letter-digit boundaries: baby/NN lions/NNS at/IN play/VB saturday/NN morning/NN 12/CD Fukushima/NNP Impossible/JJ Fork/NNP xy/-None- 39/CD m/-None- G/NNP Wbosj/-None- Y/-None- 9/CD sjz/-None- 7/CD s/-None- 8198/-NONE- ghwt/-None- rz/-None- 4/CD sdko/-None- -/: 28/CD db/-None- R/NNP W/-None- 00/-None- u/-None- the tagset might be compatible with https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html There is sample code with a comparable output to this demo: http://stackoverflow.com/questions/23953709/how-do-i-tag-a-sentence-with-the-brown-or-conll2000-tagger-chunker For the given minimal sample, the results look useful (maybe with exception of the capitalised words sometimes tagged as proper names - but it might not be that relevant here). Of course, any scoring isn't available with this approach, but you could maybe check the proportion of the recognised "words" comparing to the total number of the "words" for the respective filename. Training the tagger should be possible too in NLTK, but I don't have experiences with this. regards, vbr From vincent at vincentdavis.net Mon Dec 21 08:51:33 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 21 Dec 2015 07:51:33 -0600 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Dec 21, 2015 at 7:25 AM, Vlastimil Brom wrote: > > baby lions at play > > saturday_morning12 > > Fukushima > > ImpossibleFork > > > > > > (note that some use underscores, others spaces, and some CamelCase) while > > others are completely meaningless (or mostly so): > > > > > > xy39mGWbosjY > > 9sjz7s8198ghwt > > rz4sdko-28dbRW00u > My first thought it to search google for each wor ?d? or phase and count ?(google gives a count) ? the results. For example if you search for "xy39mGWbosjY" there is one result as of now, ?which is an archive of this tread. If you search for any given word or even the phrase ?, for example? "baby lions at play ? " you get a much larger set of results ? ~500? . I assue there are many was to search google with python, this looks like one. https://pypi.python.org/pypi/google Vincent Davis From PointedEars at web.de Mon Dec 21 09:05:01 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 15:05:01 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> Message-ID: <2827307.1DEaE21uzt@PointedEars.de> Chris Angelico wrote: > On Tue, Dec 22, 2015 at 12:19 AM, Thomas 'PointedEars' Lahn > wrote: >> Mark Lawrence wrote: >>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>> Chris Angelico wrote: >>>>> But it's been clearly stated that .format is not going to do away with >>>>> percent formatting, and all language of "new-style formatting" has >>>>> been removed so as not to cause confusion. >>>> Wishful thinking, twice. >>> http://www.gossamer-threads.com/lists/python/dev/969817 >> What is this supposed to be evidence of? > > Proof that percent formatting isn't planned for deprecation, much less > removal. Then it would have failed to accomplish that. > There is strong support for it in certain quarters of python-dev. [?] There *was*. The referred thread is from 2012-02. It is 2015-12. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Mon Dec 21 09:11:34 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Dec 2015 01:11:34 +1100 Subject: Ignore error with non-zero exit status In-Reply-To: <2827307.1DEaE21uzt@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: On Tue, Dec 22, 2015 at 1:05 AM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> On Tue, Dec 22, 2015 at 12:19 AM, Thomas 'PointedEars' Lahn >> wrote: >>> Mark Lawrence wrote: >>>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>>> Chris Angelico wrote: >>>>>> But it's been clearly stated that .format is not going to do away with >>>>>> percent formatting, and all language of "new-style formatting" has >>>>>> been removed so as not to cause confusion. >>>>> Wishful thinking, twice. >>>> http://www.gossamer-threads.com/lists/python/dev/969817 >>> What is this supposed to be evidence of? >> >> Proof that percent formatting isn't planned for deprecation, much less >> removal. > > Then it would have failed to accomplish that. > >> There is strong support for it in certain quarters of python-dev. [?] > > There *was*. The referred thread is from 2012-02. It is 2015-12. Then show some evidence that python-dev has changed in viewpoint. ChrisA From PointedEars at web.de Mon Dec 21 09:19:19 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 15:19:19 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: <4322502.fjrUL15KNH@PointedEars.de> Chris Angelico wrote: > [?] Thomas 'PointedEars' Lahn [?] wrote: >> Chris Angelico wrote: >>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>> Mark Lawrence wrote: >>>>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>>>> Chris Angelico wrote: >>>>>>> But it's been clearly stated that .format is not going to do away >>>>>>> with percent formatting, and all language of "new-style formatting" >>>>>>> has been removed so as not to cause confusion. >>>>>> Wishful thinking, twice. >>>>> http://www.gossamer-threads.com/lists/python/dev/969817 >>>> What is this supposed to be evidence of? >>> Proof that percent formatting isn't planned for deprecation, much less >>> removal. >> Then it would have failed to accomplish that. >> >>> There is strong support for it in certain quarters of python-dev. [?] >> There *was*. The referred thread is from 2012-02. It is 2015-12. > > Then show some evidence that python-dev has changed in viewpoint. And why would I do that? I have claimed no such thing. Your attempt to shift the burden of proof is unsuccessful. BTW, which part of ?attribution line? did you not understand? -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From breamoreboy at yahoo.co.uk Mon Dec 21 11:07:32 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Dec 2015 16:07:32 +0000 Subject: Ignore error with non-zero exit status In-Reply-To: <4322502.fjrUL15KNH@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> <4322502.fjrUL15KNH@PointedEars.de> Message-ID: On 21/12/2015 14:19, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> [?] Thomas 'PointedEars' Lahn [?] wrote: >>> Chris Angelico wrote: >>>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>>> Mark Lawrence wrote: >>>>>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>>>>> Chris Angelico wrote: >>>>>>>> But it's been clearly stated that .format is not going to do away >>>>>>>> with percent formatting, and all language of "new-style formatting" >>>>>>>> has been removed so as not to cause confusion. >>>>>>> Wishful thinking, twice. >>>>>> http://www.gossamer-threads.com/lists/python/dev/969817 >>>>> What is this supposed to be evidence of? >>>> Proof that percent formatting isn't planned for deprecation, much less >>>> removal. >>> Then it would have failed to accomplish that. >>> >>>> There is strong support for it in certain quarters of python-dev. [?] >>> There *was*. The referred thread is from 2012-02. It is 2015-12. >> >> Then show some evidence that python-dev has changed in viewpoint. > > And why would I do that? I have claimed no such thing. > > Your attempt to shift the burden of proof is unsuccessful. > > BTW, which part of ?attribution line? did you not understand? > Would you please go away as your continued trolling is getting tedious. TIA. -- 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 Mon Dec 21 11:10:02 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Mon, 21 Dec 2015 10:10:02 -0600 Subject: v3.5.1 - msi download In-Reply-To: References: Message-ID: On Mon, Dec 21, 2015 at 6:49 AM, Mark Lawrence wrote: > On 19/12/2015 17:45, Renato Emanuel Dysangco wrote: >> >> hello >> >> is an **.msi* version of your *Python 3.5.1 (32 bit)* in the pipeline >> soon? >> >> thanks for your time >> > > msi files are not being made available for 3.5. Correction: there is no longer a single MSI for everything. However, each individual component (e.g. the interpreter, the standard library, the standard library test suite, Tcl/Tk and IDLE, etc...) is packaged as an MSI, and all can be downloaded by running the installer as `.exe /layout some/path/to/hold/the/MSIs`. The .exe installer itself also takes many useful command line options, see https://docs.python.org/3.5/using/windows.html. -- Zach From random832 at fastmail.com Mon Dec 21 11:30:24 2015 From: random832 at fastmail.com (Random832) Date: Mon, 21 Dec 2015 11:30:24 -0500 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> <4322502.fjrUL15KNH@PointedEars.de> Message-ID: <87d1tzdasf.fsf@fastmail.com> Thomas 'PointedEars' Lahn writes: > Chris Angelico wrote: CA>>>> Proof that percent formatting isn't planned for deprecation, much less CA>>>> removal. TL>>> Then it would have failed to accomplish that. CA>>>> There is strong support for it in certain quarters of python-dev. [?] TL>>> There *was*. The referred thread is from 2012-02. It is 2015-12. CA>> Then show some evidence that python-dev has changed in viewpoint. TL> And why would I do that? I have claimed no such thing. Yes, you have. Your claim that evidence from 2012 is no longer relevant is an implicit claim of precisely that. From duncan at invalid.invalid Mon Dec 21 11:40:50 2015 From: duncan at invalid.invalid (duncan smith) Date: Mon, 21 Dec 2015 16:40:50 +0000 Subject: Catogorising strings into random versus non-random In-Reply-To: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21/12/15 03:01, Steven D'Aprano wrote: > I have a large number of strings (originally file names) which tend to fall > into two groups. Some are human-meaningful, but not necessarily dictionary > words e.g.: > > > baby lions at play > saturday_morning12 > Fukushima > ImpossibleFork > > > (note that some use underscores, others spaces, and some CamelCase) while > others are completely meaningless (or mostly so): > > > xy39mGWbosjY > 9sjz7s8198ghwt > rz4sdko-28dbRW00u > > > Let's call the second group "random" and the first "non-random", without > getting bogged down into arguments about whether they are really random or > not. I wish to process the strings and automatically determine whether each > string is random or not. I need to split the strings into three groups: > > - those that I'm confident are random > - those that I'm unsure about > - those that I'm confident are non-random > > Ideally, I'll get some sort of numeric score so I can tweak where the > boundaries fall. > > Strings are *mostly* ASCII but may include a few non-ASCII characters. > > Note that false positives (detecting a meaningful non-random string as > random) is worse for me than false negatives (miscategorising a random > string as non-random). > > Does anyone have any suggestions for how to do this? Preferably something > already existing. I have some thoughts and/or questions: > > - I think nltk has a "language detection" function, would that be suitable? > > - If not nltk, are there are suitable language detection libraries? > > - Is this the sort of problem that neural networks are good at solving? > Anyone know a really good tutorial for neural networks in Python? > > - How about Bayesian filters, e.g. SpamBayes? > > > > Finite state machine / transition matrix. Learn from some English text source. Then process your strings by lower casing, replacing underscores with spaces, removing trailing numeric characters etc. Base your score on something like the mean transition probability. I'd expect to see two pretty well separated groups of scores. Duncan From ian.g.kelly at gmail.com Mon Dec 21 11:49:55 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 21 Dec 2015 09:49:55 -0700 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Dec 21, 2015 at 9:40 AM, duncan smith wrote: > Finite state machine / transition matrix. Learn from some English text > source. Then process your strings by lower casing, replacing underscores > with spaces, removing trailing numeric characters etc. Base your score > on something like the mean transition probability. I'd expect to see two > pretty well separated groups of scores. Sounds like a case for a Hidden Markov Model. From breamoreboy at yahoo.co.uk Mon Dec 21 12:09:21 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Dec 2015 17:09:21 +0000 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21/12/2015 16:49, Ian Kelly wrote: > On Mon, Dec 21, 2015 at 9:40 AM, duncan smith wrote: >> Finite state machine / transition matrix. Learn from some English text >> source. Then process your strings by lower casing, replacing underscores >> with spaces, removing trailing numeric characters etc. Base your score >> on something like the mean transition probability. I'd expect to see two >> pretty well separated groups of scores. > > Sounds like a case for a Hidden Markov Model. > In which case https://pypi.python.org/pypi/Markov/0.1 would seem to be a starting point. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rxjwg98 at gmail.com Mon Dec 21 12:15:38 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 21 Dec 2015 09:15:38 -0800 (PST) Subject: What could cause a plot fail in my code? Message-ID: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> Hi, I find a useful code snippet on link: http://stackoverflow.com/questions/25126444/logistic-regression-in-pymc/34400966#34400966 but it has error on plot function. The error message is as following: --------- %run "C:\Users\rj\pyprj\logic_regression0.py" [-----------------100%-----------------] 10000 of 10000 complete in 12.6 secPlotting beta0 Plotting tau Plotting betaSalad Plotting sigma --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) C:\Users\pyprj\logic_regression0.py in () 34 #m.sample(100000, 50000, 50) 35 m.sample(10000, 5000, 50) ---> 36 pm.Matplot.plot(m) 37 import matplotlib.pyplot as plt 38 #plt.plot(m) C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) 339 if args: 340 name = '%s_%s' % (args[0], variable.__name__) --> 341 f(data, name, *args, **kwargs) 342 return 343 except AttributeError: C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in plot(data, name, format, suffix, path, common_scale, datarange, new, last, rows, num, fontmap, verbose) 453 num=num * 2, 454 last=last, --> 455 fontmap=fontmap) 456 457 if last: C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) 375 376 # If others fail, assume that raw data is passed --> 377 f(pymc_obj, *args, **kwargs) 378 379 wrapper.__doc__ = f.__doc__ C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in histogram(data, name, bins, datarange, format, suffix, path, rows, columns, num, last, fontmap, verbose) 576 577 # Generate histogram --> 578 hist(data.tolist(), bins, histtype='stepfilled') 579 580 xlim(datarange) C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs) 2956 histtype=histtype, align=align, orientation=orientation, 2957 rwidth=rwidth, log=log, color=color, label=label, -> 2958 stacked=stacked, data=data, **kwargs) 2959 finally: 2960 ax.hold(washold) C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1809 warnings.warn(msg % (label_namer, func.__name__), 1810 RuntimeWarning, stacklevel=2) -> 1811 return func(ax, *args, **kwargs) 1812 pre_doc = inner.__doc__ 1813 if pre_doc is None: C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs) 6192 ymin = np.amin(m[m != 0]) 6193 # filter out the 0 height bins -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty else minimum 6195 ymin = min(ymin0, ymin) 6196 self.dataLim.intervaly = (ymin, ymax) UnboundLocalError: local variable 'ymin' referenced before assignment ///////////// I have no clue at all on debug it. Could you help me? Thanks, From no.email at nospam.invalid Mon Dec 21 12:20:01 2015 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 21 Dec 2015 09:20:01 -0800 Subject: Catogorising strings into random versus non-random References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <874mfbk9by.fsf@nightsong.com> Steven D'Aprano writes: > Does anyone have any suggestions for how to do this? Preferably something > already existing. I have some thoughts and/or questions: I think I'd just look at the set of digraphs or trigraphs in each name and see if there are a lot that aren't found in English. > - I think nltk has a "language detection" function, would that be suitable? > - If not nltk, are there are suitable language detection libraries? I suspect these need longer strings to work. > - Is this the sort of problem that neural networks are good at solving? > Anyone know a really good tutorial for neural networks in Python? > - How about Bayesian filters, e.g. SpamBayes? You want large training sets for these approaches. From rxjwg98 at gmail.com Mon Dec 21 12:29:24 2015 From: rxjwg98 at gmail.com (Robert) Date: Mon, 21 Dec 2015 09:29:24 -0800 (PST) Subject: What could cause a plot fail in my code? In-Reply-To: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> References: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> Message-ID: On Monday, December 21, 2015 at 12:15:54 PM UTC-5, Robert wrote: > Hi, > > I find a useful code snippet on link: > > http://stackoverflow.com/questions/25126444/logistic-regression-in-pymc/34400966#34400966 > > but it has error on plot function. The error message is as following: > --------- > %run "C:\Users\rj\pyprj\logic_regression0.py" > [-----------------100%-----------------] 10000 of 10000 complete in 12.6 secPlotting beta0 > Plotting tau > Plotting betaSalad > Plotting sigma > --------------------------------------------------------------------------- > UnboundLocalError Traceback (most recent call last) > C:\Users\pyprj\logic_regression0.py in () > 34 #m.sample(100000, 50000, 50) > 35 m.sample(10000, 5000, 50) > ---> 36 pm.Matplot.plot(m) > 37 import matplotlib.pyplot as plt > 38 #plt.plot(m) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) > 339 if args: > 340 name = '%s_%s' % (args[0], variable.__name__) > --> 341 f(data, name, *args, **kwargs) > 342 return > 343 except AttributeError: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in plot(data, name, format, suffix, path, common_scale, datarange, new, last, rows, num, fontmap, verbose) > 453 num=num * 2, > 454 last=last, > --> 455 fontmap=fontmap) > 456 > 457 if last: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) > 375 > 376 # If others fail, assume that raw data is passed > --> 377 f(pymc_obj, *args, **kwargs) > 378 > 379 wrapper.__doc__ = f.__doc__ > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in histogram(data, name, bins, datarange, format, suffix, path, rows, columns, num, last, fontmap, verbose) > 576 > 577 # Generate histogram > --> 578 hist(data.tolist(), bins, histtype='stepfilled') > 579 > 580 xlim(datarange) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs) > 2956 histtype=histtype, align=align, orientation=orientation, > 2957 rwidth=rwidth, log=log, color=color, label=label, > -> 2958 stacked=stacked, data=data, **kwargs) > 2959 finally: > 2960 ax.hold(washold) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) > 1809 warnings.warn(msg % (label_namer, func.__name__), > 1810 RuntimeWarning, stacklevel=2) > -> 1811 return func(ax, *args, **kwargs) > 1812 pre_doc = inner.__doc__ > 1813 if pre_doc is None: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs) > 6192 ymin = np.amin(m[m != 0]) > 6193 # filter out the 0 height bins > -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty else minimum > 6195 ymin = min(ymin0, ymin) > 6196 self.dataLim.intervaly = (ymin, ymax) > > UnboundLocalError: local variable 'ymin' referenced before assignment > ///////////// > > I have no clue at all on debug it. Could you help me? > Thanks, Excuse me. The code link should be this one: http://nbviewer.ipython.org/gist/aflaxman/8329ec1b9f861469f896 Do you experience such errors? Thanks, From duncan at invalid.invalid Mon Dec 21 12:41:34 2015 From: duncan at invalid.invalid (duncan smith) Date: Mon, 21 Dec 2015 17:41:34 +0000 Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21/12/15 16:49, Ian Kelly wrote: > On Mon, Dec 21, 2015 at 9:40 AM, duncan smith wrote: >> Finite state machine / transition matrix. Learn from some English text >> source. Then process your strings by lower casing, replacing underscores >> with spaces, removing trailing numeric characters etc. Base your score >> on something like the mean transition probability. I'd expect to see two >> pretty well separated groups of scores. > > Sounds like a case for a Hidden Markov Model. > Perhaps. That would allow the encoding of marginal probabilities and distinct transition matrices for each class - if we could learn those extra parameters. Duncan From aaron.christensen at gmail.com Mon Dec 21 12:45:44 2015 From: aaron.christensen at gmail.com (Aaron) Date: Mon, 21 Dec 2015 09:45:44 -0800 (PST) Subject: In Python 3, how to append a nested dictionary to a shelve file with the added difficulty of using a for loop? Message-ID: <80ad4862-021b-4b3c-9b39-c99e79c3a9a2@googlegroups.com> Hello, I am trying to figure out how to populate a shelve file with a nested dictionary. These are my requirements: -Create shelve file called people.db -Append the shelve file with new people (person_1, person_2, etc.). -Use a for loop to iterate through 'attributes' so that I do not need to write out the lengthy code line by line to populate to the shelve file. -Need to reference shelve file data for future use Here is the key/value format that I would like to append to the shelve file. person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, {'game': 'bridge', 'high score': '10', 'time': '30.34'}, {'game': 'foosball', 'high score': '2', 'time': '24'}] ''' 50+ other attributes ''' } # Example: s['person_1]['attributes'][2]['time'] would call out '24'. # 's' is from 's = shelve.open('people')' I have a dictionary dictPeople.py file (created using pprint() that contains the information of person_1, etc. And I am extracting only a small percentage of the data that is needed. I have tried the following, but I get an invalid key error. import shelve, dictPeople s = shelve.open('people') person = 'person_1' s[person]['name'] = dictPeople.person_1['name'] s[person]['type'] = dictPeople.person_1['type'] # I need to use this for loop because there are 50+ attributes. for attribute in range(0, len(dictPeople['attributes'][attribute])): s[person]['attributes'][attribute]['game'] = \ dictPeople['attributes'][attribute]['game'] s[person]['attributes'][attribute]['high score'] = \ dictPeople['attributes'][attribute]['high score'] s[person]['attributes'][attribute]['time'] = \ dictPeople['attributes'][attribute]['time'] It turns out, I get the key error because I am not allowed to reference a key/value pair the same way that I can with a dictionary. However, the crazy thing is that I can call values in the db file using the same exact format when trying to write. For example: I can read data from the .db file using: x = s['person_1']['name'] print(x) BUT! I cannot write to that .db file using that exact format or I get an invalid key error. Makes no sense! s['person_1']['name'] = 'Bob' # Returns invalid key entry. Makes no sense. Therefore, I tried to extract data and populate the db file using the following: s[person] = { 'name': dictPeople.person_1['name'], 'type': dictPeople.person_1['type'], for attribute in range(0, len(dictPeople['attributes'][attribute])): ['game': dictPeople['attributes'][attribute]['game'], 'high score': dictPeople['attributes'][attribute]['high score'], 'time': dictPeople['attributes'][attribute]['time']] } But, this obvously doesn't work because of the for loop. How can I do this? -I am trying to figure out how to extract data from the dictionary dictPeople.py file and store it in the people.db file. -I am trying to add new people to the people.db file as more people become available. -I need to use the for loop because of the 50+ attributes I need to add. -My future steps would be to modify some of the data values that I extract and used to populate the people.db file, but my first step is to, at least, extract, and then populate the people.db file. Any help or guidance is greatly appreciated. Thank you for your time and reading my question. Thanks! Aaron From invalid at invalid.invalid Mon Dec 21 12:51:00 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 21 Dec 2015 17:51:00 +0000 (UTC) Subject: Library function to encode data to multipart/form-data format? Message-ID: Is there a standard library function that can be used to encode data into multipart/form-data format? IIRC, I looked for this once before and didn't find anything in the library. [I don't want to actually send an HTTP POST or an email message, I just need to generate sets of data for test purposes.] -- Grant Edwards grant.b.edwards Yow! -- I love KATRINKA at because she drives a gmail.com PONTIAC. We're going away now. I fed the cat. From pkpearson at nowhere.invalid Mon Dec 21 12:54:41 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 21 Dec 2015 17:54:41 GMT Subject: What could cause a plot fail in my code? References: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> Message-ID: On Mon, 21 Dec 2015 09:29:24 -0800 (PST), Robert wrote: > On Monday, December 21, 2015 at 12:15:54 PM UTC-5, Robert wrote: >> Hi, >> >> I find a useful code snippet on link: >> >> http://stackoverflow.com/questions/25126444/logistic-regression-in-pymc/34400966#34400966 >> >> but it has error on plot function. The error message is as following: >> --------- >> %run "C:\Users\rj\pyprj\logic_regression0.py" >> [-----------------100%-----------------] 10000 of 10000 complete in 12.6 secPlotting beta0 >> Plotting tau >> Plotting betaSalad >> Plotting sigma >> --------------------------------------------------------------------------- >> UnboundLocalError Traceback (most recent call last) >> C:\Users\pyprj\logic_regression0.py in () >> 34 #m.sample(100000, 50000, 50) >> 35 m.sample(10000, 5000, 50) >> ---> 36 pm.Matplot.plot(m) >> 37 import matplotlib.pyplot as plt >> 38 #plt.plot(m) >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) >> 339 if args: >> 340 name = '%s_%s' % (args[0], variable.__name__) >> --> 341 f(data, name, *args, **kwargs) >> 342 return >> 343 except AttributeError: >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in plot(data, name, format, suffix, path, common_scale, datarange, new, last, rows, num, fontmap, verbose) >> 453 num=num * 2, >> 454 last=last, >> --> 455 fontmap=fontmap) >> 456 >> 457 if last: >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) >> 375 >> 376 # If others fail, assume that raw data is passed >> --> 377 f(pymc_obj, *args, **kwargs) >> 378 >> 379 wrapper.__doc__ = f.__doc__ >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pymc\Matplot.pyc in histogram(data, name, bins, datarange, format, suffix, path, rows, columns, num, last, fontmap, verbose) >> 576 >> 577 # Generate histogram >> --> 578 hist(data.tolist(), bins, histtype='stepfilled') >> 579 >> 580 xlim(datarange) >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs) >> 2956 histtype=histtype, align=align, orientation=orientation, >> 2957 rwidth=rwidth, log=log, color=color, label=label, >> -> 2958 stacked=stacked, data=data, **kwargs) >> 2959 finally: >> 2960 ax.hold(washold) >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) >> 1809 warnings.warn(msg % (label_namer, func.__name__), >> 1810 RuntimeWarning, stacklevel=2) >> -> 1811 return func(ax, *args, **kwargs) >> 1812 pre_doc = inner.__doc__ >> 1813 if pre_doc is None: >> >> C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs) >> 6192 ymin = np.amin(m[m != 0]) >> 6193 # filter out the 0 height bins >> -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty else minimum >> 6195 ymin = min(ymin0, ymin) >> 6196 self.dataLim.intervaly = (ymin, ymax) >> >> UnboundLocalError: local variable 'ymin' referenced before assignment >> ///////////// >> >> I have no clue at all on debug it. Could you help me? >> Thanks, > > Excuse me. The code link should be this one: > > http://nbviewer.ipython.org/gist/aflaxman/8329ec1b9f861469f896 > > Do you experience such errors? >From a quick look, it appears that you are trying to plot a histogram in which all the bins are empty. -- To email me, substitute nowhere->runbox, invalid->com. From __peter__ at web.de Mon Dec 21 13:10:40 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Dec 2015 19:10:40 +0100 Subject: What could cause a plot fail in my code? References: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> Message-ID: Robert wrote: > Hi, > > I find a useful code snippet on link: > > http://stackoverflow.com/questions/25126444/logistic-regression-in-pymc/34400966#34400966 > > but it has error on plot function. The error message is as following: > --------- > %run "C:\Users\rj\pyprj\logic_regression0.py" > [-----------------100%-----------------] 10000 of 10000 complete in 12.6 > [ secPlotting beta0 > Plotting tau > Plotting betaSalad > Plotting sigma > --------------------------------------------------------------------------- > UnboundLocalError Traceback (most recent call > last) C:\Users\pyprj\logic_regression0.py in () > 34 #m.sample(100000, 50000, 50) > 35 m.sample(10000, 5000, 50) > ---> 36 pm.Matplot.plot(m) > 37 import matplotlib.pyplot as plt > 38 #plt.plot(m) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- > packages\pymc\Matplot.pyc in wrapper(pymc_obj, *args, **kwargs) > 339 if args: > 340 name = '%s_%s' % (args[0], > variable.__name__) > --> 341 f(data, name, *args, **kwargs) > 342 return > 343 except AttributeError: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc > in plot(data, name, format, suffix, path, common_scale, datarange, new, > last, rows, num, fontmap, verbose) > 453 num=num * 2, > 454 last=last, > --> 455 fontmap=fontmap) > 456 > 457 if last: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc > in wrapper(pymc_obj, *args, **kwargs) > 375 > 376 # If others fail, assume that raw data is passed > --> 377 f(pymc_obj, *args, **kwargs) > 378 > 379 wrapper.__doc__ = f.__doc__ > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\pymc\Matplot.pyc > in histogram(data, name, bins, datarange, format, suffix, path, rows, > columns, num, last, fontmap, verbose) > 576 > 577 # Generate histogram > --> 578 hist(data.tolist(), bins, histtype='stepfilled') > 579 > 580 xlim(datarange) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\matplotlib\pyplot.py > in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, > align, orientation, rwidth, log, color, label, stacked, hold, data, > **kwargs) > 2956 histtype=histtype, align=align, > orientation=orientation, > 2957 rwidth=rwidth, log=log, color=color, > label=label, > -> 2958 stacked=stacked, data=data, **kwargs) > 2959 finally: > 2960 ax.hold(washold) > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\matplotlib\__init__.py > in inner(ax, *args, **kwargs) > 1809 warnings.warn(msg % (label_namer, > func.__name__), > 1810 RuntimeWarning, stacklevel=2) > -> 1811 return func(ax, *args, **kwargs) > 1812 pre_doc = inner.__doc__ > 1813 if pre_doc is None: > > C:\Users\AppData\Local\Enthought\Canopy\User\lib\site- packages\matplotlib\axes\_axes.py > in hist(self, x, bins, range, normed, weights, cumulative, bottom, > histtype, align, orientation, rwidth, log, color, label, stacked, > **kwargs) > 6192 ymin = np.amin(m[m != 0]) > 6193 # filter out the 0 height bins > -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty > else minimum > 6195 ymin = min(ymin0, ymin) > 6196 self.dataLim.intervaly = (ymin, ymax) > > UnboundLocalError: local variable 'ymin' referenced before assignment > ///////////// > > I have no clue at all on debug it. Could you help me? To me that looks like a bug in matplotlib. ymin is not properly initialised before the loop """ for m in n: if np.sum(m) > 0: # make sure there are counts ymin = np.amin(m[m != 0]) # filter out the 0 height bins ymin = max(ymin*0.9, minimum) if not input_empty else minimum """ so if for there aren't any m with np.sum(m) > 0 (i. e. all bins are empty) you get the error. Here's a made-up example for illustration: >>> def last_positive_item(items): ... for item in items: ... if item > 0: ... last = item ... return last ... As long as you pass at least one positive item everything seems OK: >>> last_positive_item([1, 2, -3, 3]) 3 But if you don't you get the error: >>> last_positive_item([-1, -2, -3, 0]) Traceback (most recent call last): File "", line 1, in File "", line 5, in last_positive_item UnboundLocalError: local variable 'last' referenced before assignment Please file a bug report if there isn't one already. From eryksun at gmail.com Mon Dec 21 13:24:11 2015 From: eryksun at gmail.com (eryk sun) Date: Mon, 21 Dec 2015 12:24:11 -0600 Subject: IDLE 3.5.1 quits unexpectedly (portuguese keyboard) In-Reply-To: References: Message-ID: On Fri, Dec 18, 2015 at 9:15 PM, Osvaldo Dias dos Santos wrote: > > Pressing the tilde key my iMac portuguese keyboard quits IDLE > unexpectedly (along with any associated files I may be working > on, including code). > > The keyboard image is attached. The tilde key is the second > orange one from the top. There's no file attached. Attachments are unreliable on a list. This should suffice: https://en.wikipedia.org/wiki/Portuguese_keyboard_layout > This key is very important in this language, because pressing > it together with the shift key, the caret ( ^ ) symbol is > entered. So, if I try to enter a caret and press the shift and > the tilde key to do it, IDLE quits and any unsaved file > information (even code) is lost. Then Apple crash report window > opens, but if I click the reopen button nothing happens, IDLE > does not reopen. I know on Linux, Tk 8.6 has a problem with dead keys when using an international keyboard layout (see issue 25356 [1]). This crash could be related to whatever causes the problem on Linux. Try running a simple test.tcl script via wish: text .t pack .t Does wish crash when you press tilde in the window? [1]: http://bugs.python.org/issue25356 From eryksun at gmail.com Mon Dec 21 13:38:01 2015 From: eryksun at gmail.com (eryk sun) Date: Mon, 21 Dec 2015 12:38:01 -0600 Subject: No subject In-Reply-To: References: Message-ID: On Mon, Dec 21, 2015 at 3:08 AM, Animesh Srivastava wrote: > While installin python3.5.1 i m getting 0xc000007b error 0xC000007B is STATUS_INVALID_IMAGE_FORMAT, so there's something wrong with the executable. Try clearing your browser cache and download the installer again. From saurabhtiwaririshi at gmail.com Mon Dec 21 14:05:14 2015 From: saurabhtiwaririshi at gmail.com (saurabhtiwaririshi at gmail.com) Date: Mon, 21 Dec 2015 11:05:14 -0800 (PST) Subject: How can I produce ARFF files using word2vec-toolkit Message-ID: <8c80f366-03f9-42da-85c9-15711da7ec7c@googlegroups.com> I am doing a machine learning project and I need ARFF files to feed my data to Weka. How can I use word2-vec to produce ARFF files. An example would be much helpful. From invalid at invalid.invalid Mon Dec 21 14:32:17 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 21 Dec 2015 19:32:17 +0000 (UTC) Subject: (Execution) Termination bit, Alternation bit. References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: On 2015-12-21, Dennis Lee Bieber wrote: > On Mon, 21 Dec 2015 13:40:21 +0100, "Skybuck Flying" > declaimed the following: > >>The original idea I posted is less about sending a signal to another >>processor. >> >>It is more about how to break out of an instruction sequence. >> >>Example of problem: >> >>Main: >>while Condition1 do >>begin >> while Condition2 do >> begin >> while Condition3 do >> begin >> Routine1 >> end >> end; >>end; >> > I do hope this is the result of over simplification for the example, as > otherwise I'd turn it into > > while C1 and C2 and C3: > R1 That's not equivalent to what Skybuck posted. Think about what happens when Routine1 causes Condition1 and Condition2 to become false but Condition3 remains true. Not that this means that all rest of what Skyhawk posted makes any sense at all. I've spent a lot of time programming on "bare metal", in assembly, Pascal, PL/M, and C (including using coroutines and various other "multi-thread" constructs with no OS support), and I really don't see the utility of his initial suggestion. -- Grant Edwards grant.b.edwards Yow! What a COINCIDENCE! at I'm an authorized "SNOOTS gmail.com OF THE STARS" dealer!! From ian.g.kelly at gmail.com Mon Dec 21 15:30:41 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 21 Dec 2015 13:30:41 -0700 Subject: Ignore error with non-zero exit status In-Reply-To: <2062582.Z8LLNUJk5W@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> Message-ID: On Sun, Dec 20, 2015 at 3:46 PM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> On Mon, Dec 21, 2015 at 8:22 AM, Thomas 'PointedEars' Lahn >> wrote: > > It is supposed to be an attribution *line*, _not_ an attribution novel. > Also, the ?(was: ?)? part is to be removed from the Subject header field > value to complete the change of subject in a thread. Better yet, please don't change the Subject header for trivial reasons in the first place. This isn't just a Usenet group; it's also a mailing list, and many MUAs rely on the Subject header for proper threading. From ben+python at benfinney.id.au Mon Dec 21 15:58:57 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 22 Dec 2015 07:58:57 +1100 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> Message-ID: <85oadj1pta.fsf_-_@benfinney.id.au> Ian Kelly writes: > Better yet, please don't change the Subject header for trivial reasons > in the first place. When the subject of the ongoing discussion changes, it's normal to change the Subject field accordingly. I agree with your admonition against trivial alterations to that field; I hope you agree with me that it is not trivial, but rather is normal and helpful, to update the Subject field to track significant changes in the subject of the discussion. > This isn't just a Usenet group; it's also a mailing list, and many > MUAs rely on the Subject header for proper threading. If such MUAs do that, they're misinterpreting the Subject field. Other fields are available with the explicit meaning of relating messages to each other regardless of what they discuss. If the correct fields are being mangled, then the correct place to apply pressure is on those who can fix that error. Let's not overload the Subject field to make up the lack. -- \ ?Self-respect: The secure feeling that no one, as yet, is | `\ suspicious.? ?Henry L. Mencken | _o__) | Ben Finney From ian.g.kelly at gmail.com Mon Dec 21 16:16:13 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 21 Dec 2015 14:16:13 -0700 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) In-Reply-To: <85oadj1pta.fsf_-_@benfinney.id.au> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> Message-ID: On Mon, Dec 21, 2015 at 1:58 PM, Ben Finney wrote: > Ian Kelly writes: >> This isn't just a Usenet group; it's also a mailing list, and many >> MUAs rely on the Subject header for proper threading. > > If such MUAs do that, they're misinterpreting the Subject field. Other > fields are available with the explicit meaning of relating messages to > each other regardless of what they discuss. > > If the correct fields are being mangled, then the correct place to apply > pressure is on those who can fix that error. Let's not overload the > Subject field to make up the lack. It might just be Gmail. http://webapps.stackexchange.com/questions/965/how-does-gmail-decide-to-thread-email-messages I can't specifically recall if I've used any MUA other than Gmail that even attempts threading email messages. From jon+usenet at unequivocal.co.uk Mon Dec 21 16:44:23 2015 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 21 Dec 2015 21:44:23 -0000 (UTC) Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> Message-ID: On 2015-12-21, Ian Kelly wrote: > On Mon, Dec 21, 2015 at 1:58 PM, Ben Finney wrote: >> Ian Kelly writes: >>> This isn't just a Usenet group; it's also a mailing list, and many >>> MUAs rely on the Subject header for proper threading. >> >> If such MUAs do that, they're misinterpreting the Subject field. Other >> fields are available with the explicit meaning of relating messages to >> each other regardless of what they discuss. >> >> If the correct fields are being mangled, then the correct place to apply >> pressure is on those who can fix that error. Let's not overload the >> Subject field to make up the lack. > > It might just be Gmail. > > http://webapps.stackexchange.com/questions/965/how-does-gmail-decide-to-thread-email-messages > > I can't specifically recall if I've used any MUA other than Gmail that > even attempts threading email messages. Also: Thunderbird, The Bat!, Eudora, Gnus, Outlook, Outlook Express, Pegasus Mail, Pine, Apple Mail, Windows Live Mail, Yahoo Mail, Evolution, SquirrelMail, KMail, Windows Mail, etc. Trying to suggest that MUAs should never look at the Subject line for threading is, unfortunately, ridiculous. Yes, in theory it shouldn't be necessary but in practice enough people are using poor clients that don't provide enough context in the proper headers that it can't be avoided. And, yes, fixing the mail clients of "everybody else in the world" might be a lovely idea but it is a little impractical to implement. From aaron.christensen at gmail.com Mon Dec 21 17:02:49 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Mon, 21 Dec 2015 17:02:49 -0500 Subject: In Python 3, how to append a nested dictionary to a shelve file with the added difficulty of using a for loop? Message-ID: Hello, I am trying to figure out how to populate a shelve file with a nested dictionary. These are my requirements: -Create shelve file called people.db -Append the shelve file with new people (person_1, person_2, etc.). -Use a for loop to iterate through 'attributes' so that I do not need to write out the lengthy code line by line to populate to the shelve file. -Need to reference shelve file data for future use Here is the key/value format that I would like to append to the shelve file. person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, {'game': 'bridge', 'high score': '10', 'time': '30.34'}, {'game': 'foosball', 'high score': '2', 'time': '24'}] ''' 50+ other attributes ''' } # Example: s['person_1]['attributes'][2]['time'] would call out '24'. # 's' is from 's = shelve.open('people')' I have a dictionary dictPeople.py file (created using pprint() that contains the information of person_1, etc. And I am extracting only a small percentage of the data that is needed. I have tried the following, but I get an invalid key error. import shelve, dictPeople s = shelve.open('people') person = 'person_1' s[person]['name'] = dictPeople.person_1['name'] s[person]['type'] = dictPeople.person_1['type'] # I need to use this for loop because there are 50+ attributes. for attribute in range(0, len(dictPeople['attributes'][attribute])): s[person]['attributes'][attribute]['game'] = \ dictPeople['attributes'][attribute]['game'] s[person]['attributes'][attribute]['high score'] = \ dictPeople['attributes'][attribute]['high score'] s[person]['attributes'][attribute]['time'] = \ dictPeople['attributes'][attribute]['time'] It turns out, I get the key error because I am not allowed to reference a key/value pair the same way that I can with a dictionary. However, the crazy thing is that I can call values in the db file using the same exact format when trying to write. For example: I can read data from the .db file using: x = s['person_1']['name'] print(x) BUT! I cannot write to that .db file using that exact format or I get an invalid key error. Makes no sense! s['person_1']['name'] = 'Bob' # Returns invalid key entry. Makes no sense. Therefore, I tried to extract data and populate the db file using the following: s[person] = { 'name': dictPeople.person_1['name'], 'type': dictPeople.person_1['type'], for attribute in range(0, len(dictPeople['attributes'][attribute])): ['game': dictPeople['attributes'][attribute]['game'], 'high score': dictPeople['attributes'][attribute]['high score'], 'time': dictPeople['attributes'][attribute]['time']] } But, this obvously doesn't work because of the for loop. How can I do this? -I am trying to figure out how to extract data from the dictionary dictPeople.py file and store it in the people.db file. -I am trying to add new people to the people.db file as more people become available. -I need to use the for loop because of the 50+ attributes I need to add. -My future steps would be to modify some of the data values that I extract and used to populate the people.db file, but my first step is to, at least, extract, and then populate the people.db file. Any help or guidance is greatly appreciated. Thank you for your time and reading my question. Thanks! Aaron From PointedEars at web.de Mon Dec 21 17:55:52 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Mon, 21 Dec 2015 23:55:52 +0100 Subject: Meaning and purpose of the Subject field References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> Message-ID: <4441426.TLOAiApiO3@PointedEars.de> Jon Ribbens wrote: > On 2015-12-21, Ian Kelly wrote: >> I can't specifically recall if I've used any MUA other than Gmail that >> even attempts threading email messages. > > Also: Thunderbird, The Bat!, Eudora, Gnus, Outlook, Outlook Express, > Pegasus Mail, Pine, Apple Mail, Windows Live Mail, Yahoo Mail, > Evolution, SquirrelMail, KMail, Windows Mail, etc. Yes, of course. > Trying to suggest that MUAs should never look at the Subject line for > threading is, unfortunately, ridiculous. No, it is what the Internet message standard says instead: ,- | | 3.6.4. Identification Fields | | Though listed as optional in the table in section 3.6, every message | SHOULD have a "Message-ID:" field. Furthermore, reply messages | SHOULD have "In-Reply-To:" and "References:" fields as appropriate | and as described below. | | The "Message-ID:" field contains a single unique message identifier. | The "References:" and "In-Reply-To:" fields each contain one or more | unique message identifiers, optionally separated by CFWS. (?SHOULD? in an RFC means: ?do as I say unless you can give me a very good reason not to do it?. See RFC 2119 for details.) vs. ,- | | 3.6.5. Informational Fields | | The informational fields are all optional. The "Subject:" and | "Comments:" fields are unstructured fields as defined in section | 2.2.1, and therefore may contain text or folding white space. [?] > Yes, in theory it shouldn't be necessary It is not. > but in practice enough people are using poor clients that don't provide > enough context in the proper headers that it can't be avoided. That Internet communication is made more difficult for *all* because a *perceived* majority of *perceived* clients is broken, is putting upside down the good Internet principle of ?be conservative in what to send, liberal in what to receive?. Those b0rked clients should either be fixed at once or not be used, period. Instead, in practice, the Python mailing list software is b0rked since I know of the mailing list?s/newsgroups? existence (several years ago): it is b0rked in the regard that its distributor does not consider that it is also posted to a Usenet newsgroup where articles require a References header field to be properly threaded. Incidentally, that References header field is, in the absence of an In-Reply-To header field, used by hybrid e mail/NetNews agents such as Thunderbird, in full compliance with the NetNews message standard: ,- | | 3. News Header Fields | | The following news header fields extend those defined in Section 3.6 | of [RFC5322]: | | [?] | 3.2.10. References | | The References header field is the same as that specified in Section | 3.6.4 of [RFC5322], with the added restrictions detailed above in | Section 2.2 and those listed below: [?] One could kill two birds with one stone here by fixing this, but it is not done. Why? > And, yes, fixing the mail clients of "everybody else in the world" > might be a lovely idea but it is a little impractical to implement. I find your argument strewn with gaping defects in logic. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From steve at pearwood.info Mon Dec 21 18:14:57 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Dec 2015 10:14:57 +1100 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> Message-ID: <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Dec 2015 08:44 am, Jon Ribbens wrote about mail clients that use the Subject line to thread messages: > Also: Thunderbird, The Bat!, Eudora, Gnus, Outlook, Outlook Express, > Pegasus Mail, Pine, Apple Mail, Windows Live Mail, Yahoo Mail, > Evolution, SquirrelMail, KMail, Windows Mail, etc. I understand that at least some of those will only use the Subject as a fallback when other threading information is not available. That's a reasonable strategy to take. As for mail clients that *always* and *exclusively* use the subject line to implement threading, they are horrifically broken. It is completely unreasonable to insist that people using non-broken tools must change their habits to support those with completely broken tools. So as far as I am concerned, if changes of subject line breaks threading for you, so sad, too bad. Go without threading or use a better mail client. > Trying to suggest that MUAs should never look at the Subject line for > threading is, unfortunately, ridiculous. Yes, in theory it shouldn't > be necessary but in practice enough people are using poor clients that > don't provide enough context in the proper headers that it can't be > avoided. *shrug* The whole purpose of the change of subject is to indicate in a human-visible way that the subject of the thread has changed, i.e. that it is a new thread derived from the old one. If that breaks threading, oh well, it breaks threading. > And, yes, fixing the mail clients of "everybody else in the world" > might be a lovely idea but it is a little impractical to implement. Less impractical than insisting that "everybody else in the world" must change their posting habits to suit those using broken mail clients. The fact is, even if nobody ever changed the subject line, sometimes threading will be broken. I can't find the energy to care about something which already only sometimes works. -- Steven From jon+usenet at unequivocal.co.uk Mon Dec 21 18:24:21 2015 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 21 Dec 2015 23:24:21 -0000 (UTC) Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2015-12-21, Steven D'Aprano wrote: > On Tue, 22 Dec 2015 08:44 am, Jon Ribbens wrote about mail clients that use > the Subject line to thread messages: >> Also: Thunderbird, The Bat!, Eudora, Gnus, Outlook, Outlook Express, >> Pegasus Mail, Pine, Apple Mail, Windows Live Mail, Yahoo Mail, >> Evolution, SquirrelMail, KMail, Windows Mail, etc. > > I understand that at least some of those will only use the Subject as a > fallback when other threading information is not available. That's a > reasonable strategy to take. > > As for mail clients that *always* and *exclusively* use the subject > line to implement threading, they are horrifically broken. Yes, that would be bizarre and clearly wrong. Are there any such clients? I wouldn't put it past Microsoft to do such a thing, of course ;-) > So as far as I am concerned, if changes of subject line breaks > threading for you, so sad, too bad. Go without threading or use a > better mail client. I have no comment on that. > The whole purpose of the change of subject is to indicate in a human-visible > way that the subject of the thread has changed, i.e. that it is a new > thread derived from the old one. If that breaks threading, oh well, it > breaks threading. That sounds a bit confused - if the *intention* of changing the subject line is to create a new thread, then breaking the thread is not "breaking threading" ;-) >> And, yes, fixing the mail clients of "everybody else in the world" >> might be a lovely idea but it is a little impractical to implement. > > Less impractical than insisting that "everybody else in the world" must > change their posting habits to suit those using broken mail clients. Fortunately I haven't suggested that. From steve at pearwood.info Mon Dec 21 18:32:07 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Dec 2015 10:32:07 +1100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> <4322502.fjrUL15KNH@PointedEars.de> <6452640.DtIUyGyQXD@PointedEars.de> Message-ID: <56788bf9$0$1621$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Dec 2015 09:27 am, Thomas 'PointedEars' Lahn wrote: [...] > No, it is not. Your logic is flawed, too, pseudonymous nobody with the > unreadable posting style. If its unreadable, how do you know what it says? "PointedEars", you're doing a marvellous job of acting like a self-righteous and hypocritical buffoon who constantly complains about the most trivial matters when committed by others, while ignoring that you do the same sort of things. You whinge about others using "fake names", whatever that means, when you yourself go by a fake name "PointedEars". You whinge about people's attribution lines extending over two virtual lines, as if that matters, while ignoring the fact that your sig is twice as long as is polite. You whinge about people posting "dumb questions", while continuing to post dumb answers. When you make an error of logic, your response is never to accept that you were wrong, but you just compound the error by insisting that the other party is the one with flawed logic. So, Thomas, if that is your real name, get over yourself. I don't know what small pond you have come from, but you're in the big ocean of the Internet now, and you're no longer the smartest person around. Admit it when you make a mistake, and stop being such so whiny, prissy and unhelpful. Or, if you can't do that, just go away and whine on some other newsgroup where they might be impressed by your astonishing lack of social know-how. Thank you. -- Steven From lac at openend.se Mon Dec 21 18:43:45 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 22 Dec 2015 00:43:45 +0100 Subject: Library function to encode data to multipart/form-data format? In-Reply-To: References: Message-ID: <201512212343.tBLNhjQr007301@theraft.openend.se> In a message of Mon, 21 Dec 2015 17:51:00 +0000, Grant Edwards writes: >Is there a standard library function that can be used to encode data >into multipart/form-data format? IIRC, I looked for this once before >and didn't find anything in the library. > >[I don't want to actually send an HTTP POST or an email message, I >just need to generate sets of data for test purposes.] > >-- >Grant Edwards grant.b.edwards Yow! -- I love KATRINKA > at because she drives a > gmail.com PONTIAC. We're going > away now. I fed the cat. >-- >https://mail.python.org/mailman/listinfo/python-list Cannibalise this: http://code.activestate.com/recipes/146306/ which just uses standard library things. Laura From tjreedy at udel.edu Mon Dec 21 18:53:42 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Dec 2015 18:53:42 -0500 Subject: Ignore error with non-zero exit status In-Reply-To: <2827307.1DEaE21uzt@PointedEars.de> References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: On 12/21/2015 9:05 AM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> On Tue, Dec 22, 2015 at 12:19 AM, Thomas 'PointedEars' Lahn >> wrote: >>> Mark Lawrence wrote: >>>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>>> Chris Angelico wrote: >>>>>> But it's been clearly stated that .format is not going to do away with >>>>>> percent formatting, and all language of "new-style formatting" has >>>>>> been removed so as not to cause confusion. >>>>> Wishful thinking, twice. >>>> http://www.gossamer-threads.com/lists/python/dev/969817 >>> What is this supposed to be evidence of? >> >> Proof that percent formatting isn't planned for deprecation, much less >> removal. > > Then it would have failed to accomplish that. > >> There is strong support for it in certain quarters of python-dev. [?] > > There *was*. The referred thread is from 2012-02. It is 2015-12. Nothing has changed since except for https://www.python.org/dev/peps/pep-0498/ already added to 3.6. If the 2.7 doc still implies that % -formatting is deprecated, it should changed as in the 3.x docs. -- Terry Jan Reedy From ian.g.kelly at gmail.com Mon Dec 21 18:57:17 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 21 Dec 2015 16:57:17 -0700 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Dec 21, 2015 at 4:24 PM, Jon Ribbens wrote: > On 2015-12-21, Steven D'Aprano wrote: >> The whole purpose of the change of subject is to indicate in a human-visible >> way that the subject of the thread has changed, i.e. that it is a new >> thread derived from the old one. If that breaks threading, oh well, it >> breaks threading. > > That sounds a bit confused - if the *intention* of changing the > subject line is to create a new thread, then breaking the thread > is not "breaking threading" ;-) > >>> And, yes, fixing the mail clients of "everybody else in the world" >>> might be a lovely idea but it is a little impractical to implement. >> >> Less impractical than insisting that "everybody else in the world" must >> change their posting habits to suit those using broken mail clients. > > Fortunately I haven't suggested that. Yes, I only requested that people not change the subject headers for trivial reasons, by which I meant things like fixing typos (as in the subject header change that brought about this thread). I also only intended my request in the context of this forum, which is shared between Usenet and mailing list users. Changing the subject header to indicate a change in subject is, of course, fine. From rosuav at gmail.com Mon Dec 21 19:05:56 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Dec 2015 11:05:56 +1100 Subject: Ignore error with non-zero exit status In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: On Tue, Dec 22, 2015 at 10:53 AM, Terry Reedy wrote: > Nothing has changed since except for > https://www.python.org/dev/peps/pep-0498/ > already added to 3.6. And the flip side of the argument is https://www.python.org/dev/peps/pep-0461/ in 3.5, expanding on percent formatting. Both are useful, both are supported. ChrisA From ian.g.kelly at gmail.com Mon Dec 21 19:17:24 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 21 Dec 2015 17:17:24 -0700 Subject: Ignore error with non-zero exit status In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: On Dec 21, 2015 4:55 PM, "Terry Reedy" wrote: > > Nothing has changed since except for > https://www.python.org/dev/peps/pep-0498/ > already added to 3.6. https://xkcd.com/927/ From __peter__ at web.de Mon Dec 21 19:23:51 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Dec 2015 01:23:51 +0100 Subject: In Python 3, how to append a nested dictionary to a shelve file with the added difficulty of using a for loop? References: Message-ID: Aaron Christensen wrote: > Hello, > > I am trying to figure out how to populate a shelve file with a nested > dictionary. > > These are my requirements: > > -Create shelve file called people.db > -Append the shelve file with new people (person_1, person_2, etc.). > -Use a for loop to iterate through 'attributes' so that I do not need to > write out the lengthy code line by line to populate to the shelve file. > -Need to reference shelve file data for future use > > Here is the key/value format that I would like to append to the shelve > file. > > person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': > [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, > {'game': 'bridge', 'high score': '10', 'time': '30.34'}, > {'game': 'foosball', 'high score': '2', 'time': '24'}] > ''' > 50+ other attributes > ''' > } > > # Example: s['person_1]['attributes'][2]['time'] would call out '24'. > # 's' is from 's = shelve.open('people')' > I have a dictionary dictPeople.py file (created using pprint() that > contains the information of person_1, etc. And I am extracting only a > small percentage of the data that is needed. > > I have tried the following, but I get an invalid key error. > > import shelve, dictPeople > s = shelve.open('people') > person = 'person_1' > s[person]['name'] = dictPeople.person_1['name'] > s[person]['type'] = dictPeople.person_1['type'] > # I need to use this for loop because there are 50+ attributes. > for attribute in range(0, len(dictPeople['attributes'][attribute])): > s[person]['attributes'][attribute]['game'] = \ > dictPeople['attributes'][attribute]['game'] > s[person]['attributes'][attribute]['high score'] = \ > dictPeople['attributes'][attribute]['high score'] > s[person]['attributes'][attribute]['time'] = \ > dictPeople['attributes'][attribute]['time'] > It turns out, I get the key error because I am not allowed to reference a > key/value pair the same way that I can with a dictionary. However, the > crazy thing is that I can call values in the db file using the same exact > format when trying to write. > > For example: I can read data from the .db file using: > > x = s['person_1']['name'] > print(x) > BUT! I cannot write to that .db file using that exact format or I get an > invalid key error. Makes no sense! > > s['person_1']['name'] = 'Bob' > # Returns invalid key entry. Makes no sense. > Therefore, I tried to extract data and populate the db file using the > following: > > s[person] = { 'name': dictPeople.person_1['name'], > 'type': dictPeople.person_1['type'], > for attribute in range(0, len(dictPeople['attributes'][attribute])): > ['game': dictPeople['attributes'][attribute]['game'], > 'high score': dictPeople['attributes'][attribute]['high score'], > 'time': dictPeople['attributes'][attribute]['time']] > > } > But, this obvously doesn't work because of the for loop. How can I do > this? > > -I am trying to figure out how to extract data from the dictionary > dictPeople.py file and store it in the people.db file. > -I am trying to add new people to the people.db file as more people become > available. > -I need to use the for loop because of the 50+ attributes I need to add. > -My future steps would be to modify some of the data values that I extract > and used to populate the people.db file, but my first step is to, at > least, extract, and then populate the people.db file. > > Any help or guidance is greatly appreciated. Thank you for your time and > reading my question. You don't need these loops. The problem is that when you read the dict from the db db = shelve.open(...) person = db["person_1"] person is a Python object completely independent of the shelve and the shelve has no way to trace changes to that object: $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import shelve >>> db = shelve.open("tmp.shelve") >>> person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': ... [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, ... {'game': 'bridge', 'high score': '10', 'time': '30.34'}, ... {'game': 'foosball', 'high score': '2', 'time': '24'}] ... } >>> db["person_1"] = person_1 >>> db["person_1"]["age"] = 42 >>> db.close() >>> db = shelve.open("tmp.shelve") >>> db["person_1"] {'name': 'Bob', 'type': 'employee', 'attributes': [{'time': '3.34', 'high score': '100', 'game': 'basketball'}, {'time': '30.34', 'high score': '10', 'game': 'bridge'}, {'time': '24', 'high score': '2', 'game': 'foosball'}]} When you look at the data you see that there is no "age" key. The straight- forward fix is to always use an assignment db[key] = new_value when you want a change: >>> person = db["person_1"] >>> person["age"] = 42 >>> db["person_1"] = person >>> db.close() That way the change will survive: >>> db = shelve.open("tmp.shelve") >>> db["person_1"]["age"] 42 Alternatively you can open the shelve with writeback=True: >>> db = shelve.open("tmp.shelve", writeback=True) >>> db["person_1"]["height"] = 2.0 >>> db.close() >>> db = shelve.open("tmp.shelve", writeback=True) >>> db["person_1"]["height"] 2.0 That way every value will be written back (even when you don't modify it) and therefore all mutations persist, but you pay for the convenience with superfluous caching and writing. From rosuav at gmail.com Mon Dec 21 19:25:40 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Dec 2015 11:25:40 +1100 Subject: Ignore error with non-zero exit status In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: On Tue, Dec 22, 2015 at 11:17 AM, Ian Kelly wrote: > On Dec 21, 2015 4:55 PM, "Terry Reedy" wrote: >> >> Nothing has changed since except for >> https://www.python.org/dev/peps/pep-0498/ >> already added to 3.6. > > https://xkcd.com/927/ The 927ness of it was discussed at length prior to implementation. PEP 498 isn't really another competing string format operation; it's more like an alternative expression format. It's more in competition with this: msg = "The sum of " + str(x) + " and " + str(y) + " is " + str(x+y) + "." which puts the interpolated expressions at the "correct place" in the string - but at the cost of being verbose, messy, and error-prone. Compare: msg = f"The sum of {x} and {y} is {x+y}." (Yes, there's a slight semantic difference; the latter uses format() rather than str(). But otherwise, it's compiled to the "".join(...) equivalent of the repeated concatenation example.) ChrisA From rantingrickjohnson at gmail.com Mon Dec 21 20:45:49 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 21 Dec 2015 17:45:49 -0800 (PST) Subject: Catogorising strings into random versus non-random In-Reply-To: References: <56776b9d$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4b131565-a03e-44e1-9fb3-03efb18cb8f6@googlegroups.com> On Sunday, December 20, 2015 at 10:22:57 PM UTC-6, Chris Angelico wrote: > DuckDuckGo doesn't give a result count, so I skipped it. Yahoo search yielded: So why bother to mention it then? Is this another one of your "pikeish" propaganda campaigns? From cs at zip.com.au Mon Dec 21 22:36:22 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 22 Dec 2015 14:36:22 +1100 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) In-Reply-To: <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> References: <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20151222033622.GA67382@cskk.homeip.net> On 22Dec2015 10:14, Steven D'Aprano wrote: >On Tue, 22 Dec 2015 08:44 am, Jon Ribbens wrote about mail clients that use >the Subject line to thread messages: > >> Also: Thunderbird, The Bat!, Eudora, Gnus, Outlook, Outlook Express, >> Pegasus Mail, Pine, Apple Mail, Windows Live Mail, Yahoo Mail, >> Evolution, SquirrelMail, KMail, Windows Mail, etc. > >I understand that at least some of those will only use the Subject as a >fallback when other threading information is not available. That's a >reasonable strategy to take. > >As for mail clients that *always* and *exclusively* use the subject line to >implement threading, they are horrifically broken. A big +1 here. Even as big as +2. >It is completely >unreasonable to insist that people using non-broken tools must change their >habits to support those with completely broken tools. > >So as far as I am concerned, if changes of subject line breaks threading for >you, so sad, too bad. Go without threading or use a better mail client. [...snip...] Besides, changing the Subject line is _supposed_ to break the threading in these contexts: such clients clearly consider the discussion topic (subject) as sufficient definition of a thread, and changing the topic should imply a new thread to such simplistic clients. Cheers, Cameron Simpson From aaron.christensen at gmail.com Mon Dec 21 22:56:17 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Mon, 21 Dec 2015 22:56:17 -0500 Subject: In Python 3, how to append a nested dictionary to a shelve file with the added difficulty of using a for loop? In-Reply-To: References: Message-ID: Hi Peter, Thanks for the response! Several things you stated definitely got me thinking. I really appreciate the response. I used what you said and I am able to accomplish what I needed. Thanks! Aaron On Mon, Dec 21, 2015 at 7:23 PM, Peter Otten <__peter__ at web.de> wrote: > Aaron Christensen wrote: > > > Hello, > > > > I am trying to figure out how to populate a shelve file with a nested > > dictionary. > > > > These are my requirements: > > > > -Create shelve file called people.db > > -Append the shelve file with new people (person_1, person_2, etc.). > > -Use a for loop to iterate through 'attributes' so that I do not need to > > write out the lengthy code line by line to populate to the shelve file. > > -Need to reference shelve file data for future use > > > > Here is the key/value format that I would like to append to the shelve > > file. > > > > person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': > > [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, > > {'game': 'bridge', 'high score': '10', 'time': '30.34'}, > > {'game': 'foosball', 'high score': '2', 'time': '24'}] > > ''' > > 50+ other attributes > > ''' > > } > > > > # Example: s['person_1]['attributes'][2]['time'] would call out '24'. > > # 's' is from 's = shelve.open('people')' > > I have a dictionary dictPeople.py file (created using pprint() that > > contains the information of person_1, etc. And I am extracting only a > > small percentage of the data that is needed. > > > > I have tried the following, but I get an invalid key error. > > > > import shelve, dictPeople > > s = shelve.open('people') > > person = 'person_1' > > s[person]['name'] = dictPeople.person_1['name'] > > s[person]['type'] = dictPeople.person_1['type'] > > # I need to use this for loop because there are 50+ attributes. > > for attribute in range(0, len(dictPeople['attributes'][attribute])): > > s[person]['attributes'][attribute]['game'] = \ > > dictPeople['attributes'][attribute]['game'] > > s[person]['attributes'][attribute]['high score'] = \ > > dictPeople['attributes'][attribute]['high score'] > > s[person]['attributes'][attribute]['time'] = \ > > dictPeople['attributes'][attribute]['time'] > > It turns out, I get the key error because I am not allowed to reference a > > key/value pair the same way that I can with a dictionary. However, the > > crazy thing is that I can call values in the db file using the same exact > > format when trying to write. > > > > For example: I can read data from the .db file using: > > > > x = s['person_1']['name'] > > print(x) > > BUT! I cannot write to that .db file using that exact format or I get an > > invalid key error. Makes no sense! > > > > s['person_1']['name'] = 'Bob' > > # Returns invalid key entry. Makes no sense. > > Therefore, I tried to extract data and populate the db file using the > > following: > > > > s[person] = { 'name': dictPeople.person_1['name'], > > 'type': dictPeople.person_1['type'], > > for attribute in range(0, len(dictPeople['attributes'][attribute])): > > ['game': dictPeople['attributes'][attribute]['game'], > > 'high score': dictPeople['attributes'][attribute]['high score'], > > 'time': dictPeople['attributes'][attribute]['time']] > > > > } > > But, this obvously doesn't work because of the for loop. How can I do > > this? > > > > -I am trying to figure out how to extract data from the dictionary > > dictPeople.py file and store it in the people.db file. > > -I am trying to add new people to the people.db file as more people > become > > available. > > -I need to use the for loop because of the 50+ attributes I need to add. > > -My future steps would be to modify some of the data values that I > extract > > and used to populate the people.db file, but my first step is to, at > > least, extract, and then populate the people.db file. > > > > Any help or guidance is greatly appreciated. Thank you for your time and > > reading my question. > > You don't need these loops. The problem is that when you read the dict from > the db > > db = shelve.open(...) > person = db["person_1"] > > person is a Python object completely independent of the shelve and the > shelve has no way to trace changes to that object: > > $ python3 > Python 3.4.3 (default, Oct 14 2015, 20:28:29) > [GCC 4.8.4] on linux > Type "help", "copyright", "credits" or "license" for more information. > >>> import shelve > >>> db = shelve.open("tmp.shelve") > >>> person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes': > ... [{'game': 'basketball', 'high score': '100', 'time': '3.34'}, > ... {'game': 'bridge', 'high score': '10', 'time': '30.34'}, > ... {'game': 'foosball', 'high score': '2', 'time': '24'}] > ... } > >>> db["person_1"] = person_1 > >>> db["person_1"]["age"] = 42 > >>> db.close() > >>> db = shelve.open("tmp.shelve") > >>> db["person_1"] > {'name': 'Bob', 'type': 'employee', 'attributes': [{'time': '3.34', 'high > score': '100', 'game': 'basketball'}, {'time': '30.34', 'high score': '10', > 'game': 'bridge'}, {'time': '24', 'high score': '2', 'game': 'foosball'}]} > > When you look at the data you see that there is no "age" key. The straight- > forward fix is to always use an assignment > > db[key] = new_value > > when you want a change: > > >>> person = db["person_1"] > >>> person["age"] = 42 > >>> db["person_1"] = person > >>> db.close() > > That way the change will survive: > > >>> db = shelve.open("tmp.shelve") > >>> db["person_1"]["age"] > 42 > > Alternatively you can open the shelve with writeback=True: > > >>> db = shelve.open("tmp.shelve", writeback=True) > >>> db["person_1"]["height"] = 2.0 > >>> db.close() > >>> db = shelve.open("tmp.shelve", writeback=True) > >>> db["person_1"]["height"] > 2.0 > > That way every value will be written back (even when you don't modify it) > and therefore all mutations persist, but you pay for the convenience with > superfluous caching and writing. > > -- > https://mail.python.org/mailman/listinfo/python-list > From random832 at fastmail.com Mon Dec 21 23:22:10 2015 From: random832 at fastmail.com (Random832) Date: Mon, 21 Dec 2015 23:22:10 -0500 Subject: Meaning and purpose of the Subject field References: <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> <20151222033622.GA67382@cskk.homeip.net> Message-ID: Cameron Simpson writes: > Besides, changing the Subject line is _supposed_ to break the > threading in these contexts: such clients clearly consider the > discussion topic (subject) as sufficient definition of a thread, and > changing the topic should imply a new thread to such simplistic > clients. This makes sense for the change from "old" to "new (was: old)", which nobody was advocating against (after all, there's semantic content - they wouldn't have changed the subject line if they didn't consider it a new discussion topic), but I think there is a reasonable argument that changing it a second time from "new (was: old)" to "new" is frivolous. From kai.peters at gmail.com Mon Dec 21 23:29:46 2015 From: kai.peters at gmail.com (KP) Date: Mon, 21 Dec 2015 20:29:46 -0800 (PST) Subject: Newbie XML problem Message-ID: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> >From my first foray into XML with Python: I would like to retrieve this list from the XML upon searching for the 'config' with id attribute = 'B' config = {id: 1, canvas: (3840, 1024), comment: "a comment", {id: 4, gate: 3, (0, 0, 1280, 1024)}, {id: 5, gate: 2, (1280, 0, 2560, 1024)}, {id: 6, gate: 1, (2560, 0, 3840, 1024)}} I have started to use this code - but this is beginning to feel very non-elegant; not the cool Python code I usually see... import xml.etree.ElementTree as ET tree = ET.parse('master.xml') master = tree.getroot() for config in master: if config.attrib['id'] == 'B': ... Thanks for any help! 3840,1024 "bla" 1 6 0,0,1280,1024 2 5 1280,0,2560,1024 3 4 2560,0,3840,1024 3840,1024 "a comment" 4 3 0,0,1280,1024 5 2 1280,0,2560,1024 6 1 2560,0,3840,1024 From miki.tebeka at gmail.com Tue Dec 22 00:49:43 2015 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 21 Dec 2015 21:49:43 -0800 (PST) Subject: Newbie XML problem In-Reply-To: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> References: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> Message-ID: <68e4a162-235a-4b84-9ea6-a3df001facbb@googlegroups.com> Hi, > config = {id: 1, canvas: (3840, 1024), comment: "a comment", > {id: 4, gate: 3, (0, 0, 1280, 1024)}, > {id: 5, gate: 2, (1280, 0, 2560, 1024)}, > {id: 6, gate: 1, (2560, 0, 3840, 1024)}} This is not valid Python. Are you trying to have a list of dicts? > I have started to use this code - but this is beginning to feel very non-elegant; not the cool Python code I usually see... ElementTree supports XPATH, using this and some list comprehension you do things a little more easily. For example: cfg = root.find('config[@id="B"]') for panel in cfg.findall('panel'): panels.append([{elem.tag: elem.text} for elem in panel]) You'll need to do some parsing for the coordinates and handle canvas and comments separately. HTH, Miki From no at mail.com Tue Dec 22 05:56:48 2015 From: no at mail.com (Thierry) Date: Tue, 22 Dec 2015 11:56:48 +0100 Subject: match point Message-ID: <20151222115648.1222c992@eeearch> Hi, Reading the docs about regular expressions, I am under the impression that calling re.match(pattern, string) is exactly the same as re.search(r'\A'+pattern, string) Same for fullmatch, that amounts to re.search(r'\A'+pattern+r'\Z', string) The docs devote a chapter to "6.2.5.3. search() vs. match()", but they only discuss how match() is different from search() with '^', completely eluding the case of search() with r'\A'. At first I thought those functions could have been introduced at a time when r'\A' and r'\Z' did not exist, but then I noticed that re.fullmatch is a recent addition (python 3.4) Surely the python devs are not cluttering the interface of the re module with useless functions for no reason, so what am I missing? Maybe re.match has an implementation that makes it more efficient? But then why would I ever use r'\A', since that anchor makes a pattern match in only a single position, and is therefore useless in functions like re.findall, re.finditer or re.split? Thanks, Thierry From rosuav at gmail.com Tue Dec 22 06:07:43 2015 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Dec 2015 22:07:43 +1100 Subject: match point In-Reply-To: <20151222115648.1222c992@eeearch> References: <20151222115648.1222c992@eeearch> Message-ID: On Tue, Dec 22, 2015 at 9:56 PM, Thierry wrote: > Maybe re.match has an implementation that makes it more efficient? But > then why would I ever use r'\A', since that anchor makes a pattern match > in only a single position, and is therefore useless in functions like > re.findall, re.finditer or re.split? Much of the value of regular expressions is that they are NOT string literals (just strings). Effectively, someone who has no authority to change the code of the program can cause it to change from re.search to re.match, simply by putting \A at the beginning of the search string. ChrisA From __peter__ at web.de Tue Dec 22 06:45:59 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Dec 2015 12:45:59 +0100 Subject: In Python 3, how to append a nested dictionary to a shelve file with the added difficulty of using a for loop? References: Message-ID: Aaron Christensen wrote: > Thanks for the response! Several things you stated definitely got me > thinking. I really appreciate the response. I used what you said and I > am able to accomplish what I needed. Perhaps it becomes clearer when you write two helper functions def read_record(key): return db[key] def write_record(key, value): db[key] = value Changing a person's data then becomes person_data = read_record("person_1") person_data["age"] = 123 write_record("person_1", person_data) Also, I was mostly paraphrasing >>> help(shelve) so you might read that, too. From PointedEars at web.de Tue Dec 22 07:01:41 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 22 Dec 2015 13:01:41 +0100 Subject: match point References: <20151222115648.1222c992@eeearch> Message-ID: <5716668.JdziER6HFD@PointedEars.de> Thierry wrote: > Reading the docs about regular expressions, I am under the impression > that calling > re.match(pattern, string) > is exactly the same as > re.search(r'\A'+pattern, string) Correct. > Same for fullmatch, that amounts to > re.search(r'\A'+pattern+r'\Z', string) Correct. > The docs devote a chapter to "6.2.5.3. search() vs. match()", but they > only discuss how match() is different from search() with '^', completely > eluding the case of search() with r'\A'. > > At first I thought those functions could have been introduced at a time > when r'\A' and r'\Z' did not exist, but then I noticed that re.fullmatch > is a recent addition (python 3.4) > > Maybe re.match has an implementation that makes it more efficient? But > then why would I ever use r'\A', since that anchor makes a pattern match > in only a single position, and is therefore useless in functions like > re.findall, re.finditer or re.split? (Thank you for pointing out ?\A? and ?\Z?; this strongly suggests that even in raw mode you should always match literal ?\? with the regular expression ?\\?, or IOW that you should always use re.escape() when constructing regular expressions from arbitrary strings for matching WinDOS/UNC paths, for example.) If you would use re.search(r'\Afoo.*^bar$.*baz\Z', string, flags=re.DOTALL | re.MULTILINE) you could match only strings that start with ?foo?, have a line following that which contains only ?bar?, and end with ?baz?. (In multi-line mode, the meaning of ?^? and ?$? change to start-of-line and end-of-line, respectively.) Presumably, re.fullmatch() was introduced in Python 3.4 so that you can write re.fullmatch(r'foo.*^bar$.*baz', string, flags=re.DOTALL | re.MULTILINE) instead, since you are not actually searching, and would make sure that you *always* want to match against the whole string, regardless of the expression. | Note that even in MULTILINE mode, re.match() will only match at the | beginning of the string and not at the beginning of each line. and that | re.search(pattern, string, flags=0) | Scan through string looking for the first location where the regular | expression pattern produces a match [?] So with both re.search() and re.fullmatch(), you are more flexible should the expression be dynamically constructed: you can always use re.search(). Please add your last name, Thierry #1701. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Tue Dec 22 07:17:29 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 22 Dec 2015 13:17:29 +0100 Subject: Ignore error with non-zero exit status References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <2721557.Hpeo4xmTem@PointedEars.de> <2726691.rQGQ7FqzaZ@PointedEars.de> <2827307.1DEaE21uzt@PointedEars.de> Message-ID: <2170273.ZObbXjq6a4@PointedEars.de> Terry Reedy wrote: > On 12/21/2015 9:05 AM, Thomas 'PointedEars' Lahn wrote: >> Chris Angelico wrote: >>> On Tue, Dec 22, 2015 at 12:19 AM, Thomas 'PointedEars' Lahn >>> wrote: >>>> Mark Lawrence wrote: >>>>> On 21/12/2015 07:51, Thomas 'PointedEars' Lahn wrote: >>>>>> Chris Angelico wrote: >>>>>>> But it's been clearly stated that .format is not going to do away >>>>>>> with percent formatting, and all language of "new-style formatting" >>>>>>> has been removed so as not to cause confusion. >>>>>> Wishful thinking, twice. >>>>> http://www.gossamer-threads.com/lists/python/dev/969817 >>>> What is this supposed to be evidence of? >>> Proof that percent formatting isn't planned for deprecation, much less >>> removal. >> Then it would have failed to accomplish that. >> >>> There is strong support for it in certain quarters of python-dev. [?] >> There *was*. The referred thread is from 2012-02. It is 2015-12. > > Nothing has changed since except for > https://www.python.org/dev/peps/pep-0498/ > already added to 3.6. Interesting ? and disturbing that for lack of deprecation of the other two ways we would then have *three* ways. But irrelevant evidence, again. [I do not understand why that is so hard to understand: In order to substantiate the original statement, it has to be shown *what the statement says*: that it would have been ?clearly stated that .format is not going to do away with percent formatting, and all language of "new-style formatting" has been removed so as not to cause confusion.?. Everything and anything short of showing that *fails* to constitute *relevant* evidence for that statement.] > If the 2.7 doc still implies that % -formatting is deprecated, it should > changed as in the 3.x docs. IBTD. What about ,- | | [?] | There should be one-- and preferably only one --obvious way to do it. ? -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Tue Dec 22 07:26:08 2015 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 22 Dec 2015 13:26:08 +0100 Subject: Meaning and purpose of the Subject field References: <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> <20151222033622.GA67382@cskk.homeip.net> Message-ID: <69090020.F6ufQZatfT@PointedEars.de> Random832 wrote: > This makes sense for the change from "old" to "new (was: old)", > which nobody was advocating against (after all, there's semantic > content - they wouldn't have changed the subject line if they > didn't consider it a new discussion topic), but I think there is > a reasonable argument that changing it a second time from > "new (was: old)" to "new" is frivolous. Nonsense. It is complete nonsense to carry around the old Subject for the rest of the thread. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From jeanmichel at sequans.com Tue Dec 22 07:27:33 2015 From: jeanmichel at sequans.com (jmp) Date: Tue, 22 Dec 2015 13:27:33 +0100 Subject: Newbie XML problem In-Reply-To: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> References: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> Message-ID: On 12/22/2015 05:29 AM, KP wrote: > > From my first foray into XML with Python: > > I would like to retrieve this list from the XML upon searching for the 'config' with id attribute = 'B' > > > config = {id: 1, canvas: (3840, 1024), comment: "a comment", > {id: 4, gate: 3, (0, 0, 1280, 1024)}, > {id: 5, gate: 2, (1280, 0, 2560, 1024)}, > {id: 6, gate: 1, (2560, 0, 3840, 1024)}} > > I have started to use this code - but this is beginning to feel very non-elegant; not the cool Python code I usually see... > > import xml.etree.ElementTree as ET > > tree = ET.parse('master.xml') > master = tree.getroot() > > for config in master: > if config.attrib['id'] == 'B': > ... It much depends on 1/ the xml parser you use. 2/ the xml structure 1/ I'm happily using beautifulSoup. Using it is really simple and yield simple code. 2/ Whenever the code gets complicated is because the xml is not properly structured. For instance in you example, 'id' is an attribute of 'config' nodes, that's fine, but for 'panel' nodes it's a child node. There's no point using a node when only one 'id' can be specified. Filtering by attributes is much easier than by child nodes. Anyway here's an example of using beautifulSoup: python 2.7 (fix the print statement if you're using python3) import bs4 xmlp = bs4.BeautifulSoup(open('test.xml', 'r'), 'xml') # print all canvas for cfg in xmlp.findAll('config'): print cfg.canvas.text # find config B panel 6 coordinates xmlp.find('config', id='B').find(lambda node: node.name=='panel' and node.id.text=='6').coordinates.text # if panel id were attributes: xmlp.find('config', id='B').find('panel', id='6').coordinates.text If you can change the layout of the xml file it's better that you do, put every values as attribute whenever you can: comments can span on multiple lines, you probably need a node Properly structured xml will yield proper python code. cheers, JM From muizzhasan at gmail.com Tue Dec 22 09:02:54 2015 From: muizzhasan at gmail.com (muizz hasan) Date: Tue, 22 Dec 2015 19:32:54 +0530 Subject: 0x80070570-The file or directory is corrupted and unreadable Message-ID: Hi there! I've been recently trying to install Python for Windows 10 and I've been encountering some issues. Every time i try to install the program it just says"0x80070570-The file or directory is corrupted and unreadable". I have attached my log file and i hope that you guys might enlighten me on how to solve my problem. Thank you! -------------- next part -------------- [185C:1F94][2015-12-22T19:28:35]i001: Burn v3.10.0.2103, Windows v10.0 (Build 10240: Service Pack 0), path: F:\hacks\softwares\python-3.5.1.exe [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'ActionLikeInstalling' to value 'Installing' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'ActionLikeInstallation' to value 'Setup' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'ShortVersion' to value '3.5' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'ShortVersionNoDot' to value '35' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'WinVer' to value '3.5-32' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'WinVerNoDot' to value '35-32' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'InstallAllUsers' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'InstallLauncherAllUsers' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'TargetDir' to value '' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'DefaultAllUsersTargetDir' to value '[ProgramFilesFolder]Python[WinVerNoDot]' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'TargetPlatform' to value 'x86' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'DefaultJustForMeTargetDir' to value '[LocalAppDataFolder]Programs\Python\Python[WinVerNoDot]' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'OptionalFeaturesRegistryKey' to value 'Software\Python\PythonCore\[WinVer]\InstalledFeatures' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'TargetDirRegistryKey' to value 'Software\Python\PythonCore\[WinVer]\InstallPath' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'DefaultCustomTargetDir' to value '' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'InstallAllUsersState' to value 'enabled' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'InstallLauncherAllUsersState' to value 'enabled' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'CustomInstallLauncherAllUsersState' to value '[InstallLauncherAllUsersState]' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'TargetDirState' to value 'enabled' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'CustomBrowseButtonState' to value 'enabled' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_core' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_exe' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_dev' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_lib' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_test' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_doc' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_tools' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_tcltk' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_pip' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_launcher' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'Include_launcherState' to value 'enabled' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_symbols' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Include_debug' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'LauncherOnly' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'DetectedLauncher' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'DetectedOldLauncher' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'AssociateFiles' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'Shortcuts' to value '1' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'PrependPath' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'CompileAll' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing numeric variable 'SimpleInstall' to value '0' [185C:1F94][2015-12-22T19:28:35]i000: Initializing string variable 'SimpleInstallDescription' to value '' [185C:1F94][2015-12-22T19:28:35]i009: Command Line: '' [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835.log' [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'WixBundleOriginalSource' to value 'F:\hacks\softwares\python-3.5.1.exe' [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'WixBundleOriginalSourceFolder' to value 'F:\hacks\softwares\' [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'WixBundleName' to value 'Python 3.5.1 (32-bit)' [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'WixBundleManufacturer' to value 'Python Software Foundation' [185C:1F94][2015-12-22T19:28:35]i000: Setting numeric variable 'CRTInstalled' to value 1 [185C:26B0][2015-12-22T19:28:35]i000: Did not find F:\hacks\softwares\unattend.xml [185C:26B0][2015-12-22T19:28:35]i000: Setting string variable 'ActionLikeInstalling' to value 'Installing' [185C:26B0][2015-12-22T19:28:35]i000: Setting string variable 'ActionLikeInstallation' to value 'Setup' [185C:26B0][2015-12-22T19:28:35]i000: Setting version variable 'WixBundleFileVersion' to value '3.5.1150.0' [185C:26B0][2015-12-22T19:28:35]e000: Target OS is Windows 7 SP1 or later [185C:1F94][2015-12-22T19:28:35]i100: Detect begin, 58 packages [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.0_x86, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.0_x64, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.1_x86, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.1_x64, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.2_x86, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.2_x64, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.3_x86, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: crt_14.0_v6.3_x64, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_AllUsers_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_JustForMe_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: core_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: dev_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: dev_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: dev_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: dev_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: exe_AllUsers, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: exe_AllUsers, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_AllUsers_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: exe_JustForMe, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: exe_JustForMe, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_JustForMe_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: exe_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_AllUsers_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_JustForMe_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: lib_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_AllUsers_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_JustForMe_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: test_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: doc_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: doc_AllUsers, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: doc_AllUsers, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: doc_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: doc_JustForMe, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: doc_JustForMe, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tools_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tools_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_AllUsers, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_AllUsers, feature: AssociateFiles, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_AllUsers, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_AllUsers_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_AllUsers_pdb, feature: Symbols, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_AllUsers_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_AllUsers_d, feature: DebugBinaries, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_JustForMe, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_JustForMe, feature: AssociateFiles, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_JustForMe, feature: Shortcuts, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_JustForMe_pdb, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_JustForMe_pdb, feature: Symbols, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: tcltk_JustForMe_d, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: tcltk_JustForMe_d, feature: DebugBinaries, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: launcher_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: launcher_AllUsers, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: launcher_AllUsers, feature: AssociateFiles, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: launcher_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i104: Detected package: launcher_JustForMe, feature: DefaultFeature, state: Absent [185C:1F94][2015-12-22T19:28:35]i104: Detected package: launcher_JustForMe, feature: AssociateFiles, state: Absent [185C:1F94][2015-12-22T19:28:35]i101: Detected package: pip_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: pip_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: path_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: path_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileall_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileallO_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileallOO_AllUsers, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileall_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileallO_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i101: Detected package: compileallOO_JustForMe, state: Absent, cached: None [185C:1F94][2015-12-22T19:28:35]i000: Setting string variable 'TargetDir' to value 'C:\Users\i\AppData\Local\Programs\Python\Python35-32' [185C:1F94][2015-12-22T19:28:35]i199: Detect complete, result: 0x0 [185C:26B0][2015-12-22T19:28:35]i052: Condition 'not WixBundleElevated and (InstallAllUsers or (Include_launcher and InstallLauncherAllUsers and not DetectedLauncher))' evaluates to true. [185C:26B0][2015-12-22T19:28:36]i000: Setting numeric variable 'InstallLauncherAllUsers' to value 1 [185C:26B0][2015-12-22T19:28:36]i000: Setting numeric variable 'PrependPath' to value 0 [185C:26B0][2015-12-22T19:28:36]i052: Condition 'not WixBundleElevated and (InstallAllUsers or (Include_launcher and InstallLauncherAllUsers and not DetectedLauncher))' evaluates to true. [185C:26B0][2015-12-22T19:28:36]i000: Setting numeric variable 'CompileAll' to value 0 [185C:26B0][2015-12-22T19:28:36]i000: Setting string variable 'ActionLikeInstalling' to value 'Installing' [185C:26B0][2015-12-22T19:28:36]i000: Setting string variable 'ActionLikeInstallation' to value 'Setup' [185C:1F94][2015-12-22T19:28:36]i200: Plan begin, 58 packages, action: Install [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.0 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.0 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.0_x86 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.0 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.0 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.0_x64 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.1 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.1 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.1_x86 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.1 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.1 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.1_x64 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.2 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.2 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.2_x86 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.2 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.2 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.2_x64 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.3 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT = v6.3 and not VersionNT64 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.3_x86 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.3 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not CRTInstalled and VersionNT64 = v6.3 and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: crt_14.0_v6.3_x64 [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: core_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: core_AllUsers_pdb, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: core_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_core_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_000_core_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_core_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_000_core_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_core or Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_dev and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_dev and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: dev_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_dev and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_dev and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: dev_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_dev and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_dev and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_dev_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_001_dev_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_dev_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_001_dev_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_dev and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_dev and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: exe_AllUsers [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: exe_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: exe_AllUsers_pdb, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: exe_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: exe_JustForMe [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_exe_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_002_exe_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_exe_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_002_exe_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and (Include_exe or Include_launcher or Include_pip) and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: lib_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: lib_AllUsers_pdb, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_lib and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: lib_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_lib_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_003_lib_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_lib_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_003_lib_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_lib and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: test_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: test_AllUsers_pdb, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_test and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: test_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_test_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_004_test_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_test_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_004_test_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_test and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_doc and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_doc and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: doc_AllUsers [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: doc_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_doc and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_doc and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: doc_JustForMe [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_doc_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_005_doc_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_doc_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_005_doc_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tools and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tools and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: tools_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tools and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tools and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_tools_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_006_tools_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_tools_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_006_tools_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 3 msi features for package: tcltk_AllUsers [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: AssociateFiles, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: tcltk_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 1 msi features for package: tcltk_AllUsers_pdb [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Symbols, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: tcltk_AllUsers_pdb, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_tcltk and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 1 msi features for package: tcltk_AllUsers_d [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DebugBinaries, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: tcltk_AllUsers_d, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i204: Plan 3 msi features for package: tcltk_JustForMe [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: AssociateFiles, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Shortcuts, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_tcltk_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_007_tcltk_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_tcltk_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_007_tcltk_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and Include_symbols and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 1 msi features for package: tcltk_JustForMe_pdb [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: Symbols, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_tcltk and Include_debug and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 1 msi features for package: tcltk_JustForMe_d [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DebugBinaries, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i052: Condition '(InstallAllUsers or InstallLauncherAllUsers) and Include_launcher and not DetectedLauncher' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition '(InstallAllUsers or InstallLauncherAllUsers) and Include_launcher and not DetectedLauncher' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: launcher_AllUsers [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: AssociateFiles, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: launcher_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_launcher_AllUsers' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_008_launcher_AllUsers.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not (InstallAllUsers or InstallLauncherAllUsers) and Include_launcher and not DetectedLauncher' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not (InstallAllUsers or InstallLauncherAllUsers) and Include_launcher and not DetectedLauncher' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i204: Plan 2 msi features for package: launcher_JustForMe [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: DefaultFeature, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i203: Planned feature: AssociateFiles, state: Absent, default requested: Unknown, ba requested: Local, execute action: AddLocal, rollback action: Remove [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_pip and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and Include_pip and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: pip_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_pip and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and Include_pip and not LauncherOnly' evaluates to true. [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleRollbackLog_pip_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_009_pip_JustForMe_rollback.log' [185C:1F94][2015-12-22T19:28:36]i000: Setting string variable 'WixBundleLog_pip_JustForMe' to value 'C:\Users\i\AppData\Local\Temp\Python 3.5.1 (32-bit)_20151222192835_009_pip_JustForMe.log' [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and PrependPath and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and PrependPath and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w322: Skipping cross-scope dependency registration on package: path_AllUsers, bundle scope: PerUser, package scope: PerMachine [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and PrependPath and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and PrependPath and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileall_AllUsers [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileallO_AllUsers [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileallOO_AllUsers [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileall_JustForMe [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileallO_JustForMe [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]i052: Condition 'not InstallAllUsers and CompileAll and not LauncherOnly' evaluates to false. [185C:1F94][2015-12-22T19:28:36]w321: Skipping dependency registration on package with no dependency providers: compileallOO_JustForMe [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.0_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.0_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.1_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.1_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.2_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.2_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.3_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: crt_14.0_v6.3_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_AllUsers_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_JustForMe_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: core_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: dev_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: dev_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: dev_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: dev_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_AllUsers_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_JustForMe_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: exe_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_AllUsers_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_JustForMe_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: lib_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_AllUsers_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_JustForMe_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: test_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: doc_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: doc_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tools_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tools_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_AllUsers_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_AllUsers_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_JustForMe_pdb, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: tcltk_JustForMe_d, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: launcher_AllUsers, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: None, cache: Yes, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: launcher_JustForMe, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: pip_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: pip_JustForMe, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: Register [185C:1F94][2015-12-22T19:28:36]i201: Planned package: path_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: path_JustForMe, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileall_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileallO_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileallOO_AllUsers, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileall_JustForMe, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileallO_JustForMe, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i201: Planned package: compileallOO_JustForMe, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None [185C:1F94][2015-12-22T19:28:36]i299: Plan complete, result: 0x0 [185C:1F94][2015-12-22T19:28:36]i300: Apply begin [185C:1F94][2015-12-22T19:28:36]i010: Launching elevated engine process. [185C:1F94][2015-12-22T19:28:38]i011: Launched elevated engine process. [185C:1F94][2015-12-22T19:28:38]i012: Connected to elevated engine. [1630:24C4][2015-12-22T19:28:38]i358: Pausing automatic updates. [1630:24C4][2015-12-22T19:28:38]i359: Paused automatic updates. [1630:24C4][2015-12-22T19:28:38]i360: Creating a system restore point. [1630:24C4][2015-12-22T19:28:38]i361: Created a system restore point. [185C:1F94][2015-12-22T19:28:38]i370: Session begin, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{c39d559b-aa83-4476-ba20-988a35a1199a}, options: 0x7, disable resume: No [185C:1F94][2015-12-22T19:28:38]i000: Caching bundle from: 'C:\Users\i\AppData\Local\Temp\{c39d559b-aa83-4476-ba20-988a35a1199a}\.be\python-3.5.1.exe' to: 'C:\Users\i\AppData\Local\Package Cache\{c39d559b-aa83-4476-ba20-988a35a1199a}\python-3.5.1.exe' [185C:1F94][2015-12-22T19:28:38]i320: Registering bundle dependency provider: {c39d559b-aa83-4476-ba20-988a35a1199a}, version: 3.5.1150.0 [185C:1F94][2015-12-22T19:28:38]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{c39d559b-aa83-4476-ba20-988a35a1199a}, resume: Active, restart initiated: No, disable resume: No [185C:1C18][2015-12-22T19:28:38]i336: Acquiring container: WixAttachedContainer, copy from: F:\hacks\softwares\python-3.5.1.exe [185C:1C18][2015-12-22T19:28:38]i000: Setting string variable 'WixBundleLastUsedSource' to value 'F:\hacks\softwares\' [185C:0C90][2015-12-22T19:28:38]e000: Error 0x80070570: Failed to extract all files from container, erf: 1:4:0 [185C:1C18][2015-12-22T19:28:38]e000: Error 0x80070570: Failed to begin and wait for operation. [185C:1C18][2015-12-22T19:28:38]e000: Error 0x80070570: Failed to extract payload: a15 from container: WixAttachedContainer [185C:1C18][2015-12-22T19:28:38]e312: Failed to extract payloads from container: WixAttachedContainer to working path: C:\Users\i\AppData\Local\Temp\{c39d559b-aa83-4476-ba20-988a35a1199a}\8696D6566A8C0F3C98B7A2362AE180027F79F673, error: 0x80070570. [185C:1F94][2015-12-22T19:28:38]e000: Error 0x80070570: Cache thread exited unexpectedly. [185C:1F94][2015-12-22T19:28:38]i372: Session end, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{c39d559b-aa83-4476-ba20-988a35a1199a}, resume: ARP, restart: None, disable resume: No [185C:1F94][2015-12-22T19:28:38]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{c39d559b-aa83-4476-ba20-988a35a1199a}, resume: ARP, restart initiated: No, disable resume: No [185C:1F94][2015-12-22T19:28:38]i399: Apply complete, result: 0x80070570, restart: None, ba requested restart: No From denismfmcmahon at gmail.com Tue Dec 22 09:12:43 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 22 Dec 2015 14:12:43 -0000 (UTC) Subject: What could cause a plot fail in my code? References: <22c809c7-3aaf-4439-b919-8de982d7ffc9@googlegroups.com> Message-ID: On Mon, 21 Dec 2015 09:15:38 -0800, Robert wrote: > Hi, > > I find a useful code snippet on link: > > http://stackoverflow.com/questions/25126444/logistic-regression-in- pymc/34400966#34400966 > > but it has error on plot function. The error message is as following: > 6192 ymin = np.amin(m[m != 0]) > 6193 # filter out the 0 height bins > -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty > else minimum > 6195 ymin = min(ymin0, ymin) > 6196 self.dataLim.intervaly = (ymin, ymax) > > UnboundLocalError: local variable 'ymin' referenced before assignment > ///////////// > > I have no clue at all on debug it. Could you help me? > Thanks, It looks as if ymin may be defined in a conditional block, and you've managed to reach line 6194 without going through that block. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Tue Dec 22 09:23:33 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 22 Dec 2015 14:23:33 -0000 (UTC) Subject: return from function References: Message-ID: On Sun, 20 Dec 2015 12:34:40 +0000, Emil Natan wrote: > I'm completely new to Python. > parent_domain = domainname.partition('.')[2] > try: > print('Test for parent domain %s' % parent_domain) > z = dns.resolver.query(parent_domain, 'SOA') > print('the parent domain we use is: %s' % parent_domain) > return parent_domain > except dns.resolver.NXDOMAIN: > print('NXDOMAIN: invoke find_parent_domain recursively') > find_parent_domain(parent_domain) None is being returned in this case! > except dns.resolver.NoAnswer: > print('NoAnswer: invoke find_parent_domain recursively') > find_parent_domain(parent_domain) And in this case. Do you want to return None in the NXDOMAIN and NoAnswer cases? If not, a return statement might help in returning a value. When you recurse back into a function you still need to return the result of the recursion. -- Denis McMahon, denismfmcmahon at gmail.com From invalid at invalid.invalid Tue Dec 22 10:14:55 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 22 Dec 2015 15:14:55 +0000 (UTC) Subject: Library function to encode data to multipart/form-data format? References: Message-ID: On 2015-12-21, Laura Creighton wrote: > In a message of Mon, 21 Dec 2015 17:51:00 +0000, Grant Edwards writes: >>Is there a standard library function that can be used to encode data >>into multipart/form-data format? IIRC, I looked for this once before >>and didn't find anything in the library. [...] > Cannibalise this: > http://code.activestate.com/recipes/146306/ > which just uses standard library things. Yep, that's what I ended up doing. I noticed that the code referenced above doesn't check to make sure the boundary string is not contained in the data, so I fixed that. -- Grant Edwards grant.b.edwards Yow! I'm gliding over a at NUCLEAR WASTE DUMP near gmail.com ATLANTA, Georgia!! From invalid at invalid.invalid Tue Dec 22 10:17:52 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 22 Dec 2015 15:17:52 +0000 (UTC) Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2015-12-21, Steven D'Aprano wrote: > So as far as I am concerned, if changes of subject line breaks threading for > you, so sad, too bad. Go without threading or use a better mail client. Same here. After getting what is effectively a "F*&# Y*& I'm too lazy to do things right" from multiple people every day for the past 20 years, I think they deserve to be treated with equal respect. -- Grant Edwards grant.b.edwards Yow! I'm thinking about at DIGITAL READ-OUT systems gmail.com and computer-generated IMAGE FORMATIONS ... From vincent at vincentdavis.net Tue Dec 22 10:27:05 2015 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 22 Dec 2015 09:27:05 -0600 Subject: unicodedata with chr() not the same between python 3.4 and 3.5 Message-ID: ?I was expecting the code below to be the same between python3.4 and 3.5. I need a mapping between the integers and unicode that is consistant between 3.4 and 3.5 >>> import unicodedata >>> u = ''.join(chr(i) for i in range(65536) if (unicodedata.category(chr(i)) in ('Lu', 'Ll')))[945:965] >>> u '????????????????????' Python 3.4 >>> import unicodedata >>> u = ''.join(chr(i) for i in range(65536) if (unicodedata.category(chr(i)) in ('Lu', 'Ll')))[945:965] >>> u '????????????????????' As you can see they are not the same ?.? '????????????????????' '????????????????????' Vincent Davis 720-301-3003 From ian.g.kelly at gmail.com Tue Dec 22 10:28:43 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 22 Dec 2015 08:28:43 -0700 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Dec 22, 2015 at 8:17 AM, Grant Edwards wrote: > On 2015-12-21, Steven D'Aprano wrote: > >> So as far as I am concerned, if changes of subject line breaks threading for >> you, so sad, too bad. Go without threading or use a better mail client. > > Same here. After getting what is effectively a "F*&# Y*& I'm too lazy > to do things right" from multiple people every day for the past 20 > years, I think they deserve to be treated with equal respect. Can you elaborate? If there's something I could be doing better in my communications, I'm happy to entertain it. From rosuav at gmail.com Tue Dec 22 10:42:11 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Dec 2015 02:42:11 +1100 Subject: unicodedata with chr() not the same between python 3.4 and 3.5 In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 2:27 AM, Vincent Davis wrote: > I was expecting the code below to be the same between python3.4 and 3.5. I > need a mapping between the integers and unicode that is consistant between > 3.4 and 3.5 > >>>> > import unicodedata >>>> > u = ''.join(chr(i) for i in range(65536) if (unicodedata.category(chr(i)) > in ('Lu', 'Ll')))[945:965] Not sure why you're slicing it like this, but it makes little difference. The significant thing here is that the newer Pythons are shipping newer Unicode data files, and some code points have changed category. rosuav at sikorsky:~$ python3.4 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. >>> import unicodedata >>> unicodedata.unidata_version '6.3.0' >>> rosuav at sikorsky:~$ python3.5 Python 3.5.0b1+ (default:7255af1a1c50+, May 26 2015, 00:39:06) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import unicodedata >>> unicodedata.unidata_version '7.0.0' >>> rosuav at sikorsky:~$ python3.6 Python 3.6.0a0 (default:6e114c4023f5, Dec 20 2015, 19:15:28) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import unicodedata >>> unicodedata.unidata_version '8.0.0' >>> Have a read here of what changed in those two major versions: http://unicode.org/versions/Unicode7.0.0/ http://unicode.org/versions/Unicode8.0.0/ I'm not sure what the best way is to create the mapping you want, but I would advise freezing it to a specific set of codepoints in your source code, rather than depending on something external. ChrisA From skybuck2000 at hotmail.com Tue Dec 22 10:46:28 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Tue, 22 Dec 2015 16:46:28 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: "Richard Damon" wrote in message news:QXSdy.6634$QG6.5135 at fx31.iad... On 12/21/15 7:40 AM, Skybuck Flying wrote: > The original idea I posted is less about sending a signal to another > processor. > > It is more about how to break out of an instruction sequence. > > Example of problem: [snip] > Bye, > Skybuck. " The issue is that if your threads are doing real work, the cleanup needed at each point keep the environment clean for other threads likely varies. Just arbitrarily stopping or blindly going off to something else is very apt to create problems. Some languages can be better at automatically cleaning up for you, these will tend to be languages that support some form of exception processing, as that tends to need similar support. You abort can be treated as a type of exception that is automatically thrown when signaled. The problem here is that most programs, while they can handle exceptions in many spots, have some spots where exceptions will cause problems, especially in code that is directly managing the resources. Thus, you still need to have some definition of where to check for the breaks. " I can imagine that arbitrarily terminating somewhere can lead to problems for example in memory clean up code, where then memory leaks might occur. Though applications do sometimes seem to clean up anyway. One idea which immediatly comes to mind to fix this problem is to offer a "PushTerminationFlag" onto stack and then a "ClearTerminationFlag" instruction. Then a code section can be executed without breaking or terminating. Once that's done the code would then call "PopTerminationFlag". At least this offers some protection against arbitrarely breaking code sections. Bye, Skybuck. From python.list at tim.thechases.com Tue Dec 22 10:56:21 2015 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 22 Dec 2015 09:56:21 -0600 Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) In-Reply-To: References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20151222095621.53c6e2d2@bigbox.christie.dr> On 2015-12-21 23:24, Jon Ribbens wrote: > That sounds a bit confused - if the *intention* of changing the > subject line is to create a new thread, then breaking the thread > is not "breaking threading" ;-) I'm pretty sure that the purpose is not to *break* the thread, but to suggest that the sub-thread's topic has shifted away that of the parent thread. -tkc From rosuav at gmail.com Tue Dec 22 10:56:51 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Dec 2015 02:56:51 +1100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: On Wed, Dec 23, 2015 at 2:46 AM, Skybuck Flying wrote: > One idea which immediatly comes to mind to fix this problem is to offer a > "PushTerminationFlag" onto stack and then a "ClearTerminationFlag" > instruction. > > Then a code section can be executed without breaking or terminating. > > Once that's done the code would then call "PopTerminationFlag". > > At least this offers some protection against arbitrarely breaking code > sections. Congratulations! You've just rediscovered 'critical sections'. So... what happens if there's a programming bug that means you fail to pop the termination flag? Wouldn't it be so nice if you could use... exception handling? Here on python-list/comp.lang.python, we have all those high level facilities. We don't need new CPU-level features to make this work. Are you massively cross-posting? Either way, this is pretty off-topic for here. Read up a bit on what's already been done (most of what you're talking about was already solved back in the 1990s when I was programming on OS/2, and I'm pretty sure the solutions were all lifted directly from mainframe research in previous decades), or just use high level languages and save yourself a boatload of trouble. ChrisA From eryksun at gmail.com Tue Dec 22 11:44:53 2015 From: eryksun at gmail.com (eryk sun) Date: Tue, 22 Dec 2015 10:44:53 -0600 Subject: 0x80070570-The file or directory is corrupted and unreadable In-Reply-To: References: Message-ID: On Tue, Dec 22, 2015 at 8:02 AM, muizz hasan wrote: > Hi there! I've been recently trying to install Python for Windows 10 > and I've been encountering some issues. Every time i try to install > the program it just says"0x80070570-The file or directory is corrupted > and unreadable". I have attached my log file and i hope that you guys > might enlighten me on how to solve my problem. Thank you! Try downloading a new copy of the installer. Clear your browser cache first. From no at mail.com Tue Dec 22 12:18:25 2015 From: no at mail.com (Thierry Closen) Date: Tue, 22 Dec 2015 18:18:25 +0100 Subject: match point References: <20151222115648.1222c992@eeearch> Message-ID: <20151222181825.67b87012@eeearch> I found the story behind the creation of re.fullmatch(). I had no luck before because I was searching under "www.python.org/dev", while in reality it sprang out of a bug report: https://bugs.python.org/issue16203 In summary, there were repeated bugs where during maintenance of code the $ symbol disappeared from patterns, hence the decision to create a function that anchors the pattern to the end of the string independently of the presence of that symbol. I am perplexed by what I discovered, as I would never have thought that such prominent functions can be created to scratch such a minor itch: The creation of fullmatch() might address this very specific issue, but I would tend to think that if really certain symbols disappear from patterns inside a code base, this should be seen as the sign of more profound problems in the code maintenance processes. Anyway, the discussion around that bug inspired me another argument that is more satisfying: When I was saying that re.fullmatch(pattern, string) is exactly the same as re.search(r'\A'+pattern+r'\Z', string) I was wrong. For example if pattern starts with an inline flag like (?i), we cannot simply stick \A in front of it. Other example, consider pattern is 'a|b'. We end up with: re.search(r'\Aa|b\Z', string) which is not what we want. To avoid that problem we need to add parentheses: re.search(r'\A('+pattern+r')\Z', string) But now we created a group, and if the pattern already contained groups and backreferences we may just have broken it. So we need to use a non-capturing group: re.search(r'\A(?:'+pattern+r')\Z', string) ...and now I think we can say we are at a level of complexity where we cannot reasonably expect the average user to always remember to write exactly this, so it makes sense to add an easy-to-use fullmatch function to the re namespace. It may not be the real historical reason behind re.fullmatch, but personally I will stick with that one :) Cheers, Thierry From arresteddevlopment at tuta.io Tue Dec 22 12:40:41 2015 From: arresteddevlopment at tuta.io (arresteddevlopment at tuta.io) Date: Tue, 22 Dec 2015 17:40:41 +0000 (UTC) Subject: How to use a variable to act as @rule in a Sopel IRC bot module? Message-ID: Hi everyone. I'm working with the Sopel (previously Willie and before that, Jenni/Phenny) python IRC bot as I'd like to set up a trivia quiz for our IRC channel. With Sopel, the @rule decorator lets you set a string that the bot will listen out for and which triggers a corresponding function when encountered. So for the quiz I'd like the bot to confirm a correct answer by saying "Correctamundo!" when someone gets the question right. A. The first thing I tried was a nested function. After choosing a random question from the q_and_as tuples list, it sets the answer (q[1]) as the rule that should trigger the correct() function. from sopel.module import commands, ruleimport randomq_and_as = [('Why?', 'because'), ('Can I kick it?', 'nope')]@commands("quizme")def ask_q(bot, trigger): q = random.choice(q_and_as) bot.say(q[0]) @rule(q[1]) def correct(bot, trigger): bot.sat('Correctamundo!') For whatever reason the answer isn't triggering the correct() function when done this way. B. I also tried passing the answer (q[1]) to a separate answer function, which would then set it as the rule that triggered the correct() function. from sopel.module import commands, ruleimport randomq_and_as = [('Why?', 'because'), ('Can I kick it?', 'nope')]@commands("quizme")def ask_q(bot, trigger): q = random.choice(q_and_as) bot.say(q[0]) answer(bot, trigger, q[1])def answer(bot, trigger, answer): @rule(answer) def correct(bot, trigger): bot.say(' correctamundo!') Again though, the function isn't being triggered. Any ideas where I'm going wrong? Or is there a better way of doing this? Thank you. From eryksun at gmail.com Tue Dec 22 13:58:43 2015 From: eryksun at gmail.com (eryk sun) Date: Tue, 22 Dec 2015 12:58:43 -0600 Subject: 0x80070570-The file or directory is corrupted and unreadable In-Reply-To: References: Message-ID: On Tue, Dec 22, 2015 at 11:51 AM, Dennis Lee Bieber wrote: > > http://www.tech-faq.com/how-to-fix-error-0x80070570.html > suggests a registry cleaner (my preference over downloading some > unknown/unvetted "repair" tool) > > Most of the links on Google are for getting the error when installing > Win7 itself. The log says "Error 0x80070570: Failed to extract all files from container, erf: 1:4:0". 0x80070570 is a failure code for the Windows API (facility code 7) with the error value ERROR_FILE_CORRUPT (0x0570). The simplest recourse at this point is to clear the browser cache and download the installer again. Here's a program from Microsoft to check MD5 sums. You can copy fciv.exe to the Windows directory. https://www.microsoft.com/en-us/download/details.aspx?id=11533 Then verify that the MD5 sum is 4d6fdb5c3630cf60d457c9825f69b4d7, as posted on python.org: >fciv python-3.5.1.exe // // File Checksum Integrity Verifier version 2.05. // 4d6fdb5c3630cf60d457c9825f69b4d7 python-3.5.1.exe Of course, the file could be fine and this error could be just a symptom of another problem. From kai.peters at gmail.com Tue Dec 22 14:03:33 2015 From: kai.peters at gmail.com (KP) Date: Tue, 22 Dec 2015 11:03:33 -0800 (PST) Subject: Newbie XML problem In-Reply-To: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> References: <3d2e5064-9cc0-43de-a708-faf528a795ca@googlegroups.com> Message-ID: Thank you both - your help is much appreciated! From norouzey at gmail.com Tue Dec 22 14:06:17 2015 From: norouzey at gmail.com (norouzey at gmail.com) Date: Tue, 22 Dec 2015 11:06:17 -0800 (PST) Subject: imshow keeps crashhing Message-ID: Hello everyone, Can anyone please help me with "imshow"? I have tried "imshow" on different computers and different Python consoles but it does not work. Here are the code and the error message: import scipy.misc as mi img = mi.imread('C:\images\circles.png') mi.imshow(img) 'see' is not recognized as an internal or external command, operable program or batch file. Traceback (most recent call last): File "", line 1, in File "C:\...\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "C:\...\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/.../.spyder2/temp.py", line 11, in mi.imshow(img) File "C:\...\Anaconda2\lib\site-packages\scipy\misc\pilutil.py", line 389, in imshow raise RuntimeError('Could not execute image viewer.') RuntimeError: Could not execute image viewer. Thanks a lot for your time. Ahmad From gordon at panix.com Tue Dec 22 14:19:45 2015 From: gordon at panix.com (John Gordon) Date: Tue, 22 Dec 2015 19:19:45 +0000 (UTC) Subject: imshow keeps crashhing References: Message-ID: In norouzey at gmail.com writes: > Can anyone please help me with "imshow"? I have tried "imshow" on different computers and different Python consoles but it does not work. Here are the code and the error message: > import scipy.misc as mi > img = mi.imread('C:\images\circles.png') > mi.imshow(img) > 'see' is not recognized as an internal or external command, > operable program or batch file. scipy calls an external image viewer program to display the image. The name of this program is stored in the environment variable SCIPY_PIL_IMAGE_VIEWER. If that variable is not present, it uses 'see' by default. Do you have a suitable image viewing program installed on your computer? If so, try setting the SCIPY_PIL_IMAGE_VIEWER environment variable to the name of that program. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From nmcelwaine at gmail.com Tue Dec 22 15:27:32 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Tue, 22 Dec 2015 20:27:32 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD Message-ID: I have run the install (and repair) which explicitly includes Tcl/Tk and l have this problem: Microsoft Windows [Version 10.0.10586] (c) 2015 Microsoft Corporation. All rights reserved. > C:\Python\Python35\python.exe -m idlelib ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** Please suggest how this can be fixed any support greatly appreciated Nick McElwaine From kai.peters at gmail.com Tue Dec 22 15:53:45 2015 From: kai.peters at gmail.com (KP) Date: Tue, 22 Dec 2015 12:53:45 -0800 (PST) Subject: Newbie: String to Tuple Message-ID: <56576725-0f10-4c7b-aead-272f2e3a8456@googlegroups.com> How do I convert '1280,1024' to (1280,1024) ? Thanks for all help! From breamoreboy at yahoo.co.uk Tue Dec 22 15:59:21 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 22 Dec 2015 20:59:21 +0000 Subject: Newbie: String to Tuple In-Reply-To: <56576725-0f10-4c7b-aead-272f2e3a8456@googlegroups.com> References: <56576725-0f10-4c7b-aead-272f2e3a8456@googlegroups.com> Message-ID: On 22/12/2015 20:53, KP wrote: > How do I convert > > '1280,1024' > > to > > (1280,1024) ? > > Thanks for all help! > Start with this https://docs.python.org/3/library/stdtypes.html#str.split -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From kai.peters at gmail.com Tue Dec 22 16:06:32 2015 From: kai.peters at gmail.com (KP) Date: Tue, 22 Dec 2015 13:06:32 -0800 (PST) Subject: Newbie: String to Tuple In-Reply-To: References: <56576725-0f10-4c7b-aead-272f2e3a8456@googlegroups.com> Message-ID: On Tuesday, 22 December 2015 12:59:59 UTC-8, Mark Lawrence wrote: > On 22/12/2015 20:53, KP wrote: > > How do I convert > > > > '1280,1024' > > > > to > > > > (1280,1024) ? > > > > Thanks for all help! > > > > Start with this https://docs.python.org/3/library/stdtypes.html#str.split > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence Thanks - just what I was missing! From __peter__ at web.de Tue Dec 22 16:07:41 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Dec 2015 22:07:41 +0100 Subject: Newbie: String to Tuple References: <56576725-0f10-4c7b-aead-272f2e3a8456@googlegroups.com> Message-ID: KP wrote: > How do I convert > > '1280,1024' > > to > > (1280,1024) ? >>> import ast >>> ast.literal_eval('1280,1024') (1280, 1024) From arresteddevlopment at tuta.io Tue Dec 22 16:19:32 2015 From: arresteddevlopment at tuta.io (arresteddevlopment at tuta.io) Date: Tue, 22 Dec 2015 21:19:32 +0000 (UTC) Subject: How to use a variable to act as @rule in a Sopel IRC bot module? Message-ID: Apologies for the terrible formatting, let me try that again: A: from sopel.module import commands, rule import random q_and_as = [('Why?', 'because'), ('Can I kick it?', 'nope')] @commands("quizme") def ask_q(bot, trigger): q = random.choice(q_and_as) bot.say(q[0]) ?@rule(q[1]) ?def correct(bot, trigger): bot.sat('Correctamundo!') B: ... @commands("quizme") def ask_q(bot, trigger): q = random.choice(q_and_as) ?bot.say(q[0]) answer(bot, trigger, q[1]) def answer(bot, trigger, answer): @rule(answer) def correct(bot, trigger): bot.say(' correctamundo!') If the above comes out wonky again I also asked on StackOverflow (http://stackoverflow.com/questions/34419265/how-to-set-and-later-change-a-rule-in-a-sopel-irc-bot-module-python). Any help would be greatly appreciated. From tjreedy at udel.edu Tue Dec 22 16:44:43 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Dec 2015 16:44:43 -0500 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On 12/22/2015 3:27 PM, Nicky Mac wrote: > I have run the install (and repair) which explicitly includes Tcl/Tk and l > have this problem: First, I would download and install the final 3.5.1. I believe there was a change to the installer that might, possibly, make a difference. Write down exactly the install options you choose. >> C:\Python\Python35\python.exe -m idlelib > ** IDLE can't import Tkinter. > Your Python may not be configured for Tk. ** Then run python -m tkinter to remove IDLE from the issue. If problem persists, report again. > Please suggest how this can be fixed > any support greatly appreciated -- Terry Jan Reedy From invalid at invalid.invalid Tue Dec 22 17:32:46 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 22 Dec 2015 22:32:46 +0000 (UTC) Subject: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status) References: <3883651.fOIMIIEhYO@PointedEars.de> <2062582.Z8LLNUJk5W@PointedEars.de> <85oadj1pta.fsf_-_@benfinney.id.au> <567887f2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2015-12-22, Ian Kelly wrote: > On Tue, Dec 22, 2015 at 8:17 AM, Grant Edwards wrote: >> On 2015-12-21, Steven D'Aprano wrote: >> >>> So as far as I am concerned, if changes of subject line breaks threading for >>> you, so sad, too bad. Go without threading or use a better mail client. >> >> Same here. After getting what is effectively a "F*&# Y*& I'm too lazy >> to do things right" from multiple people every day for the past 20 >> years, I think they deserve to be treated with equal respect. > > Can you elaborate? If there's something I could be doing better in my > communications, I'm happy to entertain it. I was talking about the general case of people who top-post, send html-only, misidentified charsets, incorrect file types, attach all sorts of company logos, "intendended-recipient" boilerplate, and so on. Once in a while, you just can't take it any longer and have to do "the right thing" and let all the people with broken MUAs, NNTP clients, or brains deal with it... -- Grant Edwards grant.b.edwards Yow! Somewhere in DOWNTOWN at BURBANK a prostitute is gmail.com OVERCOOKING a LAMB CHOP!! From kai.peters at gmail.com Tue Dec 22 18:14:57 2015 From: kai.peters at gmail.com (KP) Date: Tue, 22 Dec 2015 15:14:57 -0800 (PST) Subject: Newbie: Convert strings in nested dict to tuples Message-ID: I now know how to convert a string cont. coordinates to a tuple, but hwo can I do this? Given cfg = {'canvas': ('3840', '1024'), 'panel1': {'gpio': '1', 'id': '4', 'co': '0,0,1280,1024'}, 'panel2': {'gpio': '2', 'id': '5', 'co': '1280,0,2560,1024'}, 'panel3': {'gpio': '3', 'id': '6', 'co': '2560,0,3840,1024'}} how can I transform cfg to cfg = {'canvas': ('3840', '1024'), 'panel1': {'gpio': '1', 'id': '4', 'co': ('0','0','1280','1024')}, 'panel2': {'gpio': '2', 'id': '5', 'co': ('1280','0','2560','1024')}, 'panel3': {'gpio': '3', 'id': '6', 'co': ('2560','0','3840','1024')}} Again, thanks for all help! From __peter__ at web.de Tue Dec 22 18:22:59 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Dec 2015 00:22:59 +0100 Subject: Newbie: Convert strings in nested dict to tuples References: Message-ID: KP wrote: > I now know how to convert a string cont. coordinates to a tuple, but hwo > can I do this? > > Given > > cfg = {'canvas': ('3840', '1024'), > 'panel1': {'gpio': '1', 'id': '4', 'co': '0,0,1280,1024'}, > 'panel2': {'gpio': '2', 'id': '5', 'co': '1280,0,2560,1024'}, > 'panel3': {'gpio': '3', 'id': '6', 'co': '2560,0,3840,1024'}} > > how can I transform cfg to > > cfg = {'canvas': ('3840', '1024'), > 'panel1': {'gpio': '1', 'id': '4', 'co': ('0','0','1280','1024')}, > 'panel2': {'gpio': '2', 'id': '5', 'co': > ('1280','0','2560','1024')}, 'panel3': {'gpio': '3', 'id': '6', > 'co': ('2560','0','3840','1024')}} > > Again, thanks for all help! >>> cfg = {'canvas': ('3840', '1024'), ... 'panel1': {'gpio': '1', 'id': '4', 'co': '0,0,1280,1024'}, ... 'panel2': {'gpio': '2', 'id': '5', 'co': '1280,0,2560,1024'}, ... 'panel3': {'gpio': '3', 'id': '6', 'co': '2560,0,3840,1024'}} >>> >>> for value in cfg.values(): ... if isinstance(value, dict): ... value["co"] = tuple(value["co"].split(",")) ... >>> import pprint >>> pprint.pprint(cfg) {'canvas': ('3840', '1024'), 'panel1': {'co': ('0', '0', '1280', '1024'), 'gpio': '1', 'id': '4'}, 'panel2': {'co': ('1280', '0', '2560', '1024'), 'gpio': '2', 'id': '5'}, 'panel3': {'co': ('2560', '0', '3840', '1024'), 'gpio': '3', 'id': '6'}} From kai.peters at gmail.com Tue Dec 22 18:31:43 2015 From: kai.peters at gmail.com (KP) Date: Tue, 22 Dec 2015 15:31:43 -0800 (PST) Subject: Newbie: Convert strings in nested dict to tuples In-Reply-To: References: Message-ID: <4438cd5a-9177-411b-8f69-8ab47f80ec26@googlegroups.com> Beautiful - thanks! On Tuesday, 22 December 2015 15:23:25 UTC-8, Peter Otten wrote: > KP wrote: > > > I now know how to convert a string cont. coordinates to a tuple, but hwo > > can I do this? > > > > Given > > > > cfg = {'canvas': ('3840', '1024'), > > 'panel1': {'gpio': '1', 'id': '4', 'co': '0,0,1280,1024'}, > > 'panel2': {'gpio': '2', 'id': '5', 'co': '1280,0,2560,1024'}, > > 'panel3': {'gpio': '3', 'id': '6', 'co': '2560,0,3840,1024'}} > > > > how can I transform cfg to > > > > cfg = {'canvas': ('3840', '1024'), > > 'panel1': {'gpio': '1', 'id': '4', 'co': ('0','0','1280','1024')}, > > 'panel2': {'gpio': '2', 'id': '5', 'co': > > ('1280','0','2560','1024')}, 'panel3': {'gpio': '3', 'id': '6', > > 'co': ('2560','0','3840','1024')}} > > > > Again, thanks for all help! > > >>> cfg = {'canvas': ('3840', '1024'), > ... 'panel1': {'gpio': '1', 'id': '4', 'co': '0,0,1280,1024'}, > ... 'panel2': {'gpio': '2', 'id': '5', 'co': '1280,0,2560,1024'}, > ... 'panel3': {'gpio': '3', 'id': '6', 'co': '2560,0,3840,1024'}} > >>> > >>> for value in cfg.values(): > ... if isinstance(value, dict): > ... value["co"] = tuple(value["co"].split(",")) > ... > >>> import pprint > >>> pprint.pprint(cfg) > {'canvas': ('3840', '1024'), > 'panel1': {'co': ('0', '0', '1280', '1024'), 'gpio': '1', 'id': '4'}, > 'panel2': {'co': ('1280', '0', '2560', '1024'), 'gpio': '2', 'id': '5'}, > 'panel3': {'co': ('2560', '0', '3840', '1024'), 'gpio': '3', 'id': '6'}} From jfong at ms4.hinet.net Tue Dec 22 21:06:58 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Tue, 22 Dec 2015 18:06:58 -0800 (PST) Subject: v3.5.1 - msi download In-Reply-To: References: Message-ID: <1c5709fb-f490-4494-a910-cd819f732322@googlegroups.com> Mark Lawrence at 2015/12/21 UTC+8 8:50:00PM wrote? > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. When I saw this sentence, I can't resist to think of the famous lie created by president John kennedy: "Ask not what your country can do for you, ask what you can do for your country". A COUNTRY WAS BUILT TO SERVE THE PEOPLE!!! Do you think people are so boring that they have to build a country to serve to? But there is always a bunch of idiots lost in these gorgeous words, don't even take a single moment to think of it, completely forgot the purpose of what a country was built for. The means eventually become the object, and millions of millions idiots sacrifice their life for this imaginary object. A LANGUAGE WAS BUILT TO SERVE THE USER!!! From rodrick.brown at gmail.com Tue Dec 22 23:14:09 2015 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 22 Dec 2015 23:14:09 -0500 Subject: convert to python code Message-ID: Tried a few things but can't seem to get it right any help ? let times = (...matrices) => matrices.reduce( ([a,b,c], [d,e,f]) => [a*d + b*e, a*e + b*f, b*e + c*f] ); From torriem at gmail.com Tue Dec 22 23:21:56 2015 From: torriem at gmail.com (Michael Torrie) Date: Tue, 22 Dec 2015 21:21:56 -0700 Subject: OT: citizens and countries - was Re: v3.5.1 - msi download In-Reply-To: <1c5709fb-f490-4494-a910-cd819f732322@googlegroups.com> References: <1c5709fb-f490-4494-a910-cd819f732322@googlegroups.com> Message-ID: <567A2164.6080400@gmail.com> On 12/22/2015 07:06 PM, jfong at ms4.hinet.net wrote: > Mark Lawrence at 2015/12/21 UTC+8 8:50:00PM wrote? >> My fellow Pythonistas, ask not what our language can do for you, ask >> what you can do for our language. > > When I saw this sentence, I can't resist to think of the famous lie created by president John kennedy: "Ask not what your country can do for you, ask what you can do for your country". > > A COUNTRY WAS BUILT TO SERVE THE PEOPLE!!! > > Do you think people are so boring that they have to build a country to serve to? In the American way of thinking, the country *is* the people. So it was neither a lie nor a bad thing that Kennedy proclaimed. Maybe this is not true for other countries, but I think most Americans would feel it is true for their country. And indeed the sentiment that Kennedy expressed resonates deeply with many/most Americans. A country is only made great by citizens willing to do many things for the good of the country and their fellow citizens. A country in which citizens only expect things from the country and never think about their ability to change and benefit the country is a week country indeed. I say this as a someone not from the US. From ben+python at benfinney.id.au Tue Dec 22 23:23:27 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 23 Dec 2015 15:23:27 +1100 Subject: convert to python code References: Message-ID: <85fuyt23pc.fsf@benfinney.id.au> Rodrick Brown writes: > Tried a few things but can't seem to get it right any help ? To convert it to Python code, you'll need to actually write some code. Please show here in this forum the actual Python code which is not behaving how you want, and say *exactly* what it's doing different from what you expect (and, preferably, explain why you expect it to behave differently). -- \ ?Do I believe in God? ? without clarification of a kind I have | `\ never seen, I don?t know whether I believe or don?t believe in | _o__) whatever a questioner has in mind.? ?Noam Chomsky | Ben Finney From random832 at fastmail.com Tue Dec 22 23:29:11 2015 From: random832 at fastmail.com (Random832) Date: Tue, 22 Dec 2015 23:29:11 -0500 Subject: Why doesn't os.remove work on directories? Message-ID: This is surprising to anyone accustomed to the POSIX C remove function, which can remove either files or directories. Is there any known rationale for this decision? From ben+python at benfinney.id.au Wed Dec 23 00:02:55 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 23 Dec 2015 16:02:55 +1100 Subject: Why doesn't os.remove work on directories? References: Message-ID: <85bn9h21vk.fsf@benfinney.id.au> Random832 writes: > This is surprising to anyone accustomed to the POSIX C remove > function, which can remove either files or directories. Is there > any known rationale for this decision? No, I don't know a rationale for implementing it this way. I expect the explanation will be ?mere historical accident?. My evidence-free reconstruction of the events leading to the current state of play: 1. ?os.unlink? implemented, using C ?unlink(3)?. Because ?unlink(2)? on a directory will cause an error, Python raises OSError for this. 2. ?os.remove? implemented; ?This is identical to the unlink() function documented below.?. 3. Backward compatibility concerns (existing code might depend on ?os.remove? raising OSError for a directory argument) justify keeping the existing behaviour. What you're looking for amounts to ?why was ?os.remove? implemented as a synonym of ?unlink(3)? instead of ?remove(3)???. I don't know why that behaviour was chosen, and I consider it a wart. -- \ ?? no testimony can be admitted which is contrary to reason; | `\ reason is founded on the evidence of our senses.? ?Percy Bysshe | _o__) Shelley, _The Necessity of Atheism_, 1811 | Ben Finney From ankit7anix at gmail.com Wed Dec 23 01:38:33 2015 From: ankit7anix at gmail.com (Ankit Deshmukh) Date: Wed, 23 Dec 2015 12:08:33 +0530 Subject: Unable to use python 3.5 Message-ID: Hi there, I am maters student in India, I have installed python 3.5 in my windows 10 64bit machine. Everything works fine except package installing. When in use ?pip install numpy? is shows unable to find *?vcvarsall.bat?* I don?t know how to fix it. I tried several things nothing works. Please help me. Thank You. Ankit Deshmukh -- *Ankit Deshmukh* IIT Hyderabad P: 9581540937 || E:ankit 7anix at gmail.com ------------------------------------------------------------------ *Simplicity is the ultimate sophistication....Leonardo da Vinci* From ganesh1pal at gmail.com Wed Dec 23 02:46:57 2015 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 23 Dec 2015 13:16:57 +0530 Subject: does the order in which the modules are placed in a file matters ? In-Reply-To: <56718F06.30300@oddbird.net> References: <56718F06.30300@oddbird.net> Message-ID: Thanks to Don , Chris and Carl for sharing your view on this topic . From gavin.packt at gmail.com Wed Dec 23 03:42:19 2015 From: gavin.packt at gmail.com (gavin.packt at gmail.com) Date: Wed, 23 Dec 2015 00:42:19 -0800 (PST) Subject: $5 Campaign - Packt Publishing Message-ID: Hey, Packt Publishing is inviting the tech world to explore its extensive library of eBooks and video courses for one amazing price. For the rest of December and into the New Year, every single eBook and video course Packt has ever created will be available on the publisher's website for just $5! Check it out: http://bit.ly/1O8QkNG Offer lasts till 8th Jan, 2016. From eryksun at gmail.com Wed Dec 23 03:50:56 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Dec 2015 02:50:56 -0600 Subject: Why doesn't os.remove work on directories? In-Reply-To: References: Message-ID: On Tue, Dec 22, 2015 at 10:29 PM, Random832 wrote: > > This is surprising to anyone accustomed to the POSIX C remove > function, which can remove either files or directories. Is there > any known rationale for this decision? Guido added os.remove as a synonym for os.unlink in version 1.4 (1996) [1]. This is also mentioned in the NEWS for 1.4b1 [2]. Note that C99 only specifies the behavior for files, as opposed to the extended unlink/rmdir that POSIX mandates [3]. 7.19.4.1 The remove function Synopsis 1 #include int remove(const char *filename); Description 2 The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation- defined. Returns 3 The remove function returns zero if the operation succeeds, nonzero if it fails. For Windows, the CRTs remove() function doesn't implement the extended POSIX behavior. It only calls DeleteFile, not RemoveDirectory. (In contrast the native NtDeleteFile [4] works for both files and directories, and relative to an open handle like unlinkat.) [1]: https://hg.python.org/cpython/rev/9fa2228bb096 [2]: https://hg.python.org/cpython/file/v1.4/Misc/NEWS#l565 [3]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html [4]: https://msdn.microsoft.com/en-us/library/ff566435 From no.email at nospam.invalid Wed Dec 23 03:51:32 2015 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 23 Dec 2015 00:51:32 -0800 Subject: $5 Campaign - Packt Publishing References: Message-ID: <87r3idim3v.fsf@nightsong.com> gavin.packt at gmail.com writes: > Packt Publishing is inviting the tech world to explore its extensive... This looks like affiliate spam (shortened link omitted). Direct link: https://www.packtpub.com They do have some good stuff there. From steve at pearwood.info Wed Dec 23 06:09:49 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Dec 2015 22:09:49 +1100 Subject: convert to python code References: Message-ID: <567a80fe$0$1594$c3e8da3$5496439d@news.astraweb.com> On Wed, 23 Dec 2015 03:14 pm, Rodrick Brown wrote: > Tried a few things but can't seem to get it right any help ? > > let times = (...matrices) => > > matrices.reduce( > > ([a,b,c], [d,e,f]) => [a*d + b*e, a*e + b*f, b*e + c*f] > > ); Are you expecting us to guess what language this is written in, decipher what it does, and write Python code to do the same thing? How about if you tell us the language and explain what it does? -- Steven From ndbecker2 at gmail.com Wed Dec 23 07:46:00 2015 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 23 Dec 2015 07:46 -0500 Subject: object() can't have attributes Message-ID: I'm a bit surprised that an object() can't have attributes: In [30]: o = object() In [31]: o.x = 2 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 o.x = 2 AttributeError: 'object' object has no attribute 'x' Sometimes I want to collect attributes on an object. Usually I would make an empty class for this. But it seems unnecessarily verbose to do this. So I thought, why not just use an Object? But no, an instance of Object apparantly can't have an attribute. Is this intentional? From rosuav at gmail.com Wed Dec 23 07:57:35 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Dec 2015 23:57:35 +1100 Subject: Unable to use python 3.5 In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 5:38 PM, Ankit Deshmukh wrote: > I am maters student in India, I have installed python 3.5 in my windows 10 > 64bit machine. Everything works fine except package installing. When in use > ?pip install numpy? is shows unable to find *?vcvarsall.bat?* I don?t know > how to fix it. I tried several things nothing works. Try grabbing a binary from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy Otherwise, pip tries to compile numpy from source, which you probably aren't set up to do. ChrisA From rosuav at gmail.com Wed Dec 23 07:58:53 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Dec 2015 23:58:53 +1100 Subject: object() can't have attributes In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker wrote: > Sometimes I want to collect attributes on an object. Usually I would make > an empty class for this. But it seems unnecessarily verbose to do this. So > I thought, why not just use an Object? But no, an instance of Object > apparantly can't have an attribute. Is this intentional? Yes; there are other uses of object() that benefit from being extremely compact. You can use types.SimpleNamespace for this job, or you can create the empty class as you're describing. (Chances are you can give the class a meaningful name anyway.) ChrisA From kwpolska at gmail.com Wed Dec 23 08:00:41 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Wed, 23 Dec 2015 14:00:41 +0100 Subject: Unable to use python 3.5 In-Reply-To: References: Message-ID: On 23 December 2015 at 07:38, Ankit Deshmukh wrote: > Hi there, > > > > I am maters student in India, We don?t care (expect that you made a typo there). > I have installed python 3.5 in my windows 10 > 64bit machine. Everything works fine except package installing. When in use > ?pip install numpy? is shows unable to find *?vcvarsall.bat?* I don?t know > how to fix it. I tried several things nothing works. You clearly haven?t tried enough, as this question is answered by a simple Google search. You need to: (a) install Visual Studio 2015 and configure it; or (b) find a binary package, eg. here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ A student who wants to work in programming should be able to find answers to their questions online. And know better than putting a phone number in their e-mail signature for the whole world to see. -- Chris Warrick PGP: 5EAAEA16 From zondo42 at gmail.com Wed Dec 23 08:02:54 2015 From: zondo42 at gmail.com (Glenn Hutchings) Date: Wed, 23 Dec 2015 05:02:54 -0800 (PST) Subject: Unable to use python 3.5 In-Reply-To: References: Message-ID: On Wednesday, 23 December 2015 12:46:43 UTC, Ankit Deshmukh wrote: > I am maters student in India, I have installed python 3.5 in my windows 10 > 64bit machine. Everything works fine except package installing. When in use > "pip install numpy" is shows unable to find *'vcvarsall.bat'* I don't know > how to fix it. I tried several things nothing works. You might find the following useful (I had the same problem): http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat From nmcelwaine at gmail.com Wed Dec 23 08:16:31 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Wed, 23 Dec 2015 13:16:31 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: slight progress: i reinstalled ticking precompile options in the "Advanced features". Now I get this: icrosoft Windows [Version 10.0.10586] (c) 2015 Microsoft Corporation. All rights reserved. C:\Users\Nick>python -m idlelib C:\Python\Python35\python.exe: Error while finding spec for 'idlelib.__main__' (: bad magic number in 'idlelib': b'\x03\xf3\r\n'); 'idlelib' is a package and cannot be directly executed any help hugely appreciated! season's greetings Nick On 22 December 2015 at 20:27, Nicky Mac wrote: > I have run the install (and repair) which explicitly includes Tcl/Tk and l > have this problem: > > Microsoft Windows [Version 10.0.10586] (c) 2015 Microsoft Corporation. All > rights reserved. > > > C:\Python\Python35\python.exe -m idlelib > ** IDLE can't import Tkinter. > Your Python may not be configured for Tk. ** > > Please suggest how this can be fixed > any support greatly appreciated > > Nick McElwaine > -- Nick "Mac" McElwaine From breamoreboy at yahoo.co.uk Wed Dec 23 08:24:06 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 23 Dec 2015 13:24:06 +0000 Subject: Unable to use python 3.5 In-Reply-To: References: Message-ID: On 23/12/2015 06:38, Ankit Deshmukh wrote: > Hi there, > > I am maters student in India, I have installed python 3.5 in my windows 10 > 64bit machine. Everything works fine except package installing. When in use > ?pip install numpy? is shows unable to find *?vcvarsall.bat?* I don?t know > how to fix it. I tried several things nothing works. > > Please help me. > > Thank You. > > Ankit Deshmukh > Welcome to this list and, regretably, one of the worst aspects of Python. You can download numpy-1.9.3+mkl-cp35-none-win_amd64.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/ and use pip to install the .whl file. Another option is to get a version of Python with a preloaded scientific stack, see here http://www.scipy.org/install.html for several choices. Then you can always install Visual Studio 2015 Community Edition. That will take hours, should get rid of the infamous "unable to find *?vcvarsall.bat?*" message but still isn't guaranteed to work, so strangely I don't recommend it. -- 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 pearwood.info Wed Dec 23 08:31:55 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Dec 2015 00:31:55 +1100 Subject: Unable to use python 3.5 References: Message-ID: <567aa24d$0$1618$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Dec 2015 12:00 am, Chris Warrick wrote: > And know better than putting a > phone number in their e-mail signature for the whole world to see. You mean, like putting their phone number in the phone book, e-card or website for the whole world to see? -- Steven From aaron.christensen at gmail.com Wed Dec 23 08:44:52 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Wed, 23 Dec 2015 08:44:52 -0500 Subject: Unable to use python 3.5 In-Reply-To: References: Message-ID: Wow, you can find cyber bullies just about anywhere... On Wed, Dec 23, 2015 at 8:00 AM, Chris Warrick wrote: > On 23 December 2015 at 07:38, Ankit Deshmukh wrote: > > Hi there, > > > > > > > > I am maters student in India, > > We don?t care (expect that you made a typo there). > > > I have installed python 3.5 in my windows 10 > > 64bit machine. Everything works fine except package installing. When in > use > > ?pip install numpy? is shows unable to find *?vcvarsall.bat?* I don?t > know > > how to fix it. I tried several things nothing works. > > You clearly haven?t tried enough, as this question is answered by a > simple Google search. You need to: > > (a) install Visual Studio 2015 and configure it; or > (b) find a binary package, eg. here: > http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > A student who wants to work in programming should be able to find > answers to their questions online. And know better than putting a > phone number in their e-mail signature for the whole world to see. > > -- > Chris Warrick > PGP: 5EAAEA16 > -- > https://mail.python.org/mailman/listinfo/python-list > From eryksun at gmail.com Wed Dec 23 08:59:55 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Dec 2015 07:59:55 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 7:16 AM, Nicky Mac wrote: > C:\Python\Python35\python.exe: Error while finding spec for > 'idlelib.__main__' (: bad magic number in 'idlelib': > b'\x03\xf3\r\n'); 'idlelib' is a package and cannot be directly executed 0xf303 (62211) is for Python 2.7. Make sure you don't have the environment variables PYTHONHOME or PYTHONPATH defined. From irmen.NOSPAM at xs4all.nl Wed Dec 23 10:49:33 2015 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 23 Dec 2015 16:49:33 +0100 Subject: object() can't have attributes In-Reply-To: References: Message-ID: <567ac28a$0$23790$e4fe514c@news.xs4all.nl> On 23-12-2015 13:58, Chris Angelico wrote: > On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker wrote: >> Sometimes I want to collect attributes on an object. Usually I would make >> an empty class for this. But it seems unnecessarily verbose to do this. So >> I thought, why not just use an Object? But no, an instance of Object >> apparantly can't have an attribute. Is this intentional? > > Yes; there are other uses of object() that benefit from being > extremely compact. You can use types.SimpleNamespace for this job, or > you can create the empty class as you're describing. (Chances are you > can give the class a meaningful name anyway.) > > ChrisA > Hey, nice, didn't know about SimpleNamespace. I was about to suggest collections.namedtuple but that one is probably more than Neal asked for. Alternatively, you can still put attributes on a function, so this works as well (but I think it's rather ugly): thing = lambda: None thing.attr = 42 vars(thing) # {'attr': 42} -irmen From rosuav at gmail.com Wed Dec 23 10:54:08 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Dec 2015 02:54:08 +1100 Subject: object() can't have attributes In-Reply-To: <567ac28a$0$23790$e4fe514c@news.xs4all.nl> References: <567ac28a$0$23790$e4fe514c@news.xs4all.nl> Message-ID: On Thu, Dec 24, 2015 at 2:49 AM, Irmen de Jong wrote: > Hey, nice, didn't know about SimpleNamespace. I was about to suggest > collections.namedtuple but that one is probably more than Neal asked for. > > Alternatively, you can still put attributes on a function, so this works as well (but I > think it's rather ugly): > > thing = lambda: None > thing.attr = 42 > vars(thing) # {'attr': 42} If you can't use SimpleNamespace (eg you need to support pre-3.3), the easiest way is an empty class: class SimpleNamespace(object): pass This will work in all versions of Python back to... I dunno, 2.something, maybe 1.x. Or, of course, you could lift the pure-Python definition of SimpleNamespace from the docs and use that :) ChrisA From rosuav at gmail.com Wed Dec 23 10:58:36 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Dec 2015 02:58:36 +1100 Subject: object() can't have attributes In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker wrote: > I'm a bit surprised that an object() can't have attributes: > > In [30]: o = object() > > In [31]: o.x = 2 > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 o.x = 2 > > AttributeError: 'object' object has no attribute 'x' BTW, the reason for this is that the base 'object' type doesn't have a __dict__. When you create a subclass, you get a __dict__ by default; but you can override this. $ python3 Python 3.6.0a0 (default:6e114c4023f5, Dec 20 2015, 19:15:28) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> object().__dict__ Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute '__dict__' >>> import sys >>> class NS(object): pass ... >>> class empty(object): __slots__ = () ... >>> sys.getsizeof(object()) 16 >>> sys.getsizeof(NS()) 56 >>> sys.getsizeof(empty()) 16 The cost of supporting arbitrary attributes is significant. It's common enough in custom classes that you have to explicitly ask for the cut-down version, but when all you need is a sentinel, that's a slab of memory and functionality that you just don't need, so it's not there. ChrisA From zachary.ware+pylist at gmail.com Wed Dec 23 11:17:09 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 23 Dec 2015 10:17:09 -0600 Subject: object() can't have attributes In-Reply-To: References: Message-ID: On Dec 23, 2015 7:00 AM, "Chris Angelico" wrote: > On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker wrote: > > Sometimes I want to collect attributes on an object. Usually I would make > > an empty class for this. But it seems unnecessarily verbose to do this. So > > I thought, why not just use an Object? But no, an instance of Object > > apparantly can't have an attribute. Is this intentional? > > Yes; there are other uses of object() that benefit from being > extremely compact. You can use types.SimpleNamespace for this job, or > you can create the empty class as you're describing. (Chances are you > can give the class a meaningful name anyway.) Its more that if you give object() an instance dict, all objects inheriting from object (i.e., all of them) must have an instance dict, which would make __slots__ and its benefits impossible. Another cross-version option: >>> bag = type("AttrBag", (), {})() >>> bag.spam = 2 >>> bag.spam 2 You can even sneak in keyword arguments like SimpleNamespace supports by passing them in the namespace dict (the third argument): >>> bag = type("AttrBag", (), dict(spam=3))() >>> bag.spam 3 Of course, using this you lose easy access to the 'AttrBag' class, but in most cases you shouldn't need it. If you do, just make it a regular class as has been suggested, or save off a reference to the class before instantiating. No comments on how ugly this is, though :) -- Zach From lele at metapensiero.it Wed Dec 23 13:04:41 2015 From: lele at metapensiero.it (Lele Gaifax) Date: Wed, 23 Dec 2015 19:04:41 +0100 Subject: Unable to use python 3.5 References: Message-ID: <8737ut11om.fsf@metapensiero.it> Chris Warrick writes: >> I am maters student in India, > > We don?t care (expect that you made a typo there). Oh, really? Surprisingly, he's not alone :-) ciao, lele. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From ben+python at benfinney.id.au Wed Dec 23 13:42:19 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 24 Dec 2015 05:42:19 +1100 Subject: Unable to use python 3.5 References: Message-ID: <8537ut0zxw.fsf@benfinney.id.au> Chris Warrick writes: > On 23 December 2015 at 07:38, Ankit Deshmukh wrote: > > I am maters student in India, > > We don?t care (expect that you made a typo there). > > > [?] When in use ?pip install numpy? is shows unable to find > > *?vcvarsall.bat?* I don?t know how to fix it. I tried several things > > nothing works. > > You clearly haven?t tried enough, as this question is answered by a > simple Google search. [?] > > A student who wants to work in programming should be able to find > answers to their questions online. And know better than putting a > phone number in their e-mail signature for the whole world to see. Chris, I found your response to be needlessly condescending and hostile to a newcomer. The original request was well-formed, and did not warrant such a slap-down. Please work to keep our community welcoming, and assume good faith in newcomers. -- \ ?Do unto others twenty-five percent better than you expect them | `\ to do unto you. (The twenty-five percent is [to correct] for | _o__) error.)? ?Linus Pauling's Golden Rule | Ben Finney From eryksun at gmail.com Wed Dec 23 14:30:25 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Dec 2015 13:30:25 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 8:38 AM, Nicky Mac wrote: > > I removed the old python2.7 entries in system Path, the PYTHON variables you > mentioned are not present. > All I have is Python35 in the PATH. Maybe there's still a stale directory on sys.path for another reason. Print sys.path from the command prompt: python -c "import sys; print(*sys.path, sep='\n')" P.S. Please reply to the list also this time. From nmcelwaine at gmail.com Wed Dec 23 14:51:56 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Wed, 23 Dec 2015 19:51:56 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: dear Python team thanks for your amazing support! no sign of old Py2.7 anywhere :- C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" C:\Python\Python35\python35.zip C:\Python\Python35\DLLs C:\Python\Python35\lib C:\Python\Python35 C:\Python\Python35\lib\site-packages On 23 December 2015 at 19:30, eryk sun wrote: > On Wed, Dec 23, 2015 at 8:38 AM, Nicky Mac wrote: > > > > I removed the old python2.7 entries in system Path, the PYTHON variables > you > > mentioned are not present. > > All I have is Python35 in the PATH. > > Maybe there's still a stale directory on sys.path for another reason. > Print sys.path from the command prompt: > > python -c "import sys; print(*sys.path, sep='\n')" > > P.S. Please reply to the list also this time. > -- Nick "Mac" McElwaine From eryksun at gmail.com Wed Dec 23 16:20:34 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Dec 2015 15:20:34 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Wed, Dec 23, 2015 at 1:51 PM, Nicky Mac wrote: > > no sign of old Py2.7 anywhere :- > > C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" > > C:\Python\Python35\python35.zip > C:\Python\Python35\DLLs > C:\Python\Python35\lib > C:\Python\Python35 > C:\Python\Python35\lib\site-packages The first blank entry is for the current directory. Do you maybe have an old "idlelib" directory in your profile? Print what it's attempting to load: python -c "import importlib; print(importlib.find_loader('idlelib').path)" From nisthesecond at verizon.net Wed Dec 23 19:57:43 2015 From: nisthesecond at verizon.net (nisthesecond at verizon.net) Date: Wed, 23 Dec 2015 18:57:43 -0600 (CST) Subject: Bug in Python 3.5.1 Message-ID: <10595588.447001.1450918663303.JavaMail.root@vms170031.mailsrvcs.net> Dear Sir, I downloaded and installed Python 3.5.1 in Windows 10. The pip command was not part of it. In the future, can you kindly include numpy, scipy, and pygame as part of the Python release? I am a teacher trying to teach Python to my students. To get a working version of Python going is extremely tedious. Kind Regards, Nick Srinivasan From ben+python at benfinney.id.au Wed Dec 23 20:24:17 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 24 Dec 2015 12:24:17 +1100 Subject: What interface is a =?utf-8?Q?=E2=80=98Popen=2Estdout=E2=80=99?= presenting? Message-ID: <85d1twzlj2.fsf@benfinney.id.au> Howdy all, When I want to wrap a binary stream to provide a text stream, such as the ?Popen.stdout? attribute from a subprocess, I can use ?io.TextIOWrapper?. That works on Python 3:: $ python3 Python 3.4.4rc1 (default, Dec 7 2015, 11:09:54) [GCC 5.3.1 20151205] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> import io >>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], stdout=subprocess.PIPE) >>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout) >>> type(gnupg_stdout) but not Python 2:: $ python2 Python 2.7.11 (default, Dec 9 2015, 00:29:25) [GCC 5.3.1 20151205] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> import io >>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], stdout=subprocess.PIPE) >>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout) Traceback (most recent call last): File "", line 1, in AttributeError: 'file' object has no attribute 'readable' I'm trying to write code that, as far as practicable, works unchanged on Python 2 and Python 3. How do I wrap an arbitrary byte stream ? already opened, such as a ?Popen.stdout? attribute ? in a text wrapper with a particular encoding? -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From ben+python at benfinney.id.au Wed Dec 23 20:36:30 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 24 Dec 2015 12:36:30 +1100 Subject: What interface is a =?utf-8?Q?=E2=80=98Popen=2Estdout?= =?utf-8?Q?=E2=80=99?= presenting? References: <85d1twzlj2.fsf@benfinney.id.au> Message-ID: <858u4kzkyp.fsf@benfinney.id.au> I left the Subject field with the wrong question. The immediate answer is ?it presents the ?file? interface?. The consequent questions remain: Ben Finney writes: > $ python2 [?] > >>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'file' object has no attribute 'readable' > > I'm trying to write code that, as far as practicable, works unchanged > on Python 2 and Python 3. > > How do I wrap an arbitrary byte stream ? already opened, such as a > ?Popen.stdout? attribute ? in a text wrapper with a particular > encoding? It appears the Python 2 ?file? type doesn't implement a ?buffer? as expected by ?io.TextIOWrapper?. So how do I get from a Python 2 ?file? object, to whatever ?io.TextIOWrapper? wants? -- \ ?Nature is trying very hard to make us succeed, but nature does | `\ not depend on us. We are not the only experiment.? ?Richard | _o__) Buckminster Fuller, 1978-04-30 | Ben Finney From qurratul.ainy1 at gmail.com Wed Dec 23 20:53:13 2015 From: qurratul.ainy1 at gmail.com (Qurrat ul Ainy) Date: Wed, 23 Dec 2015 17:53:13 -0800 (PST) Subject: need some basic help Message-ID: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> Hello, Can someone please explain this code below. I am new at Python . Thanks def receive_messages(self, msgs, time): for msg in msgs: msg.set_recv_time(time) self.msgs_received.extend(msgs) From greg.ewing at canterbury.ac.nz Wed Dec 23 22:16:36 2015 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 24 Dec 2015 16:16:36 +1300 Subject: OT: citizens and countries - was Re: v3.5.1 - msi download In-Reply-To: References: <1c5709fb-f490-4494-a910-cd819f732322@googlegroups.com> Message-ID: Michael Torrie wrote: > A country in which citizens only expect things from the country and > never think about their ability to change and benefit the country is a > week country indeed. ^^^^ Yep, definitely won't last more than 7 days. :-) -- Greg From armorsmith42 at gmail.com Wed Dec 23 22:58:40 2015 From: armorsmith42 at gmail.com (Andrew Farrell) Date: Wed, 23 Dec 2015 21:58:40 -0600 Subject: need some basic help In-Reply-To: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> Message-ID: This code snippet is a method on a class. What is a method? This chapter of the book Think Python does a good job of explaining it. Without understanding this foundation, it isn't possible to really answer your question, so definitely read at least that chapter. Think Python was the book I first learned from and if you are new to python, I recommend it among the other python tutorials to consider. In this case, this method takes two things: 0) The object that it is a method of (by python convention, this is called "self") 1) a collection of message objects (probably a list, maybe a tuple, probably not a set) 2) a time It then, goes through all of them and tells each one "you were received at some particular time." by calling a method on each of the message objects. The object that it is a method of seems to have a list of messages it has received. So, this method sticks the collection of new message objects onto the list of already-received messages. On Wed, Dec 23, 2015 at 7:53 PM, Qurrat ul Ainy wrote: > Hello, > > Can someone please explain this code below. I am new at Python . > Thanks > > > def receive_messages(self, msgs, time): > for msg in msgs: > msg.set_recv_time(time) > self.msgs_received.extend(msgs) > -- > https://mail.python.org/mailman/listinfo/python-list > From bkulbismuth at gmail.com Wed Dec 23 23:24:53 2015 From: bkulbismuth at gmail.com (Benjamin Kulas) Date: Wed, 23 Dec 2015 20:24:53 -0800 (PST) Subject: need some basic help In-Reply-To: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> Message-ID: <1dc1e09d-f1cc-4cf6-8535-f61ac2af9c43@googlegroups.com> On Wednesday, December 23, 2015 at 7:53:43 PM UTC-6, Qurrat ul Ainy wrote: > Hello, > > Can someone please explain this code below. I am new at Python . > Thanks > > > def receive_messages(self, msgs, time): > for msg in msgs: > msg.set_recv_time(time) > self.msgs_received.extend(msgs) What exactly are you confused about? This looks like it is part of a class; can you post the entire class definition? Also, what is the purpose of the program that contains this snippet? From eryksun at gmail.com Wed Dec 23 23:30:02 2015 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Dec 2015 22:30:02 -0600 Subject: =?UTF-8?B?UmU6IFdoYXQgaW50ZXJmYWNlIGlzIGEg4oCYUG9wZW4uc3Rkb3V04oCZIHByZXNlbnRpbg==?= =?UTF-8?B?Zz8=?= In-Reply-To: <858u4kzkyp.fsf@benfinney.id.au> References: <85d1twzlj2.fsf@benfinney.id.au> <858u4kzkyp.fsf@benfinney.id.au> Message-ID: On Wed, Dec 23, 2015 at 7:36 PM, Ben Finney wrote: > So how do I get from a Python 2 ?file? object, to whatever > ?io.TextIOWrapper? wants? I would dup the file descriptor and close the original file. Then open the file descriptor using io.open: >>> p = subprocess.Popen(['uname'], stdout=subprocess.PIPE) >>> fd = os.dup(p.stdout.fileno()) >>> fd 4 >>> p.stdout.close() >>> fout = io.open(fd, 'r') >>> fout <_io.TextIOWrapper name=4 encoding='UTF-8'> >>> fout.read() u'Linux\n' From ben+python at benfinney.id.au Wed Dec 23 23:40:06 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 24 Dec 2015 15:40:06 +1100 Subject: What interface is a =?utf-8?Q?=E2=80=98Popen=2Estdout?= =?utf-8?Q?=E2=80=99?= presenting? References: <85d1twzlj2.fsf@benfinney.id.au> <858u4kzkyp.fsf@benfinney.id.au> Message-ID: <854mf8zcgp.fsf@benfinney.id.au> eryk sun writes: > On Wed, Dec 23, 2015 at 7:36 PM, Ben Finney wrote: > > So how do I get from a Python 2 ?file? object, to whatever > > ?io.TextIOWrapper? wants? > > I would dup the file descriptor and close the original file. Then open > the file descriptor using io.open Thanks. Okay, now I reveal (I apologise for not making this clear initially) that I need the *same* code to work with pseudo files created by the unit test suite: files with no underlying file handle. That is, I need the same code to accept: * A Python 2 ?file? instance as emitted by many stdlib functions. * A Python 3 ?io.*? file object as emitted by many stdlib functions. * A pseudo-file (e.g. ?io.BytesIO?) test double. With any of those, I need the code to wrap a stream already open in ?binary? mode, and give me a wrapper (e.g. ?io.TextIOWrapper?) to read and/or write text on that stream. -- \ ?It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place.? ?Henry L. | _o__) Mencken | Ben Finney From DWhite at atb.com Thu Dec 24 00:27:26 2015 From: DWhite at atb.com (White, Dalton) Date: Thu, 24 Dec 2015 05:27:26 +0000 Subject: Command line for silent Install & Uninstall Message-ID: Hi Support I have seen many documents on the internet regarding installs of MSI but I only see the option to download exe's from your website. How can I get the MSI for Python version 3.5.1? I am using ""python-3.5.1rc1-amd64.exe" /passive /uninstall" to uninstall the software but the uninstall screen just keeps coming up and disappearing. Do you have any solutions or fixes that you can offer me? Thanks Dalton 416-988-0662 If you have received this email in error, please let me know by return email so I can make sure it doesn't happen again. Because emails can contain confidential and privileged material, I'd ask for your help by deleting it and any attachments. Thanks! We like to keep people up to date with information about new products and services at ATB or changes that could affect you. You can check out more about ATB and CASL at http://www.atb.com/important-information/privacy-security/Pages/ATB-and-CASL.aspx If you would like to unsubscribe from our updates, please use this URL - http://www.atb.com/important-information/privacy-security/Pages/unsubscribe.aspx From jfong at ms4.hinet.net Thu Dec 24 02:05:53 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Wed, 23 Dec 2015 23:05:53 -0800 (PST) Subject: OT: citizens and countries - was Re: v3.5.1 - msi download In-Reply-To: References: <1c5709fb-f490-4494-a910-cd819f732322@googlegroups.com> Message-ID: <6acd3325-08ce-4ccb-9c39-cbdc95686e1a@googlegroups.com> Michael Torrie at 2015/12/23 UTC+8 12:22:23PM wrote? > In the American way of thinking, the country *is* the people. So it was > neither a lie nor a bad thing that Kennedy proclaimed. Maybe this is > not true for other countries, but I think most Americans would feel it > is true for their country. And indeed the sentiment that Kennedy > expressed resonates deeply with many/most Americans. A country is only > made great by citizens willing to do many things for the good of the > country and their fellow citizens. I don't think any country can be "great" if it can't even take care of its own people well. American can not be great because of there are millions of citizens has no enough food, health cares and living on the street, at the same time this country spend billions of dollars on bombing other country's people. This situation is painful to human mind and it was supposed to be solved by the country leaders. But politicians are incapable of doing anything except been good on spreading glorious words and sentences. As an anaesthetic to divert people from this incapability, these words also make some Americans happy to ignore the facts and continuously to believe that American is still a great country. From nmcelwaine at gmail.com Thu Dec 24 06:06:43 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Thu, 24 Dec 2015 11:06:43 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: Hello again.] not sure what you mean by "my profile". following your suggestion, looks normal: C:\Users\Nick> python -c "import importlib; print(importlib.find_loader('idlelib').path)" C:\Python\Python35\lib\idlelib\__init__.pyc A search for idlelib shows this one plus one deep inside OpenOffice and a Game. On 23 December 2015 at 21:20, eryk sun wrote: > On Wed, Dec 23, 2015 at 1:51 PM, Nicky Mac wrote: > > > > no sign of old Py2.7 anywhere :- > > > > C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" > > > > C:\Python\Python35\python35.zip > > C:\Python\Python35\DLLs > > C:\Python\Python35\lib > > C:\Python\Python35 > > C:\Python\Python35\lib\site-packages > > The first blank entry is for the current directory. Do you maybe have > an old "idlelib" directory in your profile? > > Print what it's attempting to load: > > python -c "import importlib; > print(importlib.find_loader('idlelib').path)" > -- Nick "Mac" McElwaine From steve at pearwood.info Thu Dec 24 06:58:47 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Dec 2015 22:58:47 +1100 Subject: need some basic help References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> Message-ID: <567bddfa$0$1617$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Dec 2015 12:53 pm, Qurrat ul Ainy wrote: > Hello, > > Can someone please explain this code below. I am new at Python . > Thanks > > > def receive_messages(self, msgs, time): > for msg in msgs: > msg.set_recv_time(time) > self.msgs_received.extend(msgs) This is a method belonging to a class. We don't know what the class is, because you haven't shown it, so let's just call it "MyClass". The method takes two arguments (msgs and time) plus a special argument, "self", which represents the instance where the method is called. So at some point, you must say: instance = MyClass() Do you understand object oriented programming? Have you programmed in any other languages? My *guess* is that the "msgs" argument is probably a list of messages: the_messages = [first_message, second_message, third_message] and the "time" argument is possibly a number (time in seconds?): some_time = 125 Then you call the method: instance.receive_messages(the_messages, some_time) When you call the receive_messages method, the following happens: - each of the messages are taken in turn, one at a time, and a method on that message is called: for msg in msgs: msg.set_recv_time(time) Translation: for each message first_message, second_message, ... call method "set_recv_time" with argument some_time - then the original instance calls one of its own messages, probably to store those messages: self.msgs_received.extend(msgs) I can't be more detailed, as I don't know how much programming experience you have, or what the class that this method came from does. -- Steven From princeudo52 at gmail.com Thu Dec 24 07:39:40 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Thu, 24 Dec 2015 04:39:40 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Saturday, December 12, 2015 at 10:05:29 AM UTC+1, Harbey Leke wrote: > Create a class called BankAccount > > .Create a constructor that takes in an integer and assigns this to a `balance` property. > > .Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly. > > .Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` > > .Create a subclass MinimumBalanceAccount of the BankAccount class > > Please i need help on this i am a beginer into python programming. > > > Also below is a test case given for this project > > > import unittest > class AccountBalanceTestCases(unittest.TestCase): > def setUp(self): > self.my_account = BankAccount(90) > > def test_balance(self): > self.assertEqual(self.my_account.balance, 90, msg='Account Balance Invalid') > > def test_deposit(self): > self.my_account.deposit(90) > self.assertEqual(self.my_account.balance, 180, msg='Deposit method inaccurate') > > def test_withdraw(self): > self.my_account.withdraw(40) > self.assertEqual(self.my_account.balance, 50, msg='Withdraw method inaccurate') > > def test_invalid_operation(self): > self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", msg='Invalid transaction') > > def test_sub_class(self): > self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No true subclass of BankAccount') please what is a balance property in OOP From laurent at krutt.org Thu Dec 24 07:58:45 2015 From: laurent at krutt.org (Laurent Delacroix) Date: Thu, 24 Dec 2015 13:58:45 +0100 Subject: Why doesn't os.remove work on directories? References: Message-ID: On 23/12/15 05:29, Random832 wrote: > > This is surprising to anyone accustomed to the POSIX C remove > function, which can remove either files or directories. Is there > any known rationale for this decision? > Hello, in POSIX C the remove() function is actually rmdir() when called on a directory: http://bit.ly/1NE1rfZ I'm not sure about the rationale behind raising OSError if the argument is a directory though. Maybe the "There should be one-- and preferably only one --obvious way to do it." philosophy explains it. :-) Lau From princeudo52 at gmail.com Thu Dec 24 07:59:49 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Thu, 24 Dec 2015 04:59:49 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> here is what i came up with Class BankAccount(object): def_init_(self, balance): self.Balance = balance def deposit(self, amount): self.Balance = amount def withdraw(self,amount): if(self.Balance += amount): return invalid transaction #but my challange now is :Create a subclass MinimumBalanceAccount of the BankAccount class. From rosuav at gmail.com Thu Dec 24 08:10:17 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 25 Dec 2015 00:10:17 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> Message-ID: On Thu, Dec 24, 2015 at 11:59 PM, wrote: > here is what i came up with > Class BankAccount(object): > def_init_(self, balance): > self.Balance = balance > def deposit(self, amount): > self.Balance = amount > def withdraw(self,amount): > if(self.Balance += amount): > return invalid transaction > #but my challange now is :Create a subclass MinimumBalanceAccount of the BankAccount class. Step 1: Debug your code before you post it. Step 2: Make sure that the way your code ends up is the same as the way it started out. I suspect you have some of the above lines indented, but that's getting lost. Your code (a) will not compile, due to a complete lack of indentation; (b) will not compile even if indented correctly, due to a misuse of an 'operator' that isn't actually an operator; (c) won't compile due to invalid abuttal of tokens (did you intend to put quotes around something?); (d) STILL won't compile because you misspelled a keyword; and (e) won't do what you think it should, even once you make it compile, because of logic errors. Don't move on to the second challenge until you have mastered this first one. ChrisA From wjm0621 at hanmail.net Thu Dec 24 08:22:23 2015 From: wjm0621 at hanmail.net (=?utf-8?B?7Jqw7KKF66+8?=) Date: Thu, 24 Dec 2015 22:22:23 +0900 (KST) Subject: can i subscribe python mailing list? Message-ID: <20151224222223.HM.0000000000005Ua@wjm0621.wwl1499.hanmail.net> i want to subscribe mailing list [1][IMG] References Visible links 1. mailto:wjm0621 at hanmail.net From tbaror at gmail.com Thu Dec 24 08:24:12 2015 From: tbaror at gmail.com (Tal Bar-Or) Date: Thu, 24 Dec 2015 05:24:12 -0800 (PST) Subject: SSL over TCP Client\server Message-ID: Hi All , I need to write some basic tcp client/server that communicate over SSL Its seems i managed to run the server side listen with SSL but i am missing the client part. If someone could advice me how to saet the client will be appreciated Thanks Server side ============ class SingleTCPHandler(socketserver.BaseRequestHandler): "One instance per connection. Override handle(self) to customize action." def handle(self): try: #print(self.server.serverset) data = json.loads(self.request.recv(1024).decode('UTF-8').strip()) # process the data, i.e. print it: #print(self.client_address) print(data['AuthPass'],self.server.serverset['CryptKey'],self.server.serverset['Password']) Authstart = AuthMec(data['AuthPass'],self.server.serverset['CryptKey'],self.server.serverset['Password']) Authstart.DecPass() # send some 'ok' back #self.server.serverset['QuarantineIp'] self.request.sendall(bytes(json.dumps({'QuarantineIp':self.server.serverset['QuarantineIp'],'SERVERIP':self.client_address[0]}), 'UTF-8')) except Exception as e: print("Exception wile receiving message: ", e) class TcpSessionServer(socketserver.ThreadingMixIn, socketserver.TCPServer): # Ctrl-C will cleanly kill all spawned threads daemon_threads = True # much faster rebinding allow_reuse_address = True test = "test" def __init__(self, server_address, RequestHandlerClass): socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) self.socket = ssl.wrap_socket( self.socket, server_side=True, certfile="cert.pem",do_handshake_on_connect=False) #read configuraiton and seve it as class member serverinit = GetServerInfo() Clent Side =========== class TcpClientConnect: def __init__(self,Datapayload,EnforcementHost,SrvPort): self.Datapayload = Datapayload self.EnforcementHost = EnforcementHost self.SrvPort = SrvPort def ContactEnforcementHost(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.EnforcementHost, int(self.SrvPort))) s.send(bytes(json.dumps(self.Datapayload), 'UTF-8')) #Waiting for results result = s.recv(1024) txres = result.decode('UTF-8') print(txres) jsresult = json.loads(txres) print("%s"%jsresult) s.close() From nmcelwaine at gmail.com Thu Dec 24 08:59:48 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Thu, 24 Dec 2015 13:59:48 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: Dear python Team I think I've been wasting your time: C:\Users\Nick>path PATH=C:\Python27\;C:\Python27\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Python\Python35\Scripts\;C:\Python\Python35\ somehow the new py3.5 has been added to the end, not the beginning. guess this path is what you meant by "my profile". I'll set about fixing it. Meery christmas to you all Nick On 24 December 2015 at 11:06, Nicky Mac wrote: > Hello again.] > not sure what you mean by "my profile". > following your suggestion, looks normal: > > C:\Users\Nick> python -c "import importlib; > print(importlib.find_loader('idlelib').path)" > C:\Python\Python35\lib\idlelib\__init__.pyc > > A search for idlelib shows this one plus one deep inside OpenOffice and a > Game. > > On 23 December 2015 at 21:20, eryk sun wrote: > >> On Wed, Dec 23, 2015 at 1:51 PM, Nicky Mac wrote: >> > >> > no sign of old Py2.7 anywhere :- >> > >> > C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" >> > >> > C:\Python\Python35\python35.zip >> > C:\Python\Python35\DLLs >> > C:\Python\Python35\lib >> > C:\Python\Python35 >> > C:\Python\Python35\lib\site-packages >> >> The first blank entry is for the current directory. Do you maybe have >> an old "idlelib" directory in your profile? >> >> Print what it's attempting to load: >> >> python -c "import importlib; >> print(importlib.find_loader('idlelib').path)" >> > > > > -- > Nick "Mac" McElwaine > -- Nick "Mac" McElwaine From princeudo52 at gmail.com Thu Dec 24 09:17:23 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Thu, 24 Dec 2015 06:17:23 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> Message-ID: <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> i am getting to believe that no one can provide a solution to this challenge, every-one here is just beating around the bush From breamoreboy at yahoo.co.uk Thu Dec 24 09:36:50 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Dec 2015 14:36:50 +0000 Subject: Bug in Python 3.5.1 In-Reply-To: <10595588.447001.1450918663303.JavaMail.root@vms170031.mailsrvcs.net> References: <10595588.447001.1450918663303.JavaMail.root@vms170031.mailsrvcs.net> Message-ID: On 24/12/2015 00:57, nisthesecond at verizon.net wrote: > Dear Sir, > I downloaded and installed Python 3.5.1 in Windows 10. > The pip command was not part of it. > In the future, can you kindly include numpy, scipy, and pygame as part of > the Python release? > I am a teacher trying to teach Python to my students. > To get a working version of Python going is extremely tedious. > Kind Regards, > Nick Srinivasan > pip is part of Python 3.5.1, I'd assume that you did not select it when you did the installion. Installing third party modules with core Python is never going to happen. However there are several distributions that do bundle things, see http://www.scipy.org/install.html -- 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 Dec 24 09:39:13 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 25 Dec 2015 01:39:13 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: On Fri, Dec 25, 2015 at 1:17 AM, wrote: > i am getting to believe that no one can provide a solution to this challenge, every-one here is just beating around the bush It's not a question of 'can' but 'will'. We will not provide the answer to your homework question. This has already been explained to you. ChrisA From cody.piersall at gmail.com Thu Dec 24 09:46:21 2015 From: cody.piersall at gmail.com (Cody Piersall) Date: Thu, 24 Dec 2015 08:46:21 -0600 Subject: Bug in Python 3.5.1 In-Reply-To: <10595588.447001.1450918663303.JavaMail.root@vms170031.mailsrvcs.net> References: <10595588.447001.1450918663303.JavaMail.root@vms170031.mailsrvcs.net> Message-ID: On Wed, Dec 23, 2015 at 6:57 PM, wrote: > Dear Sir, > In the future, can you kindly include numpy, scipy, and pygame as part of > the Python release? > Nick Srinivasan Hello Nick, Any time you want to install a Python package, the first thing you should try is typing "pip install [package-name]". If that doesn't work (and it often doesn't), you should check [Christoph Golke's website] for the package you're trying to install. If you want to download Python and have numpy, scipy, and Python in one installer, I recommend using [Anaconda]. You will still have to download pygame yourself (I think). Anaconda is a pretty big download, but the plus side is that it comes with lots of packages so probably won't have to install as much stuff. There is no way that numpy, scipy, and pygame will become a part of the Python release; that's why redistributors like Anaconda exist. [Anaconda]: https://www.continuum.io/downloads#_windows [Christoph Golke's website]: http://www.lfd.uci.edu/~gohlke/pythonlibs/ From nmcelwaine at gmail.com Thu Dec 24 09:52:35 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Thu, 24 Dec 2015 14:52:35 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: what a horrible environment windows is to support anything! (I was a UNIX professional). seems the user profile PATH is a registry entry, and was not updated when I deinstalled Python2.7 still haven't figured out how to change it - I will NOT attempy a regedit. season's greetings On 24 December 2015 at 13:59, Nicky Mac wrote: > Dear python Team > I think I've been wasting your time: > > C:\Users\Nick>path > PATH=C:\Python27\;C:\Python27\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program > Files\Broadcom\Broadcom 802.11 Network > Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program > Files (x86)\ATI > Technologies\ATI.ACE\Core-Static;C:\Python\Python35\Scripts\;C:\Python\Python35\ > > somehow the new py3.5 has been added to the end, not the beginning. > guess this path is what you meant by "my profile". > I'll set about fixing it. > Meery christmas to you all > Nick > > On 24 December 2015 at 11:06, Nicky Mac wrote: > >> Hello again.] >> not sure what you mean by "my profile". >> following your suggestion, looks normal: >> >> C:\Users\Nick> python -c "import importlib; >> print(importlib.find_loader('idlelib').path)" >> C:\Python\Python35\lib\idlelib\__init__.pyc >> >> A search for idlelib shows this one plus one deep inside OpenOffice and a >> Game. >> >> On 23 December 2015 at 21:20, eryk sun wrote: >> >>> On Wed, Dec 23, 2015 at 1:51 PM, Nicky Mac wrote: >>> > >>> > no sign of old Py2.7 anywhere :- >>> > >>> > C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" >>> > >>> > C:\Python\Python35\python35.zip >>> > C:\Python\Python35\DLLs >>> > C:\Python\Python35\lib >>> > C:\Python\Python35 >>> > C:\Python\Python35\lib\site-packages >>> >>> The first blank entry is for the current directory. Do you maybe have >>> an old "idlelib" directory in your profile? >>> >>> Print what it's attempting to load: >>> >>> python -c "import importlib; >>> print(importlib.find_loader('idlelib').path)" >>> >> >> >> >> -- >> Nick "Mac" McElwaine >> > > > > -- > Nick "Mac" McElwaine > -- Nick "Mac" McElwaine From eryksun at gmail.com Thu Dec 24 09:59:09 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 08:59:09 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 5:06 AM, Nicky Mac wrote: > > not sure what you mean by "my profile". > following your suggestion, looks normal: I meant your profile directory, "C:\Users\Nick". But printing the package path showed the problem is in your Python 3 installation itself. > C:\Users\Nick> python -c "import importlib; > print(importlib.find_loader('idlelib').path)" > C:\Python\Python35\lib\idlelib\__init__.pyc This file should not exist. Python 3 stores .pyc files in a __pycache__ subdirectory. It won't even run "idlelib\__init__.pyc" if "idlelib\__init__.py" exists, so your installation is incomplete and damaged. I suggest that you uninstall Python 3.5 and then completely remove "C:\Python\Python35" before reinstalling. From nmcelwaine at gmail.com Thu Dec 24 10:11:05 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Thu, 24 Dec 2015 15:11:05 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: sorry to be such a darned nuisance - fixed the PATH to eliminate Py2.7 references but get same result: C:\Users\Nick>path PATH=C:\Python\Python35\Scripts\;C:\Python\Python35\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static; C:\Users\Nick>python -m idlelib C:\Python\Python35\python.exe: Error while finding spec for 'idlelib.__main__' (: bad magic number in 'idlelib': b'\x03\xf3\r\n'); 'idlelib' is a package and cannot be directly executed On 24 December 2015 at 14:52, Nicky Mac wrote: > what a horrible environment windows is to support anything! > (I was a UNIX professional). > seems the user profile PATH is a registry entry, and was not updated when > I deinstalled Python2.7 > still haven't figured out how to change it - I will NOT attempy a regedit. > > season's greetings > > On 24 December 2015 at 13:59, Nicky Mac wrote: > >> Dear python Team >> I think I've been wasting your time: >> >> C:\Users\Nick>path >> PATH=C:\Python27\;C:\Python27\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program >> Files\Broadcom\Broadcom 802.11 Network >> Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program >> Files (x86)\ATI >> Technologies\ATI.ACE\Core-Static;C:\Python\Python35\Scripts\;C:\Python\Python35\ >> >> somehow the new py3.5 has been added to the end, not the beginning. >> guess this path is what you meant by "my profile". >> I'll set about fixing it. >> Meery christmas to you all >> Nick >> >> On 24 December 2015 at 11:06, Nicky Mac wrote: >> >>> Hello again.] >>> not sure what you mean by "my profile". >>> following your suggestion, looks normal: >>> >>> C:\Users\Nick> python -c "import importlib; >>> print(importlib.find_loader('idlelib').path)" >>> C:\Python\Python35\lib\idlelib\__init__.pyc >>> >>> A search for idlelib shows this one plus one deep inside OpenOffice and >>> a Game. >>> >>> On 23 December 2015 at 21:20, eryk sun wrote: >>> >>>> On Wed, Dec 23, 2015 at 1:51 PM, Nicky Mac >>>> wrote: >>>> > >>>> > no sign of old Py2.7 anywhere :- >>>> > >>>> > C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" >>>> > >>>> > C:\Python\Python35\python35.zip >>>> > C:\Python\Python35\DLLs >>>> > C:\Python\Python35\lib >>>> > C:\Python\Python35 >>>> > C:\Python\Python35\lib\site-packages >>>> >>>> The first blank entry is for the current directory. Do you maybe have >>>> an old "idlelib" directory in your profile? >>>> >>>> Print what it's attempting to load: >>>> >>>> python -c "import importlib; >>>> print(importlib.find_loader('idlelib').path)" >>>> >>> >>> >>> >>> -- >>> Nick "Mac" McElwaine >>> >> >> >> >> -- >> Nick "Mac" McElwaine >> > > > > -- > Nick "Mac" McElwaine > -- Nick "Mac" McElwaine From joel.goldstick at gmail.com Thu Dec 24 10:47:04 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Dec 2015 10:47:04 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: On Thu, Dec 24, 2015 at 9:39 AM, Chris Angelico wrote: > On Fri, Dec 25, 2015 at 1:17 AM, wrote: > > i am getting to believe that no one can provide a solution to this > challenge, every-one here is just beating around the bush > > It's not a question of 'can' but 'will'. We will not provide the > answer to your homework question. This has already been explained to > you. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > Generally, the best way to receive help is to provide your code written in a way that is indented (plain text), provide the complete text of what you are being asked to do in your class, and copy and paste any output or exceptions. You don't seem to be willing to do any of these things, and consequently you can't be helped. Also, what is up with the handful of email addresses used to post your 'demands'. Not to be rude, but if your style of methodology for asking for help is indicative of your general attitude, and interest in learning to write software, you may be better served to find a new calling. Its not a good profession for people who basically say "do this for me" -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From darcy at VybeNetworks.com Thu Dec 24 11:14:54 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Thu, 24 Dec 2015 11:14:54 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: <20151224111454.6e0cf885@imp> On Thu, 24 Dec 2015 10:47:04 -0500 Joel Goldstick wrote: > Not to be rude, but if your style of methodology for asking for help > is indicative of your general attitude, and interest in learning to > write software, you may be better served to find a new calling. Its > not a good profession for people who basically say "do this for me" Or we wish it wasn't. That seems to be the style today. People claim to be programmers who only search the net for snippets to plug into their programs with no actual understanding. Or, they download a Wordpress theme and call themselves web designers. It reminds me of when one day people started claiming to be "building" computers and they didn't even own a soldering iron. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From rosuav at gmail.com Thu Dec 24 11:31:36 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 25 Dec 2015 03:31:36 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <20151224111454.6e0cf885@imp> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> <20151224111454.6e0cf885@imp> Message-ID: On Fri, Dec 25, 2015 at 3:14 AM, D'Arcy J.M. Cain wrote: > It reminds me of when one day people started claiming to be "building" > computers and they didn't even own a soldering iron. Hey! Don't judge me just because I use my dad's! :) ChrisA From eryksun at gmail.com Thu Dec 24 11:39:41 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 10:39:41 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 8:52 AM, Nicky Mac wrote: > seems the user profile PATH is a registry entry, and was not updated when I > deinstalled Python2.7 > still haven't figured out how to change it - I will NOT attempy a regedit. I don't use the option to add the installation and Scripts directories to PATH. It's a mess when installing multiple interpreters. I use the py launcher [1] and virtual environments [2], and manually add .PY to PATHEXT. [1]: https://docs.python.org/3/using/windows.html#python-launcher-for-windows [2]: https://docs.python.org/3/library/venv.html From laurent.pointal at free.fr Thu Dec 24 12:09:01 2015 From: laurent.pointal at free.fr (Laurent Pointal) Date: Thu, 24 Dec 2015 18:09:01 +0100 Subject: Bug in Python 3.5.1 References: Message-ID: <567c26ad$0$4096$426a74cc@news.free.fr> Hello, nisthesecond at verizon.net wrote: > Dear Sir, > I downloaded and installed Python 3.5.1 in Windows 10. > The pip command was not part of it. > In the future, can you kindly include numpy, scipy, and pygame as part > of the Python release? > I am a teacher trying to teach Python to my students. > To get a working version of Python going is extremely tedious. > Kind Regards, > Nick Srinivasan IMHO There is no chance that all these packages be distributed with Python in the standard libs. Near the third party distributions already signaled (Anaconda, but there is also Pythonxy and others), for students you can take a look a Pyzo, which integrate an IDE with some common scientific packages. http://www.pyzo.org/ It include following packages: http://www.pyzo.org/packages.html#packages But, no pygame? (maybe it can be installed via conda as indicated on this page - you may test under common student OS). A+ Laurent. From invalid at invalid.invalid Thu Dec 24 12:30:08 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 24 Dec 2015 17:30:08 +0000 (UTC) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: On 2015-12-24, D'Arcy J.M. Cain wrote: > It reminds me of when one day people started claiming to be "building" > computers and they didn't even own a soldering iron. And don't get me started on those people who use those "integrated circuits" instead of transistors, relays, and tubes... -- Grant From eryksun at gmail.com Thu Dec 24 13:10:57 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 12:10:57 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 8:52 AM, Nicky Mac wrote: > seems the user profile PATH is a registry entry, and was not updated when I > deinstalled Python2.7 > still haven't figured out how to change it - I will NOT attempy a regedit. As to PATH on Windows, it's split into system and user components, which get concatenated (system followed by user) when a profile is loaded at logon. Persisted user environment variables are defined in the user's "Environment" key. This is where PATH should be defined. HKEY_CURRENT_USER\Environment There's also the "Volatile Environment" key where the system stores variables that are defined at logon such as USERNAME, USERPROFILE, and a per-session subkey (e.g. "1" for session 1) that has values such as SESSIONNAME. HKEY_CURRENT_USER\Volatile Environment HKEY_CURRENT_USER (HKCU) references the current user's hive, which is loaded in HKEY_USERS. The entries in HKEY_USERS are named by user SIDs (see "whoami /user"). The user's registry hive is loaded when logged on interactively or otherwise by LoadUserProfile. The hive is physically stored in the user profile directory in the hidden file "%USERPROFILE%\NTUSER.DAT". The system environment is first loaded by the session manager (smss.exe) during boot, so it's a subkey of the session manager's configuration. HKEY_LOCAL_MACHINE\SYSTEM\ CurrentControlSet\Control\Session Manager\Environment The HKLM\SYSTEM hive is located on the system volume at "%SystemRoot%\System32\config\SYSTEM". Don't use regedit to modify the environment unless you plan to reboot the system. Tools that modify the environment know to broadcast a WM_SETTINGCHANGE message to all top-level windows, which makes Explorer reload its environment from the registry. Subsequent processes started by Explorer inherit the updated environment. >From the command line, use "set" to modify the current environment. If you also want the change to be permanent, and for Explorer to be notified, then use setx.exe. In this case you still need cmd's internal "set" in order to modify the current environment. For example, first modify the current PATH. C:\>set MYPATH=C:\Spam;C:\Eggs C:\>set PATH=%PATH%;%MYPATH% Next, inspect the user's PATH in the registry. C:\>reg query HKCU\Environment /v PATH HKEY_CURRENT_USER\Environment PATH REG_EXPAND_SZ %USERPROFILE%\.dnx\bin Run setx.exe to extend this value. Note that "^" is cmd's escape character. C:\>setx MYPATH %MYPATH% SUCCESS: Specified value was saved. C:\>setx PATH ^%USERPROFILE^%\.dnx\bin;^%MYPATH^% SUCCESS: Specified value was saved. Verify that it was set correctly. C:\>reg query HKCU\Environment HKEY_CURRENT_USER\Environment DNX_HOME REG_SZ %USERPROFILE%\.dnx PATH REG_EXPAND_SZ %USERPROFILE%\.dnx\bin;%MYPATH% TEMP REG_EXPAND_SZ %USERPROFILE%\AppData\Local\Temp TMP REG_EXPAND_SZ %USERPROFILE%\AppData\Local\Temp MYPATH REG_SZ C:\Spam;C:\Eggs setx.exe sets the value's type as REG_EXPAND_SZ if it contains at least two "%" characters. It's only well-defined for REG_EXPAND_SZ values to depend on REG_SZ variables (or any system variable in a user variable, since the system environment is loaded first). A registry key is enumerated in arbitrary order (not alphabetic), but the system enumerates the key in two passes, with REG_SZ variables loaded in the first pass. Note that Visual Studio mistakenly set DNX_HOME as a REG_SZ. Thus I have the following useless environment variable: C:\>echo %DNX_HOME% should have been set as REG_EXPAND_SZ. %USERPROFILE%\.dnx should have been set as REG_EXPAND_SZ. From gheskett at wdtv.com Thu Dec 24 13:51:01 2015 From: gheskett at wdtv.com (Gene Heskett) Date: Thu, 24 Dec 2015 13:51:01 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <201512241351.02019.gheskett@wdtv.com> On Thursday 24 December 2015 12:30:08 Grant Edwards wrote: > On 2015-12-24, D'Arcy J.M. Cain wrote: > > It reminds me of when one day people started claiming to be > > "building" computers and they didn't even own a soldering iron. > > And don't get me started on those people who use those "integrated > circuits" instead of transistors, relays, and tubes... > > -- > Grant Yeah, I'm sorta old fashioned that way. I can remember when electrolytic capacitors were actually wet. And tubes had numbers like an 80, or a 46, or a 2A3 for "high" powered audio even. Power transformers that made 700 volts, center tapped of course, and because of the poor iron, weighed 25 lbs. With todays modern megnetic steels, the heating losses are 10% of that one, and it weights 6 lbs. We've come a long way in my 81 years... Cheers, Gene Heskett -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author) Genes Web page From breamoreboy at yahoo.co.uk Thu Dec 24 13:51:27 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Dec 2015 18:51:27 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On 24/12/2015 14:52, Nicky Mac wrote: > what a horrible environment windows is to support anything! > (I was a UNIX professional). > seems the user profile PATH is a registry entry, and was not updated when I > deinstalled Python2.7 > still haven't figured out how to change it - I will NOT attempy a regedit. I don't have a problem, but then I don't top post on lists that greatly prefer bottom posting or interspersed answers. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From darcy at VybeNetworks.com Thu Dec 24 14:09:01 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Thu, 24 Dec 2015 14:09:01 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: <20151224140901.083908a7@imp> On Thu, 24 Dec 2015 17:30:08 +0000 (UTC) Grant Edwards wrote: > And don't get me started on those people who use those "integrated > circuits" instead of transistors, relays, and tubes... Mmmm. Tubes. Still use them in my guitar amp. Transistors just aren't the same thing. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From qurratul.ainy1 at gmail.com Thu Dec 24 14:33:18 2015 From: qurratul.ainy1 at gmail.com (Qurrat ul Ainy) Date: Thu, 24 Dec 2015 11:33:18 -0800 (PST) Subject: need some basic help In-Reply-To: <1dc1e09d-f1cc-4cf6-8535-f61ac2af9c43@googlegroups.com> References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> <1dc1e09d-f1cc-4cf6-8535-f61ac2af9c43@googlegroups.com> Message-ID: what is snippet ?? On Thursday, December 24, 2015 at 5:25:18 AM UTC+1, Benjamin Kulas wrote: > On Wednesday, December 23, 2015 at 7:53:43 PM UTC-6, Qurrat ul Ainy wrote: > > Hello, > > > > Can someone please explain this code below. I am new at Python . > > Thanks > > > > > > def receive_messages(self, msgs, time): > > for msg in msgs: > > msg.set_recv_time(time) > > self.msgs_received.extend(msgs) > > What exactly are you confused about? This looks like it is part of a class; can you post the entire class definition? Also, what is the purpose of the program that contains this snippet? From malitician at gmail.com Thu Dec 24 14:36:11 2015 From: malitician at gmail.com (malitician at gmail.com) Date: Thu, 24 Dec 2015 11:36:11 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: On Thursday, December 24, 2015 at 3:39:34 PM UTC+1, Chris Angelico wrote: > On Fri, Dec 25, 2015 at 1:17 AM, wrote: > > i am getting to believe that no one can provide a solution to this challenge, every-one here is just beating around the bush > > It's not a question of 'can' but 'will'. We will not provide the > answer to your homework question. This has already been explained to > you. > > ChrisA you are right chris it is a homework, but we are to figure out the solution first , all we need is some guidance please and not to be spoon fed like many thought in case anybody missed the question here is it >Create a class called BankAccount >Create a constructor that takes in an integer and assigns this to a `balance` property. >Create a method called `deposit` that takes in cash deposit amount and updates the balance accordingly. >Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` >Create a subclass MinimumBalanceAccount of the BankAccount class and there is a unittest that evaluate our code to check if we got it right ( i believe) and here it is below import unittest class AccountBalanceTestCases(unittest.TestCase): def setUp(self): self.my_account = BankAccount(90) def test_balance(self): self.assertEqual(self.my_account.balance, 90, msg='Account Balance Invalid') def test_deposit(self): self.my_account.deposit(90) self.assertEqual(self.my_account.balance, 180, msg='Deposit method inaccurate') def test_withdraw(self): self.my_account.withdraw(40) self.assertEqual(self.my_account.balance, 50, msg='Withdraw method inaccurate') def test_invalid_operation(self): self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", msg='Invalid transaction') def test_sub_class(self): self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No true subclass of BankAccount') and i come up with this code which i believe i'm 80 percent correct class BankAccount: def __init__(self, initial_amount): self.balance = initial_amount def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance>= amount: self.balance -= amount else: print('invalid transaction') a1 = BankAccount (90) a1.deposit(90) a1.withdraw(40) a1.withdraw(1000) class MinimumBalanceAccount(BankAccount): def __init__(self): BankAccount.__init__(self) but i kept getting this error from the unittest {"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000080"}} invalid transaction invalid transaction its like this part of the unittest explains my error [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000080"}} but i dont know what it means or where i have gone wrong in my code and for that need help on Create a subclass MinimumBalanceAccount of the BankAccount class i believe the last three lines of my code answered your question. i believe someone can help me with my problem. Thanks in advance From qurratul.ainy1 at gmail.com Thu Dec 24 14:38:52 2015 From: qurratul.ainy1 at gmail.com (Qurrat ul Ainy) Date: Thu, 24 Dec 2015 11:38:52 -0800 (PST) Subject: need some basic help In-Reply-To: References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> <1dc1e09d-f1cc-4cf6-8535-f61ac2af9c43@googlegroups.com> Message-ID: <6364f688-2022-49d9-a1ce-ed7663936745@googlegroups.com> On Thursday, December 24, 2015 at 8:33:59 PM UTC+1, Qurrat ul Ainy wrote: > what is snippet ?? > > > > On Thursday, December 24, 2015 at 5:25:18 AM UTC+1, Benjamin Kulas wrote: > > On Wednesday, December 23, 2015 at 7:53:43 PM UTC-6, Qurrat ul Ainy wrote: > > > Hello, > > > > > > Can someone please explain this code below. I am new at Python . > > > Thanks > > > > > > > > > def receive_messages(self, msgs, time): > > > for msg in msgs: > > > msg.set_recv_time(time) > > > self.msgs_received.extend(msgs) > > > > What exactly are you confused about? This looks like it is part of a class; can you post the entire class definition? Also, what is the purpose of the program that contains this snippet? Thank you steven foe the detail explanation i got it now. and thank you Andrew for recommendation I really need that From aaron.christensen at gmail.com Thu Dec 24 14:39:41 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Thu, 24 Dec 2015 14:39:41 -0500 Subject: Python and multiple user access via super cool fancy website Message-ID: Hi all, I am not sure if this is the correct venue for my question, but I'd like to submit my question just in case. I am not a programmer but I do have an incredible interest in it, so please excuse my lack of understanding if my question isn't very thorough. As an example, a website backend is developed using Python. Users can submit their input through the website and PHP (or some other language) transfers the user input from the website fields to a database such as MySQL. There is a main script called main_script.py which extracts the user data from MySQL, processes it, stores output in MySQL and sends output to the user (via webpage and email). About main_script.py # main_script.py extracts user input from MySQL, processes it, stores output in MySQL and send output to user (via webpage and email). # Inputs: User personal information such as age, dob, nationality, hobbies, and 20 or 30 other fields # Output: main_script.py is going to do something with it such as access the database and some shelve files or other py scripts. I have no clue what it's going to do, but my point is that the processing of the input to output will take longer than simply a print('Hello, %r!' %user_name). My question: I am curious to know how Python handles something like this. Let's say that there are 10, 20, 50, or even 1000 users accessing the website. They all put in their 20 to 30 pieces of input and are waiting on some fancy magic output. How exactly does that work? Can multiple users access the same script? Does the Python programmer need to code in a manner that supports this? Are requests to the script handled serially or in parallel? I've tried some searches, but not getting much except for "appending to the same file", etc. I hope my question is a good question. Thank you for your time! Aaron From kwpolska at gmail.com Thu Dec 24 15:11:03 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Thu, 24 Dec 2015 21:11:03 +0100 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: On 24 December 2015 at 20:39, Aaron Christensen wrote: > Hi all, > > I am not sure if this is the correct venue for my question, but I'd like to > submit my question just in case. I am not a programmer but I do have an > incredible interest in it, so please excuse my lack of understanding if my > question isn't very thorough. > > As an example, a website backend is developed using Python. Users can > submit their input through the website and PHP (or some other language) Cut out the middle man! Write your web app in Python, which is much saner and more modern than PHP ever will be. Write it in Django, or Flask, or Pyramid, or [insert favorite web framework here]. > transfers the user input from the website fields to a database such as > MySQL. There is a main script called main_script.py which extracts the > user data from MySQL, processes it, stores output in MySQL and sends output > to the user (via webpage and email). > > About main_script.py > # main_script.py extracts user input from MySQL, processes it, stores > output in MySQL and send output to user (via webpage and email). > # Inputs: User personal information such as age, dob, nationality, hobbies, > and 20 or 30 other fields > # Output: main_script.py is going to do something with it such as access > the database and some shelve files or other py scripts. I have no clue what > it's going to do, but my point is that the processing of the input to > output will take longer than simply a print('Hello, %r!' %user_name). Well then, figure it out first.You shouldn?t be using shelve, it?s really unsafe and error-prone ? and you already have a perfectly serviceable database! (PS. PostgreSQL is better) > My question: I am curious to know how Python handles something like this. > Let's say that there are 10, 20, 50, or even 1000 users accessing the > website. They all put in their 20 to 30 pieces of input and are waiting on > some fancy magic output. How exactly does that work? Can multiple users > access the same script? Does the Python programmer need to code in a > manner that supports this? Are requests to the script handled serially or > in parallel? We don?t know how you will structure your application. If you do the ?fancy magic? in your web app, which you should if it won?t take more than, say, 5 seconds, this will be handled by your WSGI server (eg. uwsgi), which typically can spawn threads and processes for your web application. Otherwise, you might need to use an async framework or a task queue with multiple workers. It would be better to have some idea of the desired output, though. There are many Python-based web services out there, eg. YouTube, Instagram or DISQUS. And they work well under constant load. -- Chris Warrick PGP: 5EAAEA16 From python.list at tim.thechases.com Thu Dec 24 15:48:53 2015 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 24 Dec 2015 14:48:53 -0600 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: <20151224144853.006700dc@bigbox.christie.dr> On 2015-12-24 11:36, malitician at gmail.com wrote: > it is a homework, but we are to figure out the solution first , all > we need is some guidance please and not to be spoon fed like many > thought Ah, with the intended interface as given by the tests, and the code you've already put together, you'll find comp.lang.python is a much friendlier place. > def test_invalid_operation(self): > self.assertEqual(self.my_account.withdraw(1000), "invalid > transaction", msg='Invalid transaction') The test above is failing because your withdraw() method doesn't return "invalid transaction" but rather prints it: > def withdraw(self, amount): > if self.balance>= amount: > self.balance -= amount > else: > print('invalid transaction') as gleaned from this error message: > [{"message": "Failure in line 23, in test_invalid_operation\n > self.assertEqual(self.my_account.withdraw(1000), \"invalid > transaction\", msg='Invalid transaction')\nAssertionError: Invalid > transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, > "time": "0.000080"}} The test says "I expected that calling the function would return "invalid transaction" but it didn't" (a better test-runner would also have let you know that it had returned None) Though frankly, I'd consider that a bad test, since it's an exceptional condition, so it should be checking that a custom InvalidTransactionException was raised. But sometimes you have to work with what you've got. -tkc From python at lucidity.plus.com Thu Dec 24 16:09:04 2015 From: python at lucidity.plus.com (Erik) Date: Thu, 24 Dec 2015 21:09:04 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: <567C5EF0.2080406@lucidity.plus.com> On 24/12/15 19:36, malitician at gmail.com wrote: > you are right chris > it is a homework, but we are to figure out the solution first , all we need is some guidance please and not to be spoon fed like many thought From your response, it seems that this is a homework question that a group of you are working on. That might explain some of the confusion (both from your side, posting similar questions and slightly confusing replies) and from the list side (asking why different email addresses were being used - it all seemed a bit suspicious) ... I would recommend that one of you acts as a spokesperson for the group. However, this latest response is much better. You included your code, and it looks like it would compile (I haven't run it myself, but you've included reasonable results too). Your problem looks like it's related to how the unit test harness reports its errors and I guess it's a bit unfair for you to completely have to understand how that works if you're just learning. However, the wording of the assignment _does_ give a clue as to the problem. The error seems to be coming from the test for the "withdraw" method with a value greater that what should be the current balance: > [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.000080"}} Your assignment said: >> Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` Your method is: > def withdraw(self, amount): > if self.balance>= amount: > self.balance -= amount > else: > print('invalid transaction') Can you spot the difference between what the assignment is asking for and what the method is doing? Look at both paths carefully (when called with a valid amount and when called with an amount that is too large). Pay careful attention to the words the assignment uses. > a1 = BankAccount (90) > a1.deposit(90) > a1.withdraw(40) > a1.withdraw(1000) > class MinimumBalanceAccount(BankAccount): > def __init__(self): > BankAccount.__init__(self) [snip] > i believe the last three lines of my code answered your question. When the assignment requested you create a subclass, it probably expected a subclass that would run. Have you tried creating an instance of your subclass? Try it - you might see another problem that needs fixing. E. From python.list at tim.thechases.com Thu Dec 24 16:14:21 2015 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 24 Dec 2015 15:14:21 -0600 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: <20151224151421.40229394@bigbox.christie.dr> On 2015-12-24 14:39, Aaron Christensen wrote: > I am not sure if this is the correct venue for my question, but I'd > like to submit my question just in case. I am not a programmer but > I do have an incredible interest in it, so please excuse my lack of > understanding if my question isn't very thorough. First, to do web development, you do need to be a programmer. Well, at least for anything of any complexity/novelty. But come on in, it's a fun place to be! > As an example, a website backend is developed using Python. Users > can submit their input through the website and PHP (or some other > language) transfers the user input from the website fields to a > database such as MySQL. There is a main script called > main_script.py which extracts the user data from MySQL, processes > it, stores output in MySQL and sends output to the user (via > webpage and email). A website backend can either static (just a pile of files that get served up by your web-server such as Apache or nginx, fast, but usually read-only such as a blog) or dynamic[1]. With a dynamic website, you have some language running on the server. Germane to this list, that's Python for many of us. But could be PHP, Perl, Ruby, C#, Java, Erlang, bash, or even sed/awk or Postscript. Pretty much any programming language can do the trick here. The web application then parses input from the *request*. This is usually made by the web-browser, but can also be made by other applications. The application then processes those inputs and determines the correct output. This might involve consulting a database such as PostgreSQL or MySQL to save data or gather the requested data, or it might farm that out to some other service. It might check that you're logged in. It might be purely read-only but pull information from a database or random set of files. The main thing to understand is that a request comes in, gets processed, and a response goes back. [1] or a hybrid of a dynamic site where certain assets such as images, CSS, and JavaScript are static and served outside the web application. - > # main_script.py extracts user input from MySQL, processes it, > stores output in MySQL and send output to user (via webpage and > email). # Inputs: User personal information such as age, dob, > nationality, hobbies, and 20 or 30 other fields So here it sounds like you think that the input comes from *MySQL* but it will actually come from the request. Now you can have some other (non-web) process access the same database that the web-server uses, so your inputs *can* be the database, but that doesn't sound like what you're intending to describe. > My question: I am curious to know how Python handles something > like this. Let's say that there are 10, 20, 50, or even 1000 users > accessing the website. They all put in their 20 to 30 pieces of > input and are waiting on some fancy magic output. How exactly does > that work? Can multiple users access the same script? Does the > Python programmer need to code in a manner that supports this? Are > requests to the script handled serially or in parallel? As Chris W mentions, there are lots of high-profile sites that handle hundreds of thousands of visitors. Usually they do this by splitting the load across multiple servers using a load-balancer, and with careful architecture that can accommodate characteristics of that load. Yes, multiple users can make use of the same script (it's usually run by a web-server which spawns multiple copies and farms out each request to a different sub-process). And yes, the programmer has to code to support this non-trivial aspect. It's as parallel as your architecture allows (you *can* make a single-threaded server that will only serve one request at a time which can be useful in development or if you want to just share with one other user). -tkc From nmcelwaine at gmail.com Thu Dec 24 16:29:23 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Thu, 24 Dec 2015 21:29:23 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: wow - a very comprehensive answer. However it seems I have now got it correctly reinstalled with the correct environment and path (as below) So I'm back to my original problem: C:\Users\Nick>python -m idlelib ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** On doing a repair or modify to install tcl/Tk again, the same result. C:\Users\Nick>python -c "import sys; print(*sys.path, sep='\n')" gives C:\Python\Python35\python35.zip C:\Python\Python35\DLLs C:\Python\Python35\lib C:\Python\Python35 C:\Python\Python35\lib\site-packages This looks OK, Python35 directory contains Lib and tcl as it does on my now working Win7 system, and Lib contains tkinter C:\Users\Nick>path PATH=C:\Python\Python35\Scripts\;C:\Python\Python35\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static; From kai.peters at gmail.com Thu Dec 24 17:04:40 2015 From: kai.peters at gmail.com (KP) Date: Thu, 24 Dec 2015 14:04:40 -0800 (PST) Subject: Idiom for this case? Message-ID: <86270a67-afff-42a4-a940-9f825fb57146@googlegroups.com> Given: cfg = {'c': ('3840', '1024'), 'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, 'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')}, 'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}} for config in cfg: if config != 'canvas': print config Is there an idiom that combines the 'for...' & the 'if..' lines into one? From kai.peters at gmail.com Thu Dec 24 17:11:49 2015 From: kai.peters at gmail.com (KP) Date: Thu, 24 Dec 2015 14:11:49 -0800 (PST) Subject: Is there an idiom for this? Message-ID: <08289d1a-a032-490f-963f-cc40ec0d81e3@googlegroups.com> Given: cfg = {'c': ('3840', '1024'), 'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, 'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')}, 'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}} for config in cfg: if config != 'c': print config Is there an idiom that combines the 'for...' & the 'if..' lines into one? From tjreedy at udel.edu Thu Dec 24 17:14:33 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Dec 2015 17:14:33 -0500 Subject: need some basic help In-Reply-To: References: <90cc0071-7c78-4974-88ad-60ff89649c95@googlegroups.com> <1dc1e09d-f1cc-4cf6-8535-f61ac2af9c43@googlegroups.com> Message-ID: On 12/24/2015 2:33 PM, Qurrat ul Ainy wrote: > what is snippet ?? Search 'snippet definition' on the web with your browser. It comes from 'snip', so something 'snipped'. -- Terry Jan Reedy From no.email at nospam.invalid Thu Dec 24 17:15:33 2015 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 24 Dec 2015 14:15:33 -0800 Subject: Is there an idiom for this? References: <08289d1a-a032-490f-963f-cc40ec0d81e3@googlegroups.com> Message-ID: <878u4jh4sa.fsf@nightsong.com> KP writes: > for config in cfg: > if config != 'c': > print config > > Is there an idiom that combines the 'for...' & the 'if..' lines into one? Maybe you actually want print [config for config in cfg if config != 'c'] That prints all the relevant keys as a list, rather than one per line. From eryksun at gmail.com Thu Dec 24 17:17:14 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 16:17:14 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 3:29 PM, Nicky Mac wrote: > > C:\Users\Nick>python -m idlelib > ** IDLE can't import Tkinter. > Your Python may not be configured for Tk. ** In the 3.5 installation directory, ensure that tkinter is installed in Lib/tkinter. There should be an "__init__.py" and several other files such as "filedialog.py". Also ensure that the DLLs directory has the extension module "_tkinter.pyd" and dependent DLLs "tcl86t.dll" and "tk86t.dll". From ben+python at benfinney.id.au Thu Dec 24 17:30:45 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 25 Dec 2015 09:30:45 +1100 Subject: Idiom for this case? References: <86270a67-afff-42a4-a940-9f825fb57146@googlegroups.com> Message-ID: <85vb7nxywa.fsf@benfinney.id.au> KP writes: > Given: > > cfg = {'c': ('3840', '1024'), > 'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, > 'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')}, > 'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}} > > for config in cfg: > if config != 'canvas': > print config Given the above data, none of the keys equal 'canvas', so the comparison is redundant if that's the data set. The chosen names are also confusing. It implies that each item of ?cfg? is a ?config?. Can you choose names that better communicate the semantics of that data structure? > Is there an idiom that combines the 'for...' & the 'if..' lines into one? This is an opportunity to learn generator expressions:: for item in (x for x in cfg if x != canvas): print item You will learn about these by working through the Python tutorial, from beginning to end . Don't skip anything, and experiment with each example to understand it before continuing. -- \ ?Anyone who believes exponential growth can go on forever in a | `\ finite world is either a madman or an economist.? ?Kenneth | _o__) Boulding | Ben Finney From kai.peters at gmail.com Thu Dec 24 17:32:55 2015 From: kai.peters at gmail.com (KP) Date: Thu, 24 Dec 2015 14:32:55 -0800 (PST) Subject: Is there an idiom for this? In-Reply-To: <878u4jh4sa.fsf@nightsong.com> References: <08289d1a-a032-490f-963f-cc40ec0d81e3@googlegroups.com> <878u4jh4sa.fsf@nightsong.com> Message-ID: Thanks Paul, you just pointed out one of my blonder moments: I actually want all nested dicts one by one, but not the one with the 'c' key... On Thursday, 24 December 2015 14:15:45 UTC-8, Paul Rubin wrote: > KP writes: > > for config in cfg: > > if config != 'c': > > print config > > > > Is there an idiom that combines the 'for...' & the 'if..' lines into one? > > Maybe you actually want > > print [config for config in cfg if config != 'c'] > > That prints all the relevant keys as a list, rather than one per line. From tjreedy at udel.edu Thu Dec 24 17:33:00 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Dec 2015 17:33:00 -0500 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On 12/24/2015 8:59 AM, Nicky Mac wrote: > Dear python Team > I think I've been wasting your time: > > C:\Users\Nick>path > PATH=C:\Python27\;C:\Python27\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program > Files\Broadcom\Broadcom 802.11 Network > Adapter;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program > Files (x86)\ATI > Technologies\ATI.ACE\Core-Static;C:\Python\Python35\Scripts\;C:\Python\Python35\ > > somehow the new py3.5 has been added to the end, not the beginning. > guess this path is what you meant by "my profile". Bizarre. I just installed 3.5.1 on top of 3.5.1rc1, on Win10 with the 64bit .exe installer, and the 3.5 dirs are at the front, where I expect them. Are you using a different version of installer? (The web version?) -- Terry Jan Reedy From tjreedy at udel.edu Thu Dec 24 17:45:38 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Dec 2015 17:45:38 -0500 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On 12/24/2015 9:59 AM, eryk sun wrote: > On Thu, Dec 24, 2015 at 5:06 AM, Nicky Mac wrote: >> >> not sure what you mean by "my profile". >> following your suggestion, looks normal: > > I meant your profile directory, "C:\Users\Nick". But printing the > package path showed the problem is in your Python 3 installation > itself. > >> C:\Users\Nick> python -c "import importlib; >> print(importlib.find_loader('idlelib').path)" >> C:\Python\Python35\lib\idlelib\__init__.pyc > > This file should not exist. Python 3 stores .pyc files in a > __pycache__ subdirectory. It won't even run "idlelib\__init__.pyc" if > "idlelib\__init__.py" exists, so your installation is incomplete and > damaged. I suggest that you uninstall Python 3.5 and then completely > remove "C:\Python\Python35" before reinstalling. 'python -m xyz', where xyz is a package name (directory on disk), runs xyx/__main__.py (or the xyz/__pycache__/__main__...34.py compiled version). This file currently contains the following implementation, subject to change. """ IDLE main entry point Run IDLE as python -m idlelib """ import idlelib.PyShell idlelib.PyShell.main() # This file does not work for 2.7; See issue 24212. The errant __init__.pyc should not directly be a problem, but does indicate something wrong, such as 2.7 files mixed into your 3.5 install (__cache__ is *not* used in 2.7). Based on my experience with this happening, you might try running chkdsk, from an elevated Command Prompt. 'python -m idlelib.idle' runs idlelib/idle.py (or the cached version) to mostly the same effect. The alternate entry has adjustments so it works in an uninstalled development repository, while still working in an installation. From a python program, 'import idlelib.idle' needed as 'import idlelib' would run idlelib/__init__.py, which is empty. -- Terry Jan Reedy From tjreedy at udel.edu Thu Dec 24 17:47:08 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Dec 2015 17:47:08 -0500 Subject: Idiom for this case? In-Reply-To: <86270a67-afff-42a4-a940-9f825fb57146@googlegroups.com> References: <86270a67-afff-42a4-a940-9f825fb57146@googlegroups.com> Message-ID: On 12/24/2015 5:04 PM, KP wrote: > Given: > > cfg = {'c': ('3840', '1024'), > 'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, > 'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')}, > 'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}} > > for config in cfg: > if config != 'canvas': > print config > > Is there an idiom that combines the 'for...' & the 'if..' lines into one? No. -- Terry Jan Reedy From eryksun at gmail.com Thu Dec 24 17:50:04 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 16:50:04 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 4:33 PM, Terry Reedy wrote: >> somehow the new py3.5 has been added to the end, not the beginning. >> guess this path is what you meant by "my profile". > > Bizarre. I just installed 3.5.1 on top of 3.5.1rc1, on Win10 with the 64bit > .exe installer, and the 3.5 dirs are at the front, where I expect them. Are > you using a different version of installer? (The web version?) If you install just for the current user, the installer modifies only the user's "HKCU\Environment" key in the registry. When you log on, or when Explorer reloads its environment, the value of PATH is formed by concatenating the user value to the end of the system value. From eryksun at gmail.com Thu Dec 24 18:42:36 2015 From: eryksun at gmail.com (eryk sun) Date: Thu, 24 Dec 2015 17:42:36 -0600 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: On Thu, Dec 24, 2015 at 4:45 PM, Terry Reedy wrote: > >> This file should not exist. Python 3 stores .pyc files in a >> __pycache__ subdirectory. It won't even run "idlelib\__init__.pyc" if >> "idlelib\__init__.py" exists, so your installation is incomplete and >> damaged. I suggest that you uninstall Python 3.5 and then completely >> remove "C:\Python\Python35" before reinstalling. > > 'python -m xyz', where xyz is a package name (directory on disk), runs > xyx/__main__.py (or the xyz/__pycache__/__main__...34.py compiled version). Running "-m idlelib" still imports idlelib, which executes __init__.py(c). For example, I modified __init__.py to print a message: C:\>py -3 -m idlelib Here I am. Specifically, runpy._run_module_as_main('idlelib', 1) calls runpy._get_module_details, which recurs to get the details for "idlelib.__main__". but first it executes __import__("idlelib") to "avoid catching initialization errors". It returns the module spec and the code object. Then _run_module_as_main calls runpy._run_code to exec the code in the namespace of __main__. That said, Python 3's import system should ignore a .pyc beside a .py file, because it looks for .pyc files in the __pycache__ subdirectory. It only executes "idlelib\__init__.pyc" if the corresponding .py file is missing. That's why I said Nicky's installation was both incomplete (missing "__init__.py") and damaged (somehow containing a Python 2.7 "__init__.pyc"), so I suggested a completely fresh install. Apparently that didn't help, so I presume for some reason it's not actually installing the _tkinter extension module and its dependencies. From cs at zip.com.au Thu Dec 24 22:06:08 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 25 Dec 2015 14:06:08 +1100 Subject: can i subscribe python mailing list? In-Reply-To: <20151224222223.HM.0000000000005Ua@wjm0621.wwl1499.hanmail.net> References: <20151224222223.HM.0000000000005Ua@wjm0621.wwl1499.hanmail.net> Message-ID: <20151225030608.GA16707@cskk.homeip.net> On 24Dec2015 22:22, ??? wrote: > i want to subscribe mailing list > [1][IMG] You can do that here: https://mail.python.org/mailman/listinfo/python-list Cheers, Cameron Simpson From jsf80238 at gmail.com Fri Dec 25 00:23:58 2015 From: jsf80238 at gmail.com (Jason Friedman) Date: Thu, 24 Dec 2015 22:23:58 -0700 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: > I am not sure if this is the correct venue for my question, but I'd like to > submit my question just in case. I am not a programmer but I do have an > incredible interest in it, so please excuse my lack of understanding if my > question isn't very thorough. > > As an example, a website backend is developed using Python. Users can > submit their input through the website and PHP (or some other language) > transfers the user input from the website fields to a database such as > MySQL. There is a main script called main_script.py which extracts the > user data from MySQL, processes it, stores output in MySQL and sends output > to the user (via webpage and email). > > About main_script.py > # main_script.py extracts user input from MySQL, processes it, stores > output in MySQL and send output to user (via webpage and email). > # Inputs: User personal information such as age, dob, nationality, hobbies, > and 20 or 30 other fields > # Output: main_script.py is going to do something with it such as access > the database and some shelve files or other py scripts. I have no clue what > it's going to do, but my point is that the processing of the input to > output will take longer than simply a print('Hello, %r!' %user_name). > > My question: I am curious to know how Python handles something like this. > Let's say that there are 10, 20, 50, or even 1000 users accessing the > website. They all put in their 20 to 30 pieces of input and are waiting on > some fancy magic output. How exactly does that work? Can multiple users > access the same script? Does the Python programmer need to code in a > manner that supports this? Are requests to the script handled serially or > in parallel? I have a hunch that you do not want to write the program, nor do you want to see exactly how a programmer would write it? The question is more like asking a heart surgeon how she performs heart surgery: you don't plan to do it yourself, but you want a general idea of how it is done? How do you keep the patient from bleeding to death? Does the heart stop while performing the surgery, and if yes, how does the patient stay alive? From kwpolska at gmail.com Fri Dec 25 03:59:07 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Fri, 25 Dec 2015 09:59:07 +0100 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: [Forwarding your message to the mailing list ? please use the Reply All (or Reply to List) button in the future] On 25 December 2015 at 05:02, Aaron Christensen wrote: > Hi Chris, > > Thank you for your response and information. I enjoy doing Python on my > free time so when I get closer to some kind of web application, then I can > provide more information. > > Thanks for pointing me in the right direction so far. I will replace any > shelve usage with the database. I also started looking at WSGI servers and > just found a great deal of information on fullstackpython.com. Full Stack Python is a good resource, which teaches many things considered best practices in the Python web world (I personally recommend uWSGI instead of Gunicorn, but that?s mainly just my preference) > I have some experience in PHP (which is why I mentioned it). I am > unfamiliar with Django, Flask, or Pyramid. I am looking into Django, but am > a little hesitant because of all the time I spent learning PHP. I?m sorry, but you wasted your time. PHP is an awful language with multiple problems and bad design decisions. Here?s some laughing stock: http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ http://reddit.com/r/lolphp http://phpsadness.com/ On the other hand, Python web frameworks are really fun and easy to learn, even though their general design is a bit different from PHP?s: https://docs.djangoproject.com/en/1.9/intro/tutorial01/ http://tutorial.djangogirls.org/en/ -- Chris Warrick PGP: 5EAAEA16 From oneman at onemanifest.net Fri Dec 25 05:17:52 2015 From: oneman at onemanifest.net (oneman at onemanifest.net) Date: Fri, 25 Dec 2015 11:17:52 +0100 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: <6C07A3C1-5FD1-4741-94ED-FD77EC71ED2A@onemanifest.net> > On 25 December 2015 at 05:02, Aaron Christensen > wrote: >> Hi Chris, >> >> Thank you for your response and information. I enjoy doing Python on my >> free time so when I get closer to some kind of web application, then I can >> provide more information. >> >> Thanks for pointing me in the right direction so far. I will replace any >> shelve usage with the database. I also started looking at WSGI servers and >> just found a great deal of information on fullstackpython.com. > > Full Stack Python is a good resource, which teaches many things > considered best practices in the Python web world (I personally > recommend uWSGI instead of Gunicorn, but that?s mainly just my > preference) > >> I have some experience in PHP (which is why I mentioned it). I am >> unfamiliar with Django, Flask, or Pyramid. I am looking into Django, but am >> a little hesitant because of all the time I spent learning PHP. > > I?m sorry, but you wasted your time. PHP is an awful language with > multiple problems and bad design decisions. Here?s some laughing > stock: > > http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ > http://reddit.com/r/lolphp > http://phpsadness.com/ > > On the other hand, Python web frameworks are really fun and easy to > learn, even though their general design is a bit different from PHP?s: > > https://docs.djangoproject.com/en/1.9/intro/tutorial01/ > http://tutorial.djangogirls.org/en/ If you want to get a good overview of what it means to use a python web framework, try Miguel Grinberg?s great flask tutorial [1]. It?s based on flask, a more lightweight web framework compared to django, but the basic principles are the same. He covers about anything you need to know in easy to follow lessons. Only basic python knowledge is required. [1] http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world my 2 cts, oneman From aaron.christensen at gmail.com Fri Dec 25 07:08:53 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Fri, 25 Dec 2015 07:08:53 -0500 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: Hi Jason, What gives you that idea? On Dec 25, 2015 12:23 AM, "Jason Friedman" wrote: > > I am not sure if this is the correct venue for my question, but I'd like > to > > submit my question just in case. I am not a programmer but I do have an > > incredible interest in it, so please excuse my lack of understanding if > my > > question isn't very thorough. > > > > As an example, a website backend is developed using Python. Users can > > submit their input through the website and PHP (or some other language) > > transfers the user input from the website fields to a database such as > > MySQL. There is a main script called main_script.py which extracts the > > user data from MySQL, processes it, stores output in MySQL and sends > output > > to the user (via webpage and email). > > > > About main_script.py > > # main_script.py extracts user input from MySQL, processes it, stores > > output in MySQL and send output to user (via webpage and email). > > # Inputs: User personal information such as age, dob, nationality, > hobbies, > > and 20 or 30 other fields > > # Output: main_script.py is going to do something with it such as access > > the database and some shelve files or other py scripts. I have no clue > what > > it's going to do, but my point is that the processing of the input to > > output will take longer than simply a print('Hello, %r!' %user_name). > > > > My question: I am curious to know how Python handles something like > this. > > Let's say that there are 10, 20, 50, or even 1000 users accessing the > > website. They all put in their 20 to 30 pieces of input and are waiting > on > > some fancy magic output. How exactly does that work? Can multiple users > > access the same script? Does the Python programmer need to code in a > > manner that supports this? Are requests to the script handled serially > or > > in parallel? > > I have a hunch that you do not want to write the program, nor do you > want to see exactly how a programmer would write it? > > The question is more like asking a heart surgeon how she performs > heart surgery: you don't plan to do it yourself, but you want a > general idea of how it is done? How do you keep the patient from > bleeding to death? Does the heart stop while performing the surgery, > and if yes, how does the patient stay alive? > From aaron.christensen at gmail.com Fri Dec 25 07:11:47 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Fri, 25 Dec 2015 07:11:47 -0500 Subject: Python and multiple user access via super cool fancy website In-Reply-To: <6C07A3C1-5FD1-4741-94ED-FD77EC71ED2A@onemanifest.net> References: <6C07A3C1-5FD1-4741-94ED-FD77EC71ED2A@onemanifest.net> Message-ID: Great thank you! I will look into it. I watched some tutorials on Django last night. It appears to be somewhat of a bootstrap but for the backend. I'm not sure if my opinion is correct. On Dec 25, 2015 5:27 AM, wrote: > > On 25 December 2015 at 05:02, Aaron Christensen > > wrote: > >> Hi Chris, > >> > >> Thank you for your response and information. I enjoy doing Python on my > >> free time so when I get closer to some kind of web application, then I > can > >> provide more information. > >> > >> Thanks for pointing me in the right direction so far. I will replace > any > >> shelve usage with the database. I also started looking at WSGI servers > and > >> just found a great deal of information on fullstackpython.com. > > > > Full Stack Python is a good resource, which teaches many things > > considered best practices in the Python web world (I personally > > recommend uWSGI instead of Gunicorn, but that?s mainly just my > > preference) > > > >> I have some experience in PHP (which is why I mentioned it). I am > >> unfamiliar with Django, Flask, or Pyramid. I am looking into Django, > but am > >> a little hesitant because of all the time I spent learning PHP. > > > > I?m sorry, but you wasted your time. PHP is an awful language with > > multiple problems and bad design decisions. Here?s some laughing > > stock: > > > > http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ > > http://reddit.com/r/lolphp > > http://phpsadness.com/ > > > > On the other hand, Python web frameworks are really fun and easy to > > learn, even though their general design is a bit different from PHP?s: > > > > https://docs.djangoproject.com/en/1.9/intro/tutorial01/ > > http://tutorial.djangogirls.org/en/ > > If you want to get a good overview of what it means to use a python web > framework, try Miguel Grinberg?s great flask tutorial [1]. It?s based on > flask, a more lightweight web framework compared to django, but the basic > principles are the same. He covers about anything you need to know in easy > to follow lessons. Only basic python knowledge is required. > > [1] > http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world > > my 2 cts, > > oneman > > -- > https://mail.python.org/mailman/listinfo/python-list > From aaron.christensen at gmail.com Fri Dec 25 07:15:26 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Fri, 25 Dec 2015 07:15:26 -0500 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: LOL. Thanks! PHP was definitely not very easy to pick up and I'm still having some issues. Last night I watched some tutorials on Django and plan on reading all of the links on the docs page of Django. I will also look at your recommendation. I think that will give me a good understanding. Hopefully Django isn't a copy/paste kinda "put your website together" like WordPress because my objective is to actually learn Python. On Dec 25, 2015 3:59 AM, "Chris Warrick" wrote: > [Forwarding your message to the mailing list ? please use the Reply > All (or Reply to List) button in the future] > > On 25 December 2015 at 05:02, Aaron Christensen > wrote: > > Hi Chris, > > > > Thank you for your response and information. I enjoy doing Python on my > > free time so when I get closer to some kind of web application, then I > can > > provide more information. > > > > Thanks for pointing me in the right direction so far. I will replace any > > shelve usage with the database. I also started looking at WSGI servers > and > > just found a great deal of information on fullstackpython.com. > > Full Stack Python is a good resource, which teaches many things > considered best practices in the Python web world (I personally > recommend uWSGI instead of Gunicorn, but that?s mainly just my > preference) > > > I have some experience in PHP (which is why I mentioned it). I am > > unfamiliar with Django, Flask, or Pyramid. I am looking into Django, > but am > > a little hesitant because of all the time I spent learning PHP. > > I?m sorry, but you wasted your time. PHP is an awful language with > multiple problems and bad design decisions. Here?s some laughing > stock: > > http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ > http://reddit.com/r/lolphp > http://phpsadness.com/ > > On the other hand, Python web frameworks are really fun and easy to > learn, even though their general design is a bit different from PHP?s: > > https://docs.djangoproject.com/en/1.9/intro/tutorial01/ > http://tutorial.djangogirls.org/en/ > > -- > Chris Warrick > PGP: 5EAAEA16 > From nmcelwaine at gmail.com Fri Dec 25 09:12:00 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Fri, 25 Dec 2015 14:12:00 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: thanks again for continuing to address my problem. all those files are present as required. This is a hard slog. Maybe I should give up and fallback to my now working win 7 system until a resolution crops up via an update/upgrade. Have a happy and peaceful Christmas On 24 December 2015 at 22:17, eryk sun wrote: > On Thu, Dec 24, 2015 at 3:29 PM, Nicky Mac wrote: > > > > C:\Users\Nick>python -m idlelib > > ** IDLE can't import Tkinter. > > Your Python may not be configured for Tk. ** > > In the 3.5 installation directory, ensure that tkinter is installed in > Lib/tkinter. There should be an "__init__.py" and several other files > such as "filedialog.py". Also ensure that the DLLs directory has the > extension module "_tkinter.pyd" and dependent DLLs "tcl86t.dll" and > "tk86t.dll". > -- Nick "Mac" McElwaine From nmcelwaine at gmail.com Fri Dec 25 10:45:00 2015 From: nmcelwaine at gmail.com (Nicky Mac) Date: Fri, 25 Dec 2015 15:45:00 +0000 Subject: unable to open IDLE for Python3.50rc1 on windows10 64bit AMD In-Reply-To: References: Message-ID: problem solved :_ I upgraded to 3.5.1 just released, and it works fine! (except pillow and pygame installs still dont work, but that's not your problem) Enjoy the holidays On 25 December 2015 at 14:12, Nicky Mac wrote: > thanks again for continuing to address my problem. > all those files are present as required. > This is a hard slog. > Maybe I should give up and fallback to my now working win 7 system > until a resolution crops up via an update/upgrade. > Have a happy and peaceful Christmas > > > On 24 December 2015 at 22:17, eryk sun wrote: > >> On Thu, Dec 24, 2015 at 3:29 PM, Nicky Mac wrote: >> > >> > C:\Users\Nick>python -m idlelib >> > ** IDLE can't import Tkinter. >> > Your Python may not be configured for Tk. ** >> >> In the 3.5 installation directory, ensure that tkinter is installed in >> Lib/tkinter. There should be an "__init__.py" and several other files >> such as "filedialog.py". Also ensure that the DLLs directory has the >> extension module "_tkinter.pyd" and dependent DLLs "tcl86t.dll" and >> "tk86t.dll". >> > > > > -- > Nick "Mac" McElwaine > -- Nick "Mac" McElwaine From yanzhipingliu at gmail.com Fri Dec 25 11:49:27 2015 From: yanzhipingliu at gmail.com (Ping Liu) Date: Fri, 25 Dec 2015 08:49:27 -0800 Subject: Python compiling with third party tools Message-ID: I am developing an open source software for optimization purpose. We have interface to a list of solvers or solver interfaces like Openopt, Cylp, GLPK, CBC, SCip, Cplex, etc. Now the sponsor asks us to compile the python code, and wrap all the third party tools with it so that they do not need to install any of those tools or even python itself. Does anyone know how to do this? Any advice is appreciated. Ping From jsf80238 at gmail.com Fri Dec 25 12:22:41 2015 From: jsf80238 at gmail.com (Jason Friedman) Date: Fri, 25 Dec 2015 10:22:41 -0700 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: >> I have a hunch that you do not want to write the program, nor do you >> want to see exactly how a programmer would write it? >> >> The question is more like asking a heart surgeon how she performs >> heart surgery: you don't plan to do it yourself, but you want a >> general idea of how it is done? How do you keep the patient from >> bleeding to death? Does the heart stop while performing the surgery, >> and if yes, how does the patient stay alive? > What gives you that idea? You said: I am not a programmer but I do have an incredible interest in it. Many people say: I am not a programmer but I want to become one. I just wanted to make sure your actual question was being answered. Sounds like it is. Also, the general practice is to put your response at the bottom of your reply. From kwpolska at gmail.com Fri Dec 25 12:38:19 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Fri, 25 Dec 2015 18:38:19 +0100 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: On 25 December 2015 at 13:15, Aaron Christensen wrote: > LOL. Thanks! PHP was definitely not very easy to pick up and I'm still > having some issues. Last night I watched some tutorials on Django and plan > on reading all of the links on the docs page of Django. I will also look at > your recommendation. I think that will give me a good understanding. > Hopefully Django isn't a copy/paste kinda "put your website together" like > WordPress because my objective is to actually learn Python. That?s not what WordPress is. WordPress is a blog engine that can be used as a general-purpose CMS, full stop. You don?t need any coding skills to build a website with WordPress. Many people have done that ? especially on wordpress.com or shared hosting services with one-click WP installers; and even without an installer, setting up WordPress on shared hosting requires a FTP client and reading comprehension anyways. On the other hand, Django is nothing like this. Django can do anything you tell it to, and you need to write code. While Django handles some things for you (eg. the admin panel or the ORM), you still need to write models, views, URL configuration, etc. yourself. You need an understanding of relational databases, HTTP, HTML/CSS, the template engine, and you do need to write actual code. And while there are tons of ready-made blog applications for Django that you can install and use, you can (and should!) write your own in an hour or two. And it?s a lot more fun to do that than lazily downloading something. -- Chris Warrick PGP: 5EAAEA16 From aaron.christensen at gmail.com Fri Dec 25 12:55:46 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Fri, 25 Dec 2015 12:55:46 -0500 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: On Dec 25, 2015 12:22 PM, "Jason Friedman" wrote: > > >> I have a hunch that you do not want to write the program, nor do you > >> want to see exactly how a programmer would write it? > >> > >> The question is more like asking a heart surgeon how she performs > >> heart surgery: you don't plan to do it yourself, but you want a > >> general idea of how it is done? How do you keep the patient from > >> bleeding to death? Does the heart stop while performing the surgery, > >> and if yes, how does the patient stay alive? > > > What gives you that idea? > > You said: I am not a programmer but I do have an incredible interest in it. > > Many people say: I am not a programmer but I want to become one. > > I just wanted to make sure your actual question was being answered. > Sounds like it is. > > Also, the general practice is to put your response at the bottom of your reply. Understood. I say I'm not a programmer because my degrees and day job are not programing. Thanks for making sure my question was answered! My question was answered but it also made me think of several other different things. From aaron.christensen at gmail.com Fri Dec 25 12:58:11 2015 From: aaron.christensen at gmail.com (Aaron Christensen) Date: Fri, 25 Dec 2015 12:58:11 -0500 Subject: Python and multiple user access via super cool fancy website In-Reply-To: References: Message-ID: On Dec 25, 2015 12:38 PM, "Chris Warrick" wrote: > > On 25 December 2015 at 13:15, Aaron Christensen > wrote: > > LOL. Thanks! PHP was definitely not very easy to pick up and I'm still > > having some issues. Last night I watched some tutorials on Django and plan > > on reading all of the links on the docs page of Django. I will also look at > > your recommendation. I think that will give me a good understanding. > > Hopefully Django isn't a copy/paste kinda "put your website together" like > > WordPress because my objective is to actually learn Python. > > That?s not what WordPress is. WordPress is a blog engine that can be > used as a general-purpose CMS, full stop. You don?t need any coding > skills to build a website with WordPress. Many people have done that ? > especially on wordpress.com or shared hosting services with one-click > WP installers; and even without an installer, setting up WordPress on > shared hosting requires a FTP client and reading comprehension > anyways. > > On the other hand, Django is nothing like this. Django can do anything > you tell it to, and you need to write code. While Django handles some > things for you (eg. the admin panel or the ORM), you still need to > write models, views, URL configuration, etc. yourself. You need an > understanding of relational databases, HTTP, HTML/CSS, the template > engine, and you do need to write actual code. > > And while there are tons of ready-made blog applications for Django > that you can install and use, you can (and should!) write your own in > an hour or two. And it?s a lot more fun to do that than lazily > downloading something. > > -- > Chris Warrick > PGP: 5EAAEA16 > -- > https://mail.python.org/mailman/listinfo/python-list That's excellent news. I am looking forward to learning and working with Django. I imagine that I will have Django related questions in a few weeks or so. I appreciate your lengthy responses and explanations! Thank you, Aaron From pythonml at fuckaround.org Fri Dec 25 15:35:11 2015 From: pythonml at fuckaround.org (Pol Hallen) Date: Fri, 25 Dec 2015 21:35:11 +0100 Subject: CGI Message-ID: <567DA87F.40803@fuckaround.org> Merry Christmas to all :-) A (newbie) question: I'd like learn about CGI pyhton script to create some utility using http://localhost/python_script01.py Something like that: #!/usr/bin/python print "Content-type: text/html" print print "" print "
Hello!
" print "" How can I execute a local command (like ls or similar) and show output via browser? I didn't find enough documentation to work with python and CGI :-/ Is python not good language to use it with CGI? Thanks for help! :) Pol From greg.ewing at canterbury.ac.nz Fri Dec 25 17:36:29 2015 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 26 Dec 2015 11:36:29 +1300 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: Grant Edwards wrote: > And don't get me started on those people who use those "integrated > circuits" instead of transistors, relays, and tubes... Transistors? You don't know how good you had it. In my day we had to poke the dopant atoms into the silicon one at a time with the point of a needle. -- Greg From jeanbigboute at gmail.com Fri Dec 25 18:01:51 2015 From: jeanbigboute at gmail.com (jeanbigboute at gmail.com) Date: Fri, 25 Dec 2015 15:01:51 -0800 (PST) Subject: Recursively listing the contents of a package? Message-ID: As an occasional Python user, I'd like to be able to get for myself a high-level overview of a package's capabilities. I can do this after a fashion interactively in IPython using tab completes. e.g. import numpy as np np. ---> Big list of capabilities, highlight one item np.array --> Nothing in the dropdown np.random. --> ~~75 items in dropdown np.random.test --> 3 items in dropdown For big packages like numpy, matplotlib, etc., this is slow. My web searches have resulted in pointers to dir, help, inspect, getattr, hasattr, pydoc, and so on. As far as I can tell, these will give you information if you know what you are seeking. 99% of the time, I don't know what I don't know. Is there a way to determine if a method/function/correct term has items underneath it? If such a thing exists, I think I could write the code to descend through a package's functions/methods, make a list of nodes and edges, send it to networkx, and create a graph of a package's capabilities. Thanks, JBB From princeudo52 at gmail.com Fri Dec 25 18:05:35 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Fri, 25 Dec 2015 15:05:35 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: i have gotten the answer of that problem From princeudo52 at gmail.com Fri Dec 25 18:08:17 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Fri, 25 Dec 2015 15:08:17 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> Message-ID: Create a function manipulate_data that does the following Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure Based off the first parameter return the reverse of a list or add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set return the keys of a dictionary. From princeudo52 at gmail.com Fri Dec 25 18:09:54 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Fri, 25 Dec 2015 15:09:54 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> Message-ID: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> #my solution is: def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}): return dict_data.keys() def manipulate_data( alist, list_data = [2,8,16,23,14]): return list_data.reverse() def manipulate_data(aset, set_data = {"bee","cee","dee"}): set_data = {"bee","cee","dee"} set_data.update("ANDELA","TIA","AFRICA") return dictionary_data #please what is wrong with my code From python at lucidity.plus.com Fri Dec 25 19:01:32 2015 From: python at lucidity.plus.com (Erik) Date: Sat, 26 Dec 2015 00:01:32 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <8b40be10-d859-418d-b6b6-f687463a4847@googlegroups.com> <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: <567DD8DC.7020806@lucidity.plus.com> Hi, I appreciate that you've made an effort this time to write some code, but have you attempted to try to _execute_ any of this? [I can see that the answer must be "no"] On 25/12/15 23:09, princeudo52 at gmail.com wrote: > #my solution is: > def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}): > return dict_data.keys() > > def manipulate_data( alist, list_data = [2,8,16,23,14]): > return list_data.reverse() > > def manipulate_data(aset, set_data = {"bee","cee","dee"}): > set_data = {"bee","cee","dee"} > set_data.update("ANDELA","TIA","AFRICA") > return dictionary_data > #please what is wrong with my code If you try to execute it (by writing a test that calls the functions), you will get errors. Those errors will help you to fix it. If you get to the point where there is an error you really can't work out for yourself then you can ask a specific question related to what it is you don't understand about the error. It looks like you're just typing in something and sending it to the list first rather than the Python interpreter. If you want to learn how to program well, then you need to learn how to interpret the compiler/parser error messages or exceptions you get and work out what is wrong for yourself. You can only do that by running your code. I'll give you a hint - read the words of your assignment very carefully. It says "a function" (not "several functions") that "Accepts as the first parameter a string". Look at what it then says about the second parameter, based on that first parameter. Work on it from there and when you get really stuck, post the code and the Python error you get and why you don't understand it (saying what you _think_ it means but why that doesn't help you would also be good). E. From tjreedy at udel.edu Fri Dec 25 19:06:53 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Dec 2015 19:06:53 -0500 Subject: Recursively listing the contents of a package? In-Reply-To: References: Message-ID: On 12/25/2015 6:01 PM, jeanbigboute at gmail.com wrote: > As an occasional Python user, I'd like to be able to get for myself a high-level overview of a package's capabilities. I can do this after a fashion interactively in IPython using tab completes. > > e.g. > import numpy as np > np. ---> Big list of capabilities, highlight one item > np.array --> Nothing in the dropdown > np.random. --> ~~75 items in dropdown > np.random.test --> 3 items in dropdown > > For big packages like numpy, matplotlib, etc., this is slow. > > My web searches have resulted in pointers to dir, help, inspect, getattr, hasattr, pydoc, and so on. As far as I can tell, these will give you information if you know what you are seeking. 99% of the time, I don't know what I don't know. > > Is there a way to determine if a method/function/correct term has items underneath it? > > If such a thing exists, I think I could write the code to descend through a package's functions/methods, make a list of nodes and edges, send it to networkx, and create a graph of a package's capabilities. IDLE has a module browser (called a Class Browser. , because that is what is started as), that displays a tree of module objects. Just like a directory tree, nodes can be expanded or not. -- Terry Jan Reedy From cs at zip.com.au Fri Dec 25 19:09:41 2015 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 26 Dec 2015 11:09:41 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: <20151226000941.GA36035@cskk.homeip.net> On 25Dec2015 15:05, princeudo52 at gmail.com wrote: >i have gotten the answer of that problem Please include some context when posting to the list; there are many discussions and it is best to include a little more than the subject line in such things. It is also polite to post your working solution for the benefit of those who have assisted you, or for others with a similar problem. Then two more messages in quick succession: this list is not an instant messaging system. Please try to post a single message, with your question and also what code you have already. Regarding your actual question, commentry below the quoted text follows... On 25Dec2015 15:08, princeudo52 at gmail.com wrote: >Create a function manipulate_data that does the following >Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" >Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure >Based off the first parameter > > return the reverse of a list or > add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set > return the keys of a dictionary. > >#my solution is: >def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}): > return dict_data.keys() > >def manipulate_data( alist, list_data = [2,8,16,23,14]): > return list_data.reverse() > >def manipulate_data(aset, set_data = {"bee","cee","dee"}): > set_data = {"bee","cee","dee"} > set_data.update("ANDELA","TIA","AFRICA") > return dictionary_data >#please what is wrong with my code The most obvious thing that is wrong it that you have 3 functions here with the same name. In Python that means: define the first function and bind it to the name "manipulate_data". Then define the second and bind it to the same name as the first, discarding the first function. The define the third and bind it to the same name again, discarding the second function. Your task is asking for a _single_ function which behaves differently according to a parameter which tells it what kind of data is has been given, so you want a function which starts like this: def manipulate_data(kind, data): and you are supposed to pass in the string "list", "set" or dictionary for the first parameter, and some corresponding list, set or dictionary as the second parameter. There should _not_ be default values for either of these. Instead, your function should examine the "kind" parameter and decide what to do. So it would reasonably look like this (untested): def manipulate_data(kind, data): if kind == 'list': ... do stuff with data using it as a list ... elif kind == 'set': ... do stuff with data using it as a set ... if kind == 'dictionary': ... do stuff with data using it as a dictionary ... else: raise ValueError("invalid kind %r, expected 'list', 'set' or 'dictionary'" % (kind,)) Try starting with that and see how you go. Cheers, Cameron Simpson From steve at pearwood.info Fri Dec 25 19:14:43 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Dec 2015 11:14:43 +1100 Subject: Recursively listing the contents of a package? References: Message-ID: <567ddbf5$0$1592$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Dec 2015 10:01 am, jeanbigboute at gmail.com wrote: > As an occasional Python user, I'd like to be able to get for myself a > high-level overview of a package's capabilities. Best way to do that is to read the package's documentation on the web. [...] > Is there a way to determine if a method/function/correct term has items > underneath it? > > If such a thing exists, I think I could write the code to descend through > a package's functions/methods, make a list of nodes and edges, send it to > networkx, and create a graph of a package's capabilities. Let's say you want to analyse package aardvark. First thing is to determine whether it is an actual package, or a single module, or a "namespace package". Namespace packages are new, and I don't know anything about them, so you're on your own with them. But for the others: import aardvark if aardvark.__package__ in (None, ''): print("regular module") else: print("package") If it is a regular module, you can use dir() to get a list of names in the module: dir(aardvark) => returns ['spam', 'eggs', 'Cheese', ...] For each name, get the actual attribute and inspect what it is: import inspect obj = getattr(aardvark, 'spam') if inspect.isfunction(obj): print("it is a function") elif inspect.isclass(obj): print("it is a class") else: print("it is a %s" % type(obj).__name__) Or, instead of dir() and getattr(), you can use vars() and get a dict of {name: object}. vars(aardvark) => returns {'spam': , 'eggs': , 'Cheese': , ...} Do the same for classes: vars(aardvark.Cheese) => returns a dict of methods etc. You can build a tree showing how classes are related to each other by looking at the class.__mro__, but I believe that Python already has a class-browser: import pyclbr if you can work out how to get useful results out of it. (Frankly, I suspect it is rubbish, but maybe I just don't understand what it is for or how to use it.) If aardvark is a package, it probably contains more than one module, but they aren't automatically imported when the main module is imported. That means you can't introspect them from the main module. Instead, look in the directory where the package exists to get a list of file names: import os assert aardvark.__package__ directory = aardvark.__path__[0] os.listdir(directory) => returns ['__init__.py', 'spam.py', 'spam.pyc', 'foo.txt', 'subdir', ...] Or use os.walk to enter into the subdirectories as well. That gives you a list of modules in the package: aardvark # corresponds to directory/__init__.py aardvark.spam # directory/spam.py or spam.pyc Valid module extensions depend on the version of Python and the operating system used, but you can expect any of the following will be valid: .py # Python source code .pyc # pre-compiled byte-code .pyo # pre-compiled optimized byte-code .pyw # only on Windows .so # extension module .dll # extension module? Any other file extensions may be data files and can probably be ignored. One complication: a package may be embedded in a zip file, rather than a directory. I don't know all the details on that -- it isn't well documented, but I think it is as simple as taking the usual package tree and zipping it into a .zip file. I think this more or less gives you the details you need to know to programmatically analyse a package. -- Steven From jeanbigboute at gmail.com Fri Dec 25 19:42:43 2015 From: jeanbigboute at gmail.com (jeanbigboute at gmail.com) Date: Fri, 25 Dec 2015 16:42:43 -0800 (PST) Subject: Recursively listing the contents of a package? In-Reply-To: References: Message-ID: <9b6000e5-81da-4cc6-8701-8a1cf2a06a48@googlegroups.com> On Friday, December 25, 2015 at 4:07:43 PM UTC-8, Terry Reedy wrote: > On 12/25/2015 6:01 PM, jeanbigboute at gmail.com wrote: > > As an occasional Python user, I'd like to be able to get for myself a high-level overview of a package's capabilities. I can do this after a fashion interactively in IPython using tab completes. > ... > IDLE has a module browser (called a Class Browser. , because that is > what is started as), that displays a tree of module objects. Just like > a directory tree, nodes can be expanded or not. Thanks, I will look into IDLE. I'm currently working mostly with Notebooks. --- JBB From jeanbigboute at gmail.com Fri Dec 25 19:47:28 2015 From: jeanbigboute at gmail.com (jeanbigboute at gmail.com) Date: Fri, 25 Dec 2015 16:47:28 -0800 (PST) Subject: Recursively listing the contents of a package? In-Reply-To: <567ddbf5$0$1592$c3e8da3$5496439d@news.astraweb.com> References: <567ddbf5$0$1592$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, December 25, 2015 at 4:14:56 PM UTC-8, Steven D'Aprano wrote: > On Sat, 26 Dec 2015 10:01 am, jeanbigboute at gmail.com wrote: > > > As an occasional Python user, I'd like to be able to get for myself a > > high-level overview of a package's capabilities. > > Best way to do that is to read the package's documentation on the web. I certainly do so. Some packages are very well documented, others less so. > > [...] > > Is there a way to determine if a method/function/correct term has items > > underneath it? > > > > If such a thing exists, I think I could write the code to descend through > > a package's functions/methods, make a list of nodes and edges, send it to > > networkx, and create a graph of a package's capabilities. > > Let's say you want to analyse package aardvark. [ Detailed description] > I think this more or less gives you the details you need to know to > programmatically analyse a package. This is very helpful, thank you for the time in laying out the path. I will try to implement what you've described. It will be a good way for me to sharpen my Python skills. --- JBB From princeudo52 at gmail.com Fri Dec 25 21:04:15 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Fri, 25 Dec 2015 18:04:15 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: #i have worked over 2hours only to get this: some-one help please manipulate_data = [] item = {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45} manipulate_data.append(item) for i in reversed(manipulate_data): new = {"ANDELA", "TIA", "AFRICA"} def list_append(manipulate_data, new): manipulate_data.append(new) return new return dict.keys() print manipulate_data #this is the instruction: Create a function manipulate_data that does the following Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure Based off the first parameter return the reverse of a list or add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set return the keys of a dictionary. From princeudo52 at gmail.com Fri Dec 25 21:36:15 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Fri, 25 Dec 2015 18:36:15 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: <2f7b56f9-e7c6-4433-b8c6-3589f3bd73dd@googlegroups.com> thank you God bless you moore... From jfong at ms4.hinet.net Fri Dec 25 22:06:35 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Fri, 25 Dec 2015 19:06:35 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton Message-ID: As a tranditional language programmer like me, the result is really weird. Here is the test codes in file test1.py: -------- def outerf(): counter = 55 def innerf(): print(counter) #counter += 1 return innerf myf = outerf() -------- the result is: -------- >>> import test1 >>> test1.myf() 55 >>> -------- that's OK. But if I un-comment the line "counter += 1", then it gives me this: -------- >>> import test1 >>> test1.myf() Traceback (most recent call last): File "", line 1, in File "D:\Work\Python34\test1.py", line 41, in innerf print(counter) UnboundLocalError: local variable 'counter' referenced before assignment >>> -------- In the first situation, the local variable 'counter' can be referenced correctly. But in the second, why a statement added after the print() statement can makes this variable "disappear", even the print() won't do the right thing. Isn't it wired? please help! From ben+python at benfinney.id.au Fri Dec 25 22:41:25 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 26 Dec 2015 14:41:25 +1100 Subject: A newbie quesiton: local variable in a nested funciton References: Message-ID: <85r3i9yize.fsf@benfinney.id.au> jfong at ms4.hinet.net writes: > In the first situation, the local variable 'counter' can be referenced > correctly. But in the second, why a statement added after the print() > statement can makes this variable "disappear", even the print() won't > do the right thing. Isn't it wired? please help! The Python FAQ answers this, even using an example the same as yours . -- \ ?? a Microsoft Certified System Engineer is to information | `\ technology as a McDonalds Certified Food Specialist is to the | _o__) culinary arts.? ?Michael Bacarella | Ben Finney From rosuav at gmail.com Fri Dec 25 22:44:01 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Dec 2015 14:44:01 +1100 Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: References: Message-ID: On Sat, Dec 26, 2015 at 2:06 PM, wrote: > As a tranditional language programmer like me, the result is really weird. By "traditional", I'm guessing you mean that you know C-like languages (Java, ECMAScript/JavaScript, etc). In C, and in many languages derived from or inspired by it, variable scoping is defined by declarations that say "here begins a variable". > Here is the test codes in file test1.py: > -------- > def outerf(): > counter = 55 > def innerf(): > print(counter) > #counter += 1 > return innerf > > myf = outerf() Pike is semantically very similar to Python, but it uses C-like variable scoping. Here's an equivalent, which might help with comprehension: function outerf() { int counter = 55; void innerf() { write("%d\n", counter); int counter; counter += 1; } return innerf; } Based on that, I think you can see that having a variable declaration in the function turns things into nonsense. What you're actually wanting here is to NOT have the "int counter;" line, such that the name 'counter' refers to the outerf one. In Python, assignment inside a function creates a local variable, unless you declare otherwise. To make your example work, all you need is one statement: nonlocal counter That'll cause the name 'counter' inside innerf to refer to the same thing as it does in outerf. Hope that helps! ChrisA From orgnut at yahoo.com Fri Dec 25 23:02:42 2015 From: orgnut at yahoo.com (Larry Hudson) Date: Fri, 25 Dec 2015 20:02:42 -0800 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: On 12/25/2015 06:04 PM, princeudo52 at gmail.com wrote: > #i have worked over 2hours only to get this: some-one help please > manipulate_data = [] [snip other incorrect nonsense...] > > #this is the instruction: > Create a function manipulate_data that does the following [snip...] Let's start with your first mistake (because the rest is wrong because of this): READ YOUR INSTRUCTIONS! It says "Create a function..." Your 'solution' creates a list. A list is NOT a function. -=- Larry -=- From jeanbigboute at gmail.com Fri Dec 25 23:15:26 2015 From: jeanbigboute at gmail.com (jeanbigboute at gmail.com) Date: Fri, 25 Dec 2015 20:15:26 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Sunday, December 20, 2015 at 3:29:30 AM UTC-8, Chris Angelico wrote: [... much instruction deleted] > There is a half-and-half possibility, too; sometimes a course will > give you a challenge, and *then* introduce you to the techniques > necessary for solving it (after letting you have a shot at it on your > own). I don't like that style, myself, but it does exist, so it may be > worth skimming forward a few sections in the course to see what it > teaches next. > > But frankly, I doubt that's what's going on here. It sounds to me like the one or or more about the course may be true: a) It is being offered in a country where English is not the native language b) It may not have provided the needed background c) It suggests that students get help by posting to public discussion groups I found these sites useful when I was learning about classes in Python. Perhaps it will help these students: https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/ http://anandology.com/python-practice-book/object_oriented_programming.html From malitician at gmail.com Sat Dec 26 03:47:04 2015 From: malitician at gmail.com (malitician at gmail.com) Date: Sat, 26 Dec 2015 00:47:04 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: On Saturday, December 26, 2015 at 3:04:45 AM UTC+1, princ... at gmail.com wrote: > #i have worked over 2hours only to get this: some-one help please > manipulate_data = [] > item = {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45} > manipulate_data.append(item) > for i in reversed(manipulate_data): > new = {"ANDELA", "TIA", "AFRICA"} > def list_append(manipulate_data, new): > manipulate_data.append(new) > return new > return dict.keys() > > > print manipulate_data > #this is the instruction: > Create a function manipulate_data that does the following > Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" > Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure > Based off the first parameter > > return the reverse of a list or > add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set > return the keys of a dictionary. I am now more confused than before, as beginners like we have stated earlier, how does this solution applies to the real question ( bank account ) From jfong at ms4.hinet.net Sat Dec 26 03:56:29 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sat, 26 Dec 2015 00:56:29 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: References: Message-ID: Ben Finney at 2015/12/26 UTC+8 11:42:08AM wrote: > The Python FAQ answers this, even using an example the same as yours > . > Thank you, Ben. It's amazing that you seem to know every piece of Python information hiding in the web:-) see this question listed in python core language's Q&A makes me feel better for I am not the only one who commit this kind of crime. I should read this Q&A throughly before going any further. --Jach From malitician at gmail.com Sat Dec 26 04:01:18 2015 From: malitician at gmail.com (malitician at gmail.com) Date: Sat, 26 Dec 2015 01:01:18 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: <1294f59c-aa27-4f71-a7ba-29db98ef7750@googlegroups.com> On Thursday, December 24, 2015 at 9:58:54 PM UTC+1, Tim Chase wrote: > On 2015-12-24 11:36, malitician at gmail.com wrote: > > it is a homework, but we are to figure out the solution first , all > > we need is some guidance please and not to be spoon fed like many > > thought > > Ah, with the intended interface as given by the tests, and the code > you've already put together, you'll find comp.lang.python is a much > friendlier place. > > > > def test_invalid_operation(self): > > self.assertEqual(self.my_account.withdraw(1000), "invalid > > transaction", msg='Invalid transaction') > > The test above is failing because your withdraw() method doesn't > return "invalid transaction" but rather prints it: > > > def withdraw(self, amount): > > if self.balance>= amount: > > self.balance -= amount > > else: > > print('invalid transaction') > > as gleaned from this error message: > > > [{"message": "Failure in line 23, in test_invalid_operation\n > > self.assertEqual(self.my_account.withdraw(1000), \"invalid > > transaction\", msg='Invalid transaction')\nAssertionError: Invalid > > transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, > > "time": "0.000080"}} > > The test says "I expected that calling the function would return > "invalid transaction" but it didn't" (a better test-runner would > also have let you know that it had returned None) > > Though frankly, I'd consider that a bad test, since it's an > exceptional condition, so it should be checking that a custom > InvalidTransactionException was raised. But sometimes you have to > work with what you've got. > > -tkc you and others here saved my days , instead of "RETURN" i have been using "PRINT". i never knew the differences earlier . Problem solved , thanks for having guys like all of you here. I'm just a week old into python programming and i have learned a lot .Merry xmas From jfong at ms4.hinet.net Sat Dec 26 04:07:20 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sat, 26 Dec 2015 01:07:20 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: References: Message-ID: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> Chris Angelico at 2015/12/26 UTC+8 11:44:21AM wrote: > Pike is semantically very similar to Python, but it uses C-like > variable scoping. Here's an equivalent, which might help with > comprehension: > > function outerf() > { > int counter = 55; > void innerf() > { > write("%d\n", counter); > int counter; > counter += 1; > } > return innerf; > } Hi! ChrisA, this is the first time I hear the name "Pike" programming language:-) > Based on that, I think you can see that having a variable declaration > in the function turns things into nonsense. What you're actually > wanting here is to NOT have the "int counter;" line, such that the > name 'counter' refers to the outerf one. > > In Python, assignment inside a function creates a local variable, > unless you declare otherwise. To make your example work, all you need > is one statement: > > nonlocal counter > > That'll cause the name 'counter' inside innerf to refer to the same > thing as it does in outerf. Thank you for the explanation. It reminds me to dig out something which seems I had been read before. It's about nested scope in the book "Learning Python" by Mark Lutz. "An assignment (X = value) creates or changes the name X in the current local scope, by default. If X is declared global within the function, the assignment creates or changes the name X in the enclosing module's scope instead. If, on the other hand, X is declared nonlocal within the function in 3.X (only), the assignment changes the name X in the closest enclosing function's local scope." I shouldn't forget this:-( > Hope that helps! You have a correct answer. Thanks again. --Jach From ben+python at benfinney.id.au Sat Dec 26 04:37:23 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 26 Dec 2015 20:37:23 +1100 Subject: A newbie quesiton: local variable in a nested funciton References: Message-ID: <85mvsxy2i4.fsf@benfinney.id.au> jfong at ms4.hinet.net writes: > Thank you, Ben. It's amazing that you seem to know every piece of > Python information hiding in the web:-) You're welcome, I'm glad to help. As for the ?hiding?, the answer is in the Python documentation itself. > see this question listed in python core language's Q&A makes me feel > better for I am not the only one who commit this kind of crime. Never feel embarrassed of not knowing something; we should all be active on the edge of our own ignorance. The embarrassment would be in not seeking to improve our understanding. > I should read this Q&A throughly before going any further. Searching in the official documentation, and in archives of community forums, is an essential skill to learn for a programmer. I wish you good fortune in improving that skill :-) -- \ ?Nothing is more sacred than the facts.? ?Sam Harris, _The End | `\ of Faith_, 2004 | _o__) | Ben Finney From pythonml at fuckaround.org Sat Dec 26 04:41:51 2015 From: pythonml at fuckaround.org (Pol Hallen) Date: Sat, 26 Dec 2015 10:41:51 +0100 Subject: CGI Message-ID: <567E60DF.5000007@fuckaround.org> Merry Christmas to all :-) A (newbie) question: I'd like learn about CGI pyhton script to create some utility using http://localhost/python_script01.py Something like that: #!/usr/bin/python print "Content-type: text/html" print print "" print "
Hello!
" print "" How can I execute a local command (like ls or similar) and show output via browser? I didn't find enough documentation to work with python and CGI :-/ Is python not good language to use it with CGI? Thanks for help! :) Pol From rosuav at gmail.com Sat Dec 26 04:49:47 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Dec 2015 20:49:47 +1100 Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> Message-ID: On Sat, Dec 26, 2015 at 8:07 PM, wrote: > Thank you for the explanation. It reminds me to dig out something which seems I had been read before. It's about nested scope in the book "Learning Python" by Mark Lutz. > > "An assignment (X = value) creates or changes the name X in the current local > scope, by default. If X is declared global within the function, the assignment creates or changes the name X in the enclosing module's scope instead. If, on the other hand, X is declared nonlocal within the function in 3.X (only), the assignment changes the name X in the closest enclosing function's local scope." > Yep! That's an accurate description of how assignment works. One of the cool things about Python is that there are all sorts of things that work _exactly_ the same way. Every one of these statements is a form of assignment: import json # 1 from sys import argv # 2 def testfiles(files): # 3, 4 failures = 0 # 5 for file in files: # 6 with open(file) as fp: # 7 try: data = json.load(fp) # 8 except JSONDecodeError as err: # 9 failures += 1 # 10 return failures count = testfiles(argv) # 11 Okay, every one except the 'return' statement. :) 1: "import x" is basically the same as "x = __import__('x')". 2: "from x import y" is basically "y = __import__('x').y" (more or less). This grabs "sys.argv" and assigns it to the name "argv". 3: Defining a function constructs a new function object and assigns it to the name. This is like doing "testfiles = ". 4: As the function gets called, a new scope is created, and inside that scope, the interpreter does the equivalent of "files = ", where the magic snags a reference to whatever was used as the argument (so this is basically "files = argv"). 5: That's straight-forward assignment, right there. 6: A 'for' loop grabs an iterator, then repeatedly does "file = next(iterator)" until there's nothing more to do. 7: A 'with' statement does some work, and then does "fp = " if it has an 'as' clause. 8: Another straight-forward assignment, because I couldn't think of anything better to use. (Normally you'd lay this out with 'try:' on a separate line, but then I'd have had a line without any assignment at all.) 9: Like a 'with' statement, 'except' assigns to its name. There's a special case here, in that it also does 'del err' at the end of the except block, to clean stuff up; but it's still just assignment. 10: Augmented assignment is assignment too. x+=1, x-=1, x*=1, etc, are all assigning to x. 11: Another normal assignment, because otherwise the rest of the work is pointless. :) Every one of these follows the standard rules for assignment. For instance, you could create a function that does a top-level import: $ python3 Python 3.6.0a0 (default:6e114c4023f5, Dec 20 2015, 19:15:28) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def do_imports(): ... global os, sys, json ... import os, sys, json ... >>> do_imports() >>> json You wouldn't normally do this for standard modules like 'os' and 'sys', but if you have something huge to load up (like pandas, or oauth2client), it might be convenient to use them globally, but load them conditionally. Since 'import' is a statement, not a declaration, you can do this! Python's flexibility and simplicity are a huge part of why I love the language so much. ChrisA From princeudo52 at gmail.com Sat Dec 26 04:52:25 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Sat, 26 Dec 2015 01:52:25 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <3c8e53cb-4548-448f-9eb1-ebceef19c07f@googlegroups.com> i am really enjoying u guyz, i didnt sleep yesterday night, but all is working out well now: i am 2weeks old in python, thanks you all for the assistance From princeudo52 at gmail.com Sat Dec 26 05:38:29 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Sat, 26 Dec 2015 02:38:29 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: @ cameron, are u sure this solution u gave me works here is what i am getting, i am really having headache, some-one should please have mercy: def manipulate_data(list_data, set_data): if list_data == ["apples", "orange", "mangoes"]: for i in reversed(set_data): return i elif list_data == {} and this is the erro: File "python", line 5 elif list_data == {} ^ SyntaxError: invalid syntax From princeudo52 at gmail.com Sat Dec 26 06:23:40 2015 From: princeudo52 at gmail.com (princeudo52 at gmail.com) Date: Sat, 26 Dec 2015 03:23:40 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <9b74e1e6-a28e-475d-b213-3a80e241773d@googlegroups.com> Message-ID: <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> this is what i finally got, i give-up, some-one, any body pls help: def manipulate_data(list_data, set_data): if list_data == ["apples", "orange", "mangoes"]: for set_data in reversed(set_data): return set_data elif manipulate_data(list_data == {"apples", "orange", "mangoes"}): list_data.append("ANDELA", "TIA", "AFRICA") for set_data in list_data: return set_data if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}): return dict.keys() From princeudo52 at gmail.com Sat Dec 26 06:36:55 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Sat, 26 Dec 2015 03:36:55 -0800 (PST) Subject: please can i get help on this problem Message-ID: Create a function manipulate_data that does the following Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure Based off the first parameter return the reverse of a list or add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set return the keys of a dictionary. here is my work, but i dont know what i ave done wrong: def manipulate_data(list_data, set_data): if list_data == ["apples", "orange", "mangoes"]: for set_data in reversed(set_data): return set_data elif manipulate_data(list_data == {"apples", "orange", "mangoes"}): list_data.append("ANDELA", "TIA", "AFRICA") for set_data in list_data: return set_data if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}): return list_data.keys() From ben+python at benfinney.id.au Sat Dec 26 07:15:38 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 26 Dec 2015 23:15:38 +1100 Subject: please can i get help on this problem References: Message-ID: <85ege9xv6d.fsf@benfinney.id.au> Please help us by choosing a descriptive Subject field. The one you've chosen tells us *nothing* useful. As it turns out, I can't get anything useful from your message either: Prince Udoka writes: > here is my work, but i dont know what i ave done wrong: Neither do I. What is confusing you, in particular? Describe what you're confused by (for example, what behaviour are you seeing, and how is that different from what you expect?). Summarise that behaviour in a short phrase and put it in the Subject field. -- \ ?Please to bathe inside the tub.? ?hotel room, Japan | `\ | _o__) | Ben Finney From princeudo52 at gmail.com Sat Dec 26 07:26:06 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Sat, 26 Dec 2015 04:26:06 -0800 (PST) Subject: please can i get help on this problem In-Reply-To: References: Message-ID: <42000620-fc4c-4d80-b747-23accf825c52@googlegroups.com> gud day sir, please i have an assignment, nd i am just 2weeks in python; i tried the code i uploaded but its nt working plz help, i need guidiance From princeudo52 at gmail.com Sat Dec 26 08:13:02 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Sat, 26 Dec 2015 05:13:02 -0800 (PST) Subject: please can i get help on this problem In-Reply-To: References: Message-ID: sir does this make sense: def manipulate_data(item, fruits): if item == ["apples", "oranges", "mangoes", "grapes"]: for fruits in reversed(item): return item elif item == {"apples", "oranges", "mangoes", "grapes"}: for fruits in item: fruits.append("ANDELA", "TIA", "AFRICA") return item if item == {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}: return dict.keys() From ariklapid.swim at gmail.com Sat Dec 26 10:14:36 2015 From: ariklapid.swim at gmail.com (ariklapid.swim at gmail.com) Date: Sat, 26 Dec 2015 07:14:36 -0800 (PST) Subject: Importing constantly changing variables Message-ID: <944a9d35-dc31-4074-8d56-bb6e9a0d1d15@googlegroups.com> Hello everyone ! First of all, excuse me for my horrible English. I am an electronics engineering student, trying to use raspberry pi for one of my projects. Meanwhile, my goal is simply to create a pair of files, written in python, which would do the following: A file named "sensors.py" imports varying values from physical sensors. These values are constantly changing. (At this point - I intend to change them manually): [code] def import_soilMoisture(): soilMoisture = 40 # Later - Imports value from corresponding RPi's GPIO return soilMoisture def import_airTemperture(): airTemperture = 24 # Later - Imports value from corresponding RPi's GPIO return airTemperture def import_airHumidity(): airHumidity = 69 # Later - Imports value from corresponding RPi's GPIO return airHumidity [/code] A second file, named "main.py" is intended to import and print the values from "sensors.py": [code] import time def main(): while True: import sensors print(sensors.import_soilMoisture()) print(sensors.import_airTemperture()) print(sensors.import_airHumidity()) time.sleep(5) main() [/code] As you can see, I want the program to print all values each 5 seconds. When I run the file "main.py" it does print values every 5 seconds, BUT when I manually change the values (e.g. airTemperture = 30 instead of 24) and save the file, nothing changes - the old values keep on printing. [b]Help me please to understand what's wrong[/b] [i]For who it may concern: My OS is Debian[/i] Thanks to you all in advance!! :) :D From ian.g.kelly at gmail.com Sat Dec 26 12:11:53 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 26 Dec 2015 10:11:53 -0700 Subject: Importing constantly changing variables In-Reply-To: <944a9d35-dc31-4074-8d56-bb6e9a0d1d15@googlegroups.com> References: <944a9d35-dc31-4074-8d56-bb6e9a0d1d15@googlegroups.com> Message-ID: On Sat, Dec 26, 2015 at 8:14 AM, wrote: > As you can see, I want the program to print all values each 5 seconds. > When I run the file "main.py" it does print values every 5 seconds, BUT when I manually change > the values (e.g. airTemperture = 30 instead of 24) and save the file, nothing changes - > the old values keep on printing. Changing the source code of a module isn't going to affect that module in a running program if it's already been imported. You can use the importlib.reload function to force a module to be reloaded, but this is generally anti-recommended. If not done correctly it can result in multiple versions of the module being simultaneously in use, leading to confusing error conditions. It sounds like you're not trying to update the code anyway, just the data used in the code. For that, you'd be better off putting the data in a data file that your "sensors.py" would read from and re-read on every iteration. From cs at zip.com.au Sat Dec 26 15:20:50 2015 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 27 Dec 2015 07:20:50 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> Message-ID: <20151226202050.GA77214@cskk.homeip.net> On 26Dec2015 03:23, princeudo52 at gmail.com wrote: >this is what i finally got, i give-up, some-one, any body pls help: >def manipulate_data(list_data, set_data): > if list_data == ["apples", "orange", "mangoes"]: > for set_data in reversed(set_data): > return set_data > elif manipulate_data(list_data == {"apples", "orange", "mangoes"}): > list_data.append("ANDELA", "TIA", "AFRICA") > for set_data in list_data: > return set_data > if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}): > return dict.keys() It is like you have not read the question at all. To remind you: Create a function manipulate_data that does the following Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure Based off the first parameter ... So clearly the function must start like this: def manipulate_data(kind, data): and have some kind of decision inside the function, based on the first parameter, which will be one of the strings "list", "set" or "dictionary". Instead, you have written a function above which seems to accept two parameters with the first being a list and the second a set. Perhaps you have not realised that while Python has types, a variable may refer to an object of _any_ type. So the "data" parameter in my example above may be a list OR a set OR a dictionary. (Or anything else, but you only need to cope with those three). So the function might be called in these ways: manipulate_data("list", ["apples", "orange", "mangoes"]) manipulate_data("set", {"apples", "orange", "mangoes"}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) In fact, I suggest you make your test program end with those three calls, so that it looks like this (again, untested - this is a framework for you to complete): def manipulate_data(kind, data): if kind == 'list': ... do stuff with data using it as a list ... ... return the reverse of a list ... elif kind == 'set': ... do stuff with data using it as a set ... ... add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set ... ... and return the resulting set ... elif kind == 'dictionary': ... do stuff with data using it as a dictionary ... ... return the keys of a dictionary ... else: raise ValueError("invalid kind %r, expected 'list', 'set' or 'dictionary'" % (kind,)) manipulate_data("list", ["apples", "orange", "mangoes"]) manipulate_data("set", {"apples", "orange", "mangoes"}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) so that it is a small program which defines your function and then calls it three times with different parameters. Note that where your question says "a list" or "the set" or "a dictionary", it is really referring to the "data" parameter, so that is what you should be working with. Cheers, Cameron Simpson >https://mail.python.org/mailman/listinfo/python-list On 26Dec2015 11:09, Cameron Simpson wrote: >On 25Dec2015 15:05, princeudo52 at gmail.com wrote: >>i have gotten the answer of that problem > >Please include some context when posting to the list; there are many >discussions and it is best to include a little more than the subject >line in such things. It is also polite to post your working solution >for the benefit of those who have assisted you, or for others with a >similar problem. > >Then two more messages in quick succession: this list is not an >instant messaging system. Please try to post a single message, with >your question and also what code you have already. > >Regarding your actual question, commentry below the quoted text follows... > >On 25Dec2015 15:08, princeudo52 at gmail.com wrote: >>Create a function manipulate_data that does the following >>Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary" >>Accepts as the second parameter the data to be manipulated based on the data structure specified e.g [1, 4, 9, 16, 25] for a list data structure >>Based off the first parameter >> >> return the reverse of a list or >> add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set >> return the keys of a dictionary. >> >>#my solution is: >>def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}): >> return dict_data.keys() >> >>def manipulate_data( alist, list_data = [2,8,16,23,14]): >> return list_data.reverse() >> >>def manipulate_data(aset, set_data = {"bee","cee","dee"}): >> set_data = {"bee","cee","dee"} >> set_data.update("ANDELA","TIA","AFRICA") >> return dictionary_data >>#please what is wrong with my code > >The most obvious thing that is wrong it that you have 3 functions here >with the same name. In Python that means: define the first function >and bind it to the name "manipulate_data". Then define the second and >bind it to the same name as the first, discarding the first function. >The define the third and bind it to the same name again, discarding >the second function. > >Your task is asking for a _single_ function which behaves differently >according to a parameter which tells it what kind of data is has been >given, so you want a function which starts like this: > > def manipulate_data(kind, data): > >and you are supposed to pass in the string "list", "set" or dictionary >for the first parameter, and some corresponding list, set or >dictionary as the second parameter. There should _not_ be default >values for either of these. > >Instead, your function should examine the "kind" parameter and decide >what to do. So it would reasonably look like this (untested): > > def manipulate_data(kind, data): > if kind == 'list': > ... do stuff with data using it as a list ... > elif kind == 'set': > ... do stuff with data using it as a set ... > if kind == 'dictionary': > ... do stuff with data using it as a dictionary ... > else: > raise ValueError("invalid kind %r, expected 'list', 'set' or 'dictionary'" % (kind,)) > >Try starting with that and see how you go. > >Cheers, >Cameron Simpson >-- >https://mail.python.org/mailman/listinfo/python-list From ben+python at benfinney.id.au Sat Dec 26 18:11:13 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 27 Dec 2015 10:11:13 +1100 Subject: please can i get help on this problem References: Message-ID: <8537uoyfe6.fsf@benfinney.id.au> Prince Udoka writes: > sir does this make sense: Referring to the whole of a community as ?sir? is not only too formal, it also betrays a different error: you seem to think you're in a one-on-one dialogue devoted to your issues. Please, instead of trying to make your messages more polite (your phrasing is already plenty polite enough), do us the respect of spending time on the *content* of your message. As has been asked of you many times now: When you have a question, please make it specific and answerable. Describe what *specifically* is confusing or concerning you; describe *specifically* what you did, what you expected to happen, and what happened instead. Putting effort into making your messages easiler to comprehend will be far more polite than merely calling us collectively ?sir?. It will have the added benefit of getting you more useful answers. -- \ ?When cryptography is outlawed, bayl bhgynjf jvyy unir | `\ cevinpl.? ?Anonymous | _o__) | Ben Finney From ben+python at benfinney.id.au Sat Dec 26 18:15:19 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 27 Dec 2015 10:15:19 +1100 Subject: Importing constantly changing variables References: <944a9d35-dc31-4074-8d56-bb6e9a0d1d15@googlegroups.com> Message-ID: <85y4cgx0mw.fsf@benfinney.id.au> ariklapid.swim at gmail.com writes: > Hello everyone ! > First of all, excuse me for my horrible English. As is often the case with people who make this apology, your English is far better than most native English speakers can use any other language :-) > A file named "sensors.py" imports varying values from physical > sensors. These values are constantly changing. Such values, then, should not be obtained from a Python ?import?. Instead, you need to come up with a data transfer protocol, or (more likely) make use of an existing one. Your running program will make function calls that get the data from ?the outside world? ? a file, or a network interface, or some other input to the program. So to solve this you will need to know the specifics of how the device connects to the computer, what interfaces it presents for obtaining the data at run time, and what Python libraries you can use for accessing that interface. -- \ ?If you do not trust the source do not use this program.? | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From jfong at ms4.hinet.net Sat Dec 26 23:05:44 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sat, 26 Dec 2015 20:05:44 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> Message-ID: <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> Chris Angelico at 2015/12/26 UTC+8 5:50:07PM wrote: > 11: Another normal assignment, because otherwise the rest of the work > is pointless. :) Thanks for this detailed example. As I had learned so far, Python really take "name" seriously, and every meaningful result you got have to assign to a name at last. This morning I played some codes on the http://pythonturor.com and found out that every objects which was not created at top-level of a module or in a class will disappear after import. A very "unusual" view. > Python's flexibility and simplicity are a huge part of why I love the > language so much. simplicity? Maybe because you are soooo familiar with Python. It's not to me, at least at this moment. Please see my next question follows. --Jach From jfong at ms4.hinet.net Sat Dec 26 23:11:12 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sat, 26 Dec 2015 20:11:12 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> Message-ID: <0bf611ba-c4d9-4465-8d61-6a94bcee79a4@googlegroups.com> Last night I noticed that Python does not resolve name in "def" during import, as C does in the compile/link stage, it was deferred until it was referenced (i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner or later. I just have to get used to this style. But check these codes, it seems not. ------- x = 1 # a global variable print(x) class Test: x = 4 # a class attribute print(x) def func(self): print(x) x1 = Test() x1.x = 41 # a instance's attribute x1.func() # it's 1 but 41 was expect:-( -------- --Jach From brian.moreira at owl.ucc.edu Sat Dec 26 23:59:37 2015 From: brian.moreira at owl.ucc.edu (brian.moreira) Date: Sun, 27 Dec 2015 04:59:37 +0000 Subject: Problem Running tkinter gui Code Message-ID: Hi there. I trying to run a simple code that opens a Tkinter window with text in it, on my windows 8 machine using Python 3.4.3 I used to ge: ?ImportError: no tkinter module exists? But now it opens a windows Wizard screen that prompts me to Modify, Repair, or Uninstall Python. I have tried all three options and the code still won?t run. NOTE* the code runs fine on my other windows 8 machine. I am using the same version of windows on both. I have been Coding Python since last semester and now when I try to make my codes, they are unusable and I run into a he roadblock! Please help me. This should not be a problem for me! Sent from Windows Mail From rosuav at gmail.com Sun Dec 27 01:22:45 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Dec 2015 17:22:45 +1100 Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> Message-ID: On Sun, Dec 27, 2015 at 3:05 PM, wrote: >> Python's flexibility and simplicity are a huge part of why I love the >> language so much. > > simplicity? Maybe because you are soooo familiar with Python. It's not to me, at least at this moment. Please see my next question follows. > I define "simplicity" in terms of the number and complexity of the rules you have to keep in your head. It's not necessarily the best thing to do; for instance, a C-style #include directive is *extremely* simple (it is literally "drop the file contents in at this location"), but I prefer Python's semantics. On the other hand, PHP's include directive is *not* simple; in many ways it behaves like C's #include, but it can't be used inside class definitions, and if used in a function, some of what it does is at top level and some is inside the function. Python's rules for imports (whether they're "import X" or "from X import Y") include a somewhat complicated definition of search path, but ultimately, it's a matter of hunting down a module and executing it (all of it) in its own namespace, and then giving you a reference to sys.modules["X"] (or sys.modules["X"].Y for a from-import). ChrisA From rosuav at gmail.com Sun Dec 27 01:32:17 2015 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Dec 2015 17:32:17 +1100 Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: <0bf611ba-c4d9-4465-8d61-6a94bcee79a4@googlegroups.com> References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> <0bf611ba-c4d9-4465-8d61-6a94bcee79a4@googlegroups.com> Message-ID: On Sun, Dec 27, 2015 at 3:11 PM, wrote: > Last night I noticed that Python does not resolve name in "def" during import, as C does in the compile/link stage, it was deferred until it was referenced (i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner or later. I just have to get used to this style. > > But check these codes, it seems not. > ------- > x = 1 # a global variable > print(x) > > class Test: > x = 4 # a class attribute > print(x) > def func(self): > print(x) > > x1 = Test() > x1.x = 41 # a instance's attribute > x1.func() # it's 1 but 41 was expect:-( > -------- > > --Jach When you import this module, it runs all top-level code. So the 'print' at the top will happen at import time. Among the top-level statements is a class definition. When that gets run (to construct the class itself - distinct from instantiating it, which happens further down), it builds a class by executing all the statements in it, in order. That results in that value of x being printed, and then defines a function. The function definition is being run at time of class construction, and it creates a new attribute on the Test class. At that time, the function body isn't actually executed (as you might expect). However, it's worth noting that the function does not inherit class scope. The unadorned name 'x' references the global. If you want to access class-scope names from inside methods, you need to say 'self.x', which also applies to instance attributes. That's what would do what you expect here. ChrisA From malitician at gmail.com Sun Dec 27 10:02:38 2015 From: malitician at gmail.com (lee) Date: Sun, 27 Dec 2015 07:02:38 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> Message-ID: <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> > >Instead, your function should examine the "kind" parameter and decide > >what to do. So it would reasonably look like this (untested): > > > > def manipulate_data(kind, data): > > if kind == 'list': > > ... do stuff with data using it as a list ... > > elif kind == 'set': > > ... do stuff with data using it as a set ... > > if kind == 'dictionary': > > ... do stuff with data using it as a dictionary ... > > else: > > raise ValueError("invalid kind %r, expected 'list', 'set' or 'dictionary'" % (kind,)) > > > >Try starting with that and see how you go. > > > >Cheers, > >Cameron Simpson > >-- > >https://mail.python.org/mailman/listinfo/python-list the question again >Create a function manipulate_data that does the following >Accepts as the first parameter a string specifying the data structure to be >used "list", "set" or "dictionary" >Accepts as the second parameter the data to be manipulated based on the data >structure specified e.g [1, 4, 9, 16, 25] for a list data structure >Based off the first parameter > return the reverse of a list or > add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the >resulting set > return the keys of a dictionary. unittest for the question >import unittest >class DataStructureTest(TestCase): > def setUp(self): > self.list_data = [1,2,3,4,5] > self.set_data = {"a", "b", "c", "d", "e"} > self.dictionary_data = {"apples": 23, "oranges": 15, "mangoes": 3, >"grapes": 45} > > def test_manipulate_list(self): > result = manipulate_data("list", self.list_data) > self.assertEqual(result, [5,4,3,2,1], msg = "List not manipulated >correctly") > > def test_manipulate_set(self): > result = manipulate_data("set", self.set_data) > self.assertEqual(result, {"a", "b", "c", "d", "e", "ANDELA", "TIA", >"AFRICA"}, msg = "Set not manipulated correctly") > > def test_manipulate_dictionary(self): > result = manipulate_data("dictionary", self.dictionary_data) > self.assertEqual(result, ["grapes", "mangoes", "apples", "oranges"], msg = >"Dictionary not manipulated correctly") the code i have tested base on Cameron's code def manipulate_data(kind, data): if kind == 'list': return list(data)[::-1] elif kind == 'set': return set(data) elif kind == 'dictionary': return dict( data) manipulate_data("list", range(1,6)) a = manipulate_data("set", {"a", "b", "c", "d", "e"}) a.add("ANDELA") a.add("TIA") a.add("AFRICA") b = manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) list(b.keys()) this is the result i got from the unittest Total Specs: 3 Total Failures: 2 1 . test_manipulate_dictionary Failure in line 23, in test_manipulate_dictionary self.assertEqual(result, ["grapes", "mangoes", "apples", "oranges"], msg = "Dictionary not manipulated correctly") AssertionError: Dictionary not manipulated correctly 2 . test_manipulate_set Failure in line 19, in test_manipulate_set self.assertEqual(result, {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}, msg = "Set not manipulated correctly") AssertionError: Set not manipulated correctly i guess i passed the first requirement to return the reversed order of the list and believe i messed up when creating a set then add data to the set, also something is wrong with returning the keys of the dictionary can someone point out the error in my code and the meaning of the unittes error? thanks in advance From python at lucidity.plus.com Sun Dec 27 10:26:44 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 27 Dec 2015 15:26:44 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> Message-ID: <56800334.9000106@lucidity.plus.com> On 27/12/15 15:02, lee wrote: > the code i have tested base on Cameron's code > > def manipulate_data(kind, data): > if kind == 'list': > return list(data)[::-1] > > elif kind == 'set': > return set(data) > elif kind == 'dictionary': > return dict( data) > > manipulate_data("list", range(1,6)) > a = manipulate_data("set", {"a", "b", "c", "d", "e"}) > a.add("ANDELA") > a.add("TIA") > a.add("AFRICA") > b = manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) > list(b.keys()) [snip] > i guess i passed the first requirement to return the reversed order of the list and believe i messed up when creating a set then add data to the set, also something is wrong with returning the keys of the dictionary > > > can someone point out the error in my code and the meaning of the unittes error? You're nearly there. After you've called the function, anything you do to the result is not done BY the function and will therefore not be done when called by other code. The unit test that calls the function will not do those things. It expects them to already be done. So ... what changes to your function do you think would fix that? Regards, E. From rosuav at gmail.com Sun Dec 27 11:13:22 2015 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 28 Dec 2015 03:13:22 +1100 Subject: CGI In-Reply-To: <567DA87F.40803@fuckaround.org> References: <567DA87F.40803@fuckaround.org> Message-ID: On Sat, Dec 26, 2015 at 7:35 AM, Pol Hallen wrote: > Merry Christmas to all :-) > > A (newbie) question: I'd like learn about CGI pyhton script to create some > utility using http://localhost/python_script01.py > > Something like that: > > #!/usr/bin/python > print "Content-type: text/html" > print > print "" > print "
Hello!
" > print "" > > How can I execute a local command (like ls or similar) and show output via > browser? > > I didn't find enough documentation to work with python and CGI :-/ > > Is python not good language to use it with CGI? > > Thanks for help! :) Hi! I would recommend picking up one of the Python web frameworks like Django or Flask. It's usually easier than using CGI. But either way, the easiest way to run a local command is the subprocess module: https://docs.python.org/2/library/subprocess.html https://docs.python.org/3/library/subprocess.html I've provided two links because, unless you have a really good reason for using Python 2, it'd be well worth using Python 3 instead. There are lots of neat new features in the 3.x line, so it'll be best to start on 3.x rather than migrating later. The current release is 3.5, and new releases keep coming out. :) ChrisA From zen at nonirvana.org Sun Dec 27 11:19:41 2015 From: zen at nonirvana.org (Maitu Zentz) Date: Sun, 27 Dec 2015 17:19:41 +0100 Subject: CGI References: Message-ID: <73be1$56800f9d$54852b34$22183@news1.surfino.com> Pol Hallen: > Merry Christmas to all :-) > > A (newbie) question: I'd like learn about CGI pyhton script to create > some utility using http://localhost/python_script01.py > > Something like that: > > #!/usr/bin/python print "Content-type: text/html" > print print "" > print "
Hello!
" > print "" > > How can I execute a local command (like ls or similar) and show output > via browser? > > I didn't find enough documentation to work with python and CGI :-/ > > Is python not good language to use it with CGI? > > Thanks for help! :) > > Pol http://www.fullstackpython.com/ -- Maitu Zentz From laurent at krutt.org Sun Dec 27 12:59:43 2015 From: laurent at krutt.org (Laurent Delacroix) Date: Sun, 27 Dec 2015 18:59:43 +0100 Subject: CGI References: Message-ID: On 26/12/15 10:41, Pol Hallen wrote: > > How can I execute a local command (like ls or similar) and show output > via browser? > Either you use a proper web framework (Flask, Bottle, Django in order of complexity) or you set up a web server with FastCGI support (e.g. nginx) and run a WSGI application behind it. Useful link: https://docs.python.org/2/howto/webservers.html#setting-up-fastcgi Lau From rxjwg98 at gmail.com Sun Dec 27 14:08:44 2015 From: rxjwg98 at gmail.com (Robert) Date: Sun, 27 Dec 2015 11:08:44 -0800 (PST) Subject: How to change/set compiler option for weave inline function Message-ID: <8ee388db-df33-480a-aad9-73cefa996bfa@googlegroups.com> Hi, I want to run a few C code inside Python on Windows 7, 64-bit PC, Canopy 1.5.2.2785. I made a few trials, but I forget the detail commands I made on compiler setting. One thing I remember is that I added one file: distutils.cfg, whose content is: [build] compiler=mingw32 And another thing I did was an option to msvc for the compiler, but I don't remember where the file was. Now, it always search for 'msvccompiler', though I think it should use mingw32, as the following: import scipy.weave In [16]: weave.test() Running unit tests for scipy.weave NumPy version 1.9.2..................................S.SSS....SSSSSS................................................................................................. NumPy is installed in C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy SciPy version 0.16.1 SciPy is installed in C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy Python version 2.7.6 | 64-bit | (default, Sep 15 2014, 17:36:35) [MSC v.1500 64 bit (AMD64)] nose version 1.3.4 ---------------------------------------------------------------------- Ran 146 tests in 5.652s OK (SKIP=10) Out[16]: In [17]: a = 1 In [18]: weave.inline('printf("%d\\n",a);',['a']) No module named msvccompiler in numpy.distutils; trying from distutils objdump.exe: C:\Users\jj\AppData\Local\Enthought\Canopy\User\python27.dll: File format not recognized Looking for python27.dll --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () ----> 1 weave.inline('printf("%d\\n",a);',['a']) C:\Users\rj\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\weave\inline_tools.pyc in inline(code, arg_names, local_dict, global_dict, force, compiler, verbose, support_code, headers, customize, type_converters, auto_downcast, newarr_converter, **kw) 364 type_converters=type_converters, 365 auto_downcast=auto_downcast, --> 366 **kw) 367 368 function_catalog.add_function(code,func,module_dir) C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\weave\inline_tools.pyc in compile_function(code, arg_names, local_dict, global_dict, module_dir, compiler, verbose, support_code, headers, customize, type_converters, auto_downcast, **kw) 494 # setting. All input keywords are passed through to distutils 495 mod.compile(location=storage_dir,compiler=compiler, --> 496 verbose=verbose, **kw) 497 498 # import the module and return the function. Make sure C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\weave\ext_tools.pyc in compile(self, location, compiler, verbose, **kw) 371 success = build_tools.build_extension(file, temp_dir=temp, 372 compiler_name=compiler, --> 373 verbose=verbose, **kw) 374 if not success: 375 raise SystemError('Compilation failed') C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\weave\build_tools.pyc in build_extension(module_path, compiler_name, build_dir, temp_dir, verbose, **kw) 277 environ = copy.deepcopy(os.environ) 278 try: --> 279 setup(name=module_name, ext_modules=[ext],verbose=verb) 280 finally: 281 # restore state C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\core.pyc in setup(**attr) 167 new_attr['distclass'] = NumpyDistribution 168 --> 169 return old_setup(**new_attr) 170 171 def _check_append_library(libraries, item): C:\Users\jj\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.2.2785.win-x86_64\lib\distutils\core.pyc in setup(**attrs) 150 if ok: 151 try: --> 152 dist.run_commands() 153 except KeyboardInterrupt: 154 raise SystemExit, "interrupted" C:\Users\jj\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.2.2785.win-x86_64\lib\distutils\dist.pyc in run_commands(self) 951 """ 952 for cmd in self.commands: --> 953 self.run_command(cmd) 954 955 # -- Methods that operate on its Commands -------------------------- C:\Users\jj\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.2.2785.win-x86_64\lib\distutils\dist.pyc in run_command(self, command) 970 cmd_obj = self.get_command_obj(command) 971 cmd_obj.ensure_finalized() --> 972 cmd_obj.run() 973 self.have_run[command] = 1 974 C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\command\build_ext.pyc in run(self) 92 verbose=self.verbose, 93 dry_run=self.dry_run, ---> 94 force=self.force) 95 self.compiler.customize(self.distribution) 96 self.compiler.customize_cmd(self) C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\ccompiler.pyc in new_compiler(plat, compiler, verbose, dry_run, force) 560 raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " + 561 "in module '%s'") % (class_name, module_name)) --> 562 compiler = klass(None, dry_run, force) 563 log.debug('new_compiler returns %s' % (klass)) 564 return compiler C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\mingw32ccompiler.pyc in __init__(self, verbose, dry_run, force) 89 # 1. Check for import library on Windows. Build if it doesn't exist. 90 ---> 91 build_import_library() 92 93 # Check for custom msvc runtime library on Windows. Build if it doesn't exist. C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\mingw32ccompiler.pyc in build_import_library() 376 arch = get_build_architecture() 377 if arch == 'AMD64': --> 378 return _build_import_library_amd64() 379 elif arch == 'Intel': 380 return _build_import_library_x86() C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\mingw32ccompiler.pyc in _build_import_library_amd64() 397 % (out_file, dll_file)) 398 --> 399 generate_def(dll_file, def_file) 400 401 cmd = ['dlltool', '-d', def_file, '-l', out_file] C:\Users\jj\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\distutils\mingw32ccompiler.pyc in generate_def(dll, dfile) 276 break 277 else: --> 278 raise ValueError("Symbol table not found") 279 280 syms = [] ValueError: Symbol table not found How can I set correctly to use inline C code? Thanks From p_s_d_a_s_i_l_v_a_ns at netcabo.pt Sun Dec 27 14:30:39 2015 From: p_s_d_a_s_i_l_v_a_ns at netcabo.pt (Paulo da Silva) Date: Sun, 27 Dec 2015 19:30:39 +0000 Subject: Error References: Message-ID: I am not a windows user but googling for api-ms-win-crt-runtime-l1-1-0.dll I could find many pages on this subject. The 1st one was https://www.smartftp.com/support/kb/the-program-cant-start-because-api-ms-win-crt-runtime-l1-1-0dll-is-missing-f2702.html Search by yourself or use this one, for example. *As I said this is from a Google search. I don't know anything about this* ?s 22:21 de 19-12-2015, Amaan Hussain escreveu: > Hello. > I get an error saying "api-ms-win-crt-runtime-l1-1-0.dll is missing" > Can you tell me how to fix this. > Thanks > From kwpolska at gmail.com Sun Dec 27 15:01:15 2015 From: kwpolska at gmail.com (Chris Warrick) Date: Sun, 27 Dec 2015 21:01:15 +0100 Subject: CGI In-Reply-To: References: Message-ID: On 27 December 2015 at 18:59, Laurent Delacroix wrote: > On 26/12/15 10:41, Pol Hallen wrote: >> >> How can I execute a local command (like ls or similar) and show output >> via browser? >> > > Either you use a proper web framework (Flask, Bottle, Django in order of > complexity) or you set up a web server with FastCGI support (e.g. nginx) > and run a WSGI application behind it. > > Useful link: > https://docs.python.org/2/howto/webservers.html#setting-up-fastcgi > > Lau > -- > https://mail.python.org/mailman/listinfo/python-list Better yet, use a real WSGI server like uWSGI and its associated nginx module. (there are plenty of tutorials around the Internet) -- Chris Warrick PGP: 5EAAEA16 From malitician at gmail.com Sun Dec 27 15:26:42 2015 From: malitician at gmail.com (lee) Date: Sun, 27 Dec 2015 12:26:42 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> Message-ID: <423fff7a-ea6a-4949-be99-f13cce6f360e@googlegroups.com> > > After you've called the function, anything you do to the result is not > done BY the function and will therefore not be done when called by other > code. > > The unit test that calls the function will not do those things. It > expects them to already be done. > > So ... what changes to your function do you think would fix that? > > Regards, > E. i modified my code a little but still no luck, the same unit test error surfaced again. here is the modified code def manipulate_data(kind, data): if kind == 'list': return list(data)[::-1] elif kind == 'set': return set(data) elif kind == 'dictionary': return dict( data) manipulate_data("list", range(1,6)) manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}).keys() From princeudo52 at gmail.com Sun Dec 27 15:32:11 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Sun, 27 Dec 2015 12:32:11 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> Message-ID: <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> thanks mr cameron simpson, finally at i got the solution, God bless you: def manipulate_data(kind, data): if kind == 'list': for data in [1, 2, 3, 4, 5]: return data.reverse() elif kind == 'set': for data in {"a", "b", "c", "d", "e"}: data.add("ANDELA") data.add("TIA") data.add("AFRICA") return data elif kind == 'dictionary': for data in {"apples": 23, "oranges": 15, "mangoes": 3, "grape": 45}: return data.key() From malitician at gmail.com Sun Dec 27 15:54:11 2015 From: malitician at gmail.com (lee) Date: Sun, 27 Dec 2015 12:54:11 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> Message-ID: <463ca880-2af7-42fa-93ca-dcf6187c6a4d@googlegroups.com> On Sunday, December 27, 2015 at 9:32:24 PM UTC+1, Prince Udoka wrote: > thanks mr cameron simpson, finally at i got the solution, God bless you: > def manipulate_data(kind, data): > if kind == 'list': > for data in [1, 2, 3, 4, 5]: > return data.reverse() > elif kind == 'set': > for data in {"a", "b", "c", "d", "e"}: > data.add("ANDELA") > data.add("TIA") > data.add("AFRICA") > return data > elif kind == 'dictionary': > for data in {"apples": 23, "oranges": 15, "mangoes": 3, "grape": 45}: > return data.key() so how did you call the function because just pasting your code as it is did not work for me. sorry if question sounds dumb From zachary.ware+pylist at gmail.com Sun Dec 27 16:26:25 2015 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Sun, 27 Dec 2015 15:26:25 -0600 Subject: Problem Running tkinter gui Code In-Reply-To: References: Message-ID: On Sat, Dec 26, 2015 at 10:59 PM, brian.moreira wrote: > I trying to run a simple code that opens a Tkinter window with text in it, on my windows 8 machine using Python 3.4.3 Hi Brian, Details are important, and there are several missing from your question that make any advice just guesswork. Please show us a simple code example that doesn't work ("import tkinter;tkinter.Tk()" should be enough to either run successfully or throw an exception in this case), and how you're trying to run it that doesn't work. With that extra information, we should be able to figure out what's going on. I've given a couple of guesses below anyway. > I used to ge: ?ImportError: no tkinter module exists? That is not the phrasing that is actually used in Python; it is better to copy and paste tracebacks than to retype them from memory. I realize that's not an option when the traceback is no longer available, but that also means that the traceback is irrelevant to the current issue. My guess is that either your own code produced that exception, or you were trying to import 'Tkinter' rather than 'tkinter' (the name changed from Python 2 to Python 3; many online examples may still refer to 'Tkinter'). > But now it opens a windows Wizard screen that prompts me to Modify, Repair, or Uninstall Python. That sounds like you're trying to run the installer rather than the interpreter. Without knowing how you're trying to run it, I can't guess as to how that might be. Regards, -- Zach From python at lucidity.plus.com Sun Dec 27 16:42:04 2015 From: python at lucidity.plus.com (Erik) Date: Sun, 27 Dec 2015 21:42:04 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> References: <20151226000941.GA36035@cskk.homeip.net> <4dba6e6d-68f5-42af-b9d8-8bb1bd92312b@googlegroups.com> <6890848e-bffa-4cac-8a3b-3f8a529b7cd9@googlegroups.com> <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> Message-ID: <56805B2C.7040408@lucidity.plus.com> On 27/12/15 20:32, Prince Udoka wrote: > thanks mr cameron simpson, finally at i got the solution, God bless you: > def manipulate_data(kind, data): > if kind == 'list': > for data in [1, 2, 3, 4, 5]: > return data.reverse() > elif kind == 'set': > for data in {"a", "b", "c", "d", "e"}: > data.add("ANDELA") > data.add("TIA") > data.add("AFRICA") > return data > elif kind == 'dictionary': > for data in {"apples": 23, "oranges": 15, "mangoes": 3, "grape": 45}: > return data.key() Please stop posting code to the list which you have not even attempted to run. This is getting a bit silly. RUN your code. Three of the four paths through that code will fail when it is run, so I am sure that you have not. If you don't understand the error messages then ask what they mean, along with your guess at what you think they mean and what you tried to do about it (but did not work). Please consider joining a list which is more appropriate for these questions: https://mail.python.org/mailman/listinfo/tutor/ E. From real-not-anti-spam-address at apple-juice.co.uk Sun Dec 27 17:45:09 2015 From: real-not-anti-spam-address at apple-juice.co.uk (D.M. Procida) Date: Sun, 27 Dec 2015 22:45:09 +0000 Subject: Textarc recreation in Jupyter Notebook Message-ID: <1mg41gk.7ewh2azf1k8N%real-not-anti-spam-address@apple-juice.co.uk> Maybe you remember , which creates an interactive representation of relationships within a text. Textarc doesn't work for me on OS X any more, but I did find a JavaScript recreation, (code: ). I'd like to try recreating and maybe extending it in Jupyter Notebook. Is anyone else interested in working on this as a project (for fun)? I'm pretty new to Notebook, so it will definitely be a learning project for me. I'm interested in using programs to explore texts generally. Here's a re-creation of Ulises Carri?n's "Hamlet, for two voices" in Python: . Daniele From jfong at ms4.hinet.net Sun Dec 27 20:02:39 2015 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Sun, 27 Dec 2015 17:02:39 -0800 (PST) Subject: A newbie quesiton: local variable in a nested funciton In-Reply-To: References: <701dd0e6-a9c1-4aa9-a3a2-6607cd3f3759@googlegroups.com> <661a13a1-8084-41ca-b458-297462dc3367@googlegroups.com> <0bf611ba-c4d9-4465-8d61-6a94bcee79a4@googlegroups.com> Message-ID: Chris Angelico at 2015/12/27 UTC+8 2:32:32PM wrote: > On Sun, Dec 27, 2015 at 3:11 PM, wrote: > > Last night I noticed that Python does not resolve name in "def" during import, as C does in the compile/link stage, it was deferred until it was referenced (i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner or later. I just have to get used to this style. > > > > But check these codes, it seems not. > > ------- > > x = 1 # a global variable > > print(x) > > > > class Test: > > x = 4 # a class attribute > > print(x) > > def func(self): > > print(x) > > > > x1 = Test() > > x1.x = 41 # a instance's attribute > > x1.func() # it's 1 but 41 was expect:-( > > -------- > > > > --Jach > > When you import this module, it runs all top-level code. So the > 'print' at the top will happen at import time. > > Among the top-level statements is a class definition. When that gets > run (to construct the class itself - distinct from instantiating it, > which happens further down), it builds a class by executing all the > statements in it, in order. That results in that value of x being > printed, and then defines a function. > > The function definition is being run at time of class construction, > and it creates a new attribute on the Test class. At that time, the > function body isn't actually executed (as you might expect). However, > it's worth noting that the function does not inherit class scope. The > unadorned name 'x' references the global. If you want to access > class-scope names from inside methods, you need to say 'self.x', which > also applies to instance attributes. That's what would do what you > expect here. > > ChrisA Yea, right, it's in a method, not a function. A stupid mistake I had made:-( Thanks for your kindly patient with me, and Happy New Year to you:-) --Jach From cs at zip.com.au Sun Dec 27 22:32:58 2015 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 28 Dec 2015 14:32:58 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> References: <5e43da5b-01e8-4395-a04c-dc311844a617@googlegroups.com> Message-ID: <20151228033258.GA67520@cskk.homeip.net> On 27Dec2015 12:32, Prince Udoka wrote: >thanks mr cameron simpson, finally at i got the solution, God bless you: >def manipulate_data(kind, data): > if kind == 'list': > for data in [1, 2, 3, 4, 5]: > return data.reverse() > elif kind == 'set': > for data in {"a", "b", "c", "d", "e"}: > data.add("ANDELA") > data.add("TIA") > data.add("AFRICA") > return data > elif kind == 'dictionary': > for data in {"apples": 23, "oranges": 15, "mangoes": 3, "grape": 45}: > return data.key() Have you actually run this? Because it is still not right, though far better. There are several problems: The biggest issue is that "data" is a _parameter_. This means that it is information passed into the function from outside, to be used. However, in each of your "if" sections you iterate "data" over some hardwired values in a loop, and do _nothing_ with the value passed to the function. 1: why do you have hardwired values inside this function? The next is that you have "return" statements inside the loops. This means that on the _first_ iteration of the loop, the function will return, and the later loop iterations will not happen. Normal practice would be for the "return" to be outside the loop, therefore _after_ the loop has done its work. Now, also consider what such a change would mean. For the "list" case, it would mean that the code _inside_ the loop is empty. If there is no code there, why do you have a loop at all? Perhaps it is not needed. What do _you_ think the purpose of the loop is? Cheers, Cameron Simpson From 1991loctran at gmail.com Mon Dec 28 00:00:41 2015 From: 1991loctran at gmail.com (User of Products) Date: Sun, 27 Dec 2015 21:00:41 -0800 (PST) Subject: please can i get help on this problem In-Reply-To: References: Message-ID: <74ba7e4b-df69-4943-ab21-76fc2981c6a6@googlegroups.com> In other words, nobody wants to do your homework for you. Your fault for being a lazy POS and doing everything last minute. From malitician at gmail.com Mon Dec 28 04:25:35 2015 From: malitician at gmail.com (lee) Date: Mon, 28 Dec 2015 01:25:35 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> I'm still stuck on this, any Rescuer? From princeudo52 at gmail.com Mon Dec 28 04:29:55 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Mon, 28 Dec 2015 01:29:55 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> Message-ID: <098af50f-4aef-4b72-8e16-c011054f9a40@googlegroups.com> wow thats true the code did not work From princeudo52 at gmail.com Mon Dec 28 04:34:13 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Mon, 28 Dec 2015 01:34:13 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> Message-ID: <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> bu i have come up with a solution, that will work but encounter a problem in the set, giving set not manipulated correctly: def manipulate_data(kind, data): if kind == 'list': return list(data)[::-1] elif kind == 'set': return set(data) elif kind == 'dictionary': return dict.keys(data) manipulate_data("list", range(1,6)) manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) the thing now is the function to use in adding "ANDELA", "TIA", "AFRICA" pls 4give my use of language From ben+python at benfinney.id.au Mon Dec 28 04:38:15 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 28 Dec 2015 20:38:15 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> Message-ID: <8537umx69k.fsf@benfinney.id.au> lee writes: > I'm still stuck on this, any Rescuer? You appear to be yet another different person asking about this homework assignment. Please: * This forum is not suitable for the kind of close attention to very basic learning. Take this discussion to the ?tutor? forum , which is much better focussed on close collaborative mentoring of beginners. * Choose a single spokesperson, and have that person provide continuity in the discussion by responding consistently from the same email address. * Learn proper email etiquette (plain text messages, quoted material, give sufficient context, etc.) to help the community understand what each message is about. -- \ ?Holy uncanny photographic mental processes, Batman!? ?Robin | `\ | _o__) | Ben Finney From princeudo52 at gmail.com Mon Dec 28 04:39:30 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Mon, 28 Dec 2015 01:39:30 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <098af50f-4aef-4b72-8e16-c011054f9a40@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> <098af50f-4aef-4b72-8e16-c011054f9a40@googlegroups.com> Message-ID: def manipulate_data(kind, data): if kind == 'list': return list(data)[::-1] elif kind == 'set': return set(data) elif kind == 'dictionary': return dict.keys(data) manipulate_data("list", range(1,6)) manipulate_data("set", {"a", "b", "c", "d", "e",}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) just use a function to add "ANDELA", "TIA", "AFRICA" to the set, the u are don From ben+python at benfinney.id.au Mon Dec 28 04:41:05 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 28 Dec 2015 20:41:05 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> Message-ID: <85y4cevrke.fsf@benfinney.id.au> Prince Udoka writes: > pls 4give my use of language Your messages are becoming quite disruptive and inconsiderate of your readers. Please take more care with each message, don't bombard us with a series of poorly-thought-out, hyper-abbreviated messages. Please take extreme-beginner discussions to the ?tutor? forum. -- \ ?All progress has resulted from people who took unpopular | `\ positions.? ?Adlai Stevenson | _o__) | Ben Finney From malitician at gmail.com Mon Dec 28 04:53:48 2015 From: malitician at gmail.com (lee) Date: Mon, 28 Dec 2015 01:53:48 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> Message-ID: <4023d75d-5e96-40b0-b1b1-a193c722004d@googlegroups.com> On Monday, December 28, 2015 at 10:38:47 AM UTC+1, Ben Finney wrote: > lee writes: > > > I'm still stuck on this, any Rescuer? > > You appear to be yet another different person asking about this homework > assignment. > > Please: > > * This forum is not suitable for the kind of close attention to very > basic learning. Take this discussion to the 'tutor' forum > , which is much > better focussed on close collaborative mentoring of beginners. > > * Choose a single spokesperson, and have that person provide continuity > in the discussion by responding consistently from the same email > address. > > * Learn proper email etiquette (plain text messages, quoted material, > give sufficient context, etc.) to help the community understand what > each message is about. > > -- > \ "Holy uncanny photographic mental processes, Batman!" --Robin | > `\ | > _o__) | > Ben Finney if you have followed this thread from the beginning , you should have been aware that different people have contributed in asking/answering on this same discussion and nobody has any problem with that, so please if someone ( same or different) needs help on a single problem , allow them contribute, they could be the source of getting the problem solved. thanks prince( botic) , will try you suggestion From joel.goldstick at gmail.com Mon Dec 28 07:32:34 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Dec 2015 07:32:34 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <4023d75d-5e96-40b0-b1b1-a193c722004d@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> <4023d75d-5e96-40b0-b1b1-a193c722004d@googlegroups.com> Message-ID: On Mon, Dec 28, 2015 at 4:53 AM, lee wrote: > On Monday, December 28, 2015 at 10:38:47 AM UTC+1, Ben Finney wrote: > > lee writes: > > > > > I'm still stuck on this, any Rescuer? > > > > You appear to be yet another different person asking about this homework > > assignment. > > > > Please: > > > > * This forum is not suitable for the kind of close attention to very > > basic learning. Take this discussion to the 'tutor' forum > > , which is much > > better focussed on close collaborative mentoring of beginners. > > > > * Choose a single spokesperson, and have that person provide continuity > > in the discussion by responding consistently from the same email > > address. > > > > * Learn proper email etiquette (plain text messages, quoted material, > > give sufficient context, etc.) to help the community understand what > > each message is about. > > > > -- > > \ "Holy uncanny photographic mental processes, Batman!" --Robin | > > `\ | > > _o__) | > > Ben Finney > > > if you have followed this thread from the beginning , you should have > been aware that different people have contributed in asking/answering on > this same discussion and nobody has any problem with that, so please if > someone ( same or different) needs help on a single problem , allow them > contribute, they could be the source of getting the problem solved. thanks > prince( botic) , will try you suggestion > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From breamoreboy at yahoo.co.uk Mon Dec 28 09:27:54 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 28 Dec 2015 14:27:54 +0000 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> Message-ID: On 28/12/2015 09:25, lee wrote: > I'm still stuck on this, any Rescuer? > Try running your code at an interactive prompt, or in a debugger, or use paper and pencil to trace what the code is actually doing as opposed to what you are required to get it to do. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From besimms at gmail.com Mon Dec 28 10:35:18 2015 From: besimms at gmail.com (Brian Simms) Date: Mon, 28 Dec 2015 07:35:18 -0800 (PST) Subject: Converting py files to .exe and .dmg Message-ID: <9b206057-0593-4560-af40-442d03111770@googlegroups.com> Hi there, I have done a lot of looking around online to find out how to convert Python files to .exe and .dmg files, but I am confused. Could someone provide pointers/advice as to how I can turn a Python file into a Windows .exe and Mac .dmg file. Thanks for any help. From denismfmcmahon at gmail.com Mon Dec 28 10:48:08 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 28 Dec 2015 15:48:08 -0000 (UTC) Subject: Converting py files to .exe and .dmg References: <9b206057-0593-4560-af40-442d03111770@googlegroups.com> Message-ID: On Mon, 28 Dec 2015 07:35:18 -0800, Brian Simms wrote: > I have done a lot of looking around online to find out how to convert > Python files to .exe and .dmg files, but I am confused. Could someone > provide pointers/advice as to how I can turn a Python file into a > Windows .exe and Mac .dmg file. Python files are scripts, they need to be run by an interpreter. If you want an executable file, you need to compile them. I don't know if this is possible. Otherwise, if you want to distribute the .py files, then the people you distribute them to will need to install a python interpreter on the machine they wish to execute them on. -- Denis McMahon, denismfmcmahon at gmail.com From amorawski at magna-power.com Mon Dec 28 11:09:12 2015 From: amorawski at magna-power.com (Adam M) Date: Mon, 28 Dec 2015 08:09:12 -0800 (PST) Subject: Converting py files to .exe and .dmg In-Reply-To: <9b206057-0593-4560-af40-442d03111770@googlegroups.com> References: <9b206057-0593-4560-af40-442d03111770@googlegroups.com> Message-ID: On Monday, December 28, 2015 at 10:35:41 AM UTC-5, Brian Simms wrote: > Hi there, > > I have done a lot of looking around online to find out how to convert Python files to .exe and .dmg files, but I am confused. Could someone provide pointers/advice as to how I can turn a Python file into a Windows .exe and Mac .dmg file. > > Thanks for any help. Please check this website: http://www.pyinstaller.org/ It should solve your problem. From mbrahimi02 at gmail.com Mon Dec 28 16:43:02 2015 From: mbrahimi02 at gmail.com (Malik Brahimi) Date: Mon, 28 Dec 2015 16:43:02 -0500 Subject: Message Box Message-ID: Hey Guys, I have an event driven script that prompts users as the events are triggered with a message box. Is there anyway with any GUI toolkit to create these dialogs simultaneously in the event that they coincide? I have been trying everything, but I can't seem to get it right. Malik From princeudo52 at gmail.com Mon Dec 28 17:10:13 2015 From: princeudo52 at gmail.com (botic) Date: Mon, 28 Dec 2015 14:10:13 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <4023d75d-5e96-40b0-b1b1-a193c722004d@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <79ce6cf5-4bad-47f6-8824-44ce9849d825@googlegroups.com> <4023d75d-5e96-40b0-b1b1-a193c722004d@googlegroups.com> Message-ID: <1fa635dd-704b-41c6-a6e0-f3be0dac1fe5@googlegroups.com> lee, i will give u the answer just inbox me princeudo55 at yahoo.com, so that i can drop it privately From cs at zip.com.au Mon Dec 28 17:29:53 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 29 Dec 2015 09:29:53 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> References: <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> Message-ID: <20151228222953.GA94789@cskk.homeip.net> On 28Dec2015 01:34, Prince Udoka wrote: >bu i have come up with a solution, that will work but encounter a problem in the set, giving set not manipulated correctly: > >def manipulate_data(kind, data): > if kind == 'list': > return list(data)[::-1] > elif kind == 'set': > return set(data) > elif kind == 'dictionary': > return dict.keys(data) >manipulate_data("list", range(1,6)) >manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) >manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) > >the thing now is the function to use in adding "ANDELA", "TIA", "AFRICA" >pls 4give my use of language You are very close. Let me remind you of the original task text: add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set Your previous attempt (with hardwired values inside the function) actually had code to do it. While you have pulled out all the hardwired values from the function (good) and put them in the external calls, note that the task explicitly says "add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set". So _those_ values _are_ supposed to be hardwired inside the function - they are a fixed part of the task. So move them back in, as in your previous attempt. There is some ambiguity in that part of the question: should you return a _new_ set consistint of the original set plus the three new values, or simply add the three values to the original set? Your prior code modified the original set, which may fit the task specification. However, it is a common design objective that functions do not, _normally_, modify their arguments. So, consider this code: set1 = {"a", "b", "c", "d", "e"} set2 = manipulate_data("set", set1) After running this, set2 should look like this: {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"} (in some order -- sets are not ordered). However, what about set1? In your current code, set1 is modified, so it will be the same. But you can imagine that it would be more useful for the caller if set1 were unchanged. In python, the convention is usually that if a function returns the new value then it should not modify the original. So you should probably construct a copy of the original set and modify that: data = set(data) ... add the new values ... return data Cheers, Cameron Simpson From princeudo52 at gmail.com Mon Dec 28 17:35:15 2015 From: princeudo52 at gmail.com (Prince Udoka) Date: Mon, 28 Dec 2015 23:35:15 +0100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <20151228222953.GA94789@cskk.homeip.net> References: <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> <20151228222953.GA94789@cskk.homeip.net> Message-ID: thanks everyone, though it was very tough, but i thank GOD On Mon, Dec 28, 2015 at 11:29 PM, Cameron Simpson wrote: > On 28Dec2015 01:34, Prince Udoka wrote: > >> bu i have come up with a solution, that will work but encounter a problem >> in the set, giving set not manipulated correctly: >> >> def manipulate_data(kind, data): >> if kind == 'list': >> return list(data)[::-1] >> elif kind == 'set': >> return set(data) >> elif kind == 'dictionary': >> return dict.keys(data) >> manipulate_data("list", range(1,6)) >> manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", >> "AFRICA"}) >> manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, >> "grapes": 45}) >> >> the thing now is the function to use in adding "ANDELA", "TIA", "AFRICA" >> pls 4give my use of language >> > > You are very close. Let me remind you of the original task text: > > add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the > resulting set > > Your previous attempt (with hardwired values inside the function) actually > had code to do it. > > While you have pulled out all the hardwired values from the function > (good) and put them in the external calls, note that the task explicitly > says "add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set". So _those_ > values _are_ supposed to be hardwired inside the function - they are a > fixed part of the task. So move them back in, as in your previous attempt. > > There is some ambiguity in that part of the question: should you return a > _new_ set consistint of the original set plus the three new values, or > simply add the three values to the original set? Your prior code modified > the original set, which may fit the task specification. > > However, it is a common design objective that functions do not, > _normally_, modify their arguments. So, consider this code: > > set1 = {"a", "b", "c", "d", "e"} > set2 = manipulate_data("set", set1) > > After running this, set2 should look like this: > > {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"} > > (in some order -- sets are not ordered). However, what about set1? In your > current code, set1 is modified, so it will be the same. But you can imagine > that it would be more useful for the caller if set1 were unchanged. > > In python, the convention is usually that if a function returns the new > value then it should not modify the original. So you should probably > construct a copy of the original set and modify that: > > data = set(data) > ... add the new values ... > return data > > Cheers, > Cameron Simpson > From tjreedy at udel.edu Mon Dec 28 18:41:47 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Dec 2015 18:41:47 -0500 Subject: Message Box In-Reply-To: References: Message-ID: On 12/28/2015 4:43 PM, Malik Brahimi wrote: > I have an event driven script What does that mean, more specifically? > that prompts users as the events are > triggered with a message box. Is there anyway with any GUI toolkit to > create these dialogs simultaneously in the event that they coincide? Yes, in tkinter, though the events must be tk events. (By simultaneously, I presume you mean in the event handler.) -- Terry Jan Reedy From v+python at g.nevcal.com Tue Dec 29 01:50:55 2015 From: v+python at g.nevcal.com (Glenn Linderman) Date: Mon, 28 Dec 2015 22:50:55 -0800 Subject: EOFError: marshal data too short -- causes? Message-ID: <56822D4F.8070309@g.nevcal.com> Here's a sanatized stack trace off my web server: File ".../cgihelpers.py", line 10, in import cgitb File ".../py34/lib/python3.4/cgitb.py", line 24, in import inspect File ".../py34/lib/python3.4/inspect.py", line 54, in from dis import COMPILER_FLAG_NAMES as _flag_names File "", line 2237, in _find_and_load File "", line 2226, in _find_and_load_unlocked File "", line 1200, in _load_unlocked File "", line 1129, in _exec File "", line 1467, in exec_module File "", line 1570, in get_code File "", line 656, in _compile_bytecode EOFError: marshal data too short It worked this morning, and does this now. I hadn't changed anything. The only reference I find on Google seems to be related to out-of-disk-space, so I cleaned up some files, but I'm not sure of how the web server mounts things; df didn't show particularly high usage in any of the disks it reported on. The files I cleaned up are ever-growing log files that I need to clean up now and then manually, but cleaning them up didn't help... and df wasn't complaining anyway. So maybe out-of-disk-space is a red herring, or only one cause of this symptom. When I log in to the web server with Putty, I can run Python at the command prompt, and "import dis" suffices to reproduce the problem. Are there other causes of this symptom than out-of-disk-space? If it is out-of-disk-space, how could one determine which disk? Maybe if not really out of space, it is a bad permission, disallowing creation of a temporary file? But how could one determine which temporary file, and where it would be written? From tjreedy at udel.edu Tue Dec 29 02:19:22 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Dec 2015 02:19:22 -0500 Subject: EOFError: marshal data too short -- causes? In-Reply-To: <56822D4F.8070309@g.nevcal.com> References: <56822D4F.8070309@g.nevcal.com> Message-ID: On 12/29/2015 1:50 AM, Glenn Linderman wrote: > Here's a sanatized stack trace off my web server: > > File ".../cgihelpers.py", line 10, in > import cgitb > File ".../py34/lib/python3.4/cgitb.py", line 24, in > import inspect > File ".../py34/lib/python3.4/inspect.py", line 54, in > from dis import COMPILER_FLAG_NAMES as _flag_names > File "", line 2237, in _find_and_load > File "", line 2226, in _find_and_load_unlocked > File "", line 1200, in _load_unlocked > File "", line 1129, in _exec > File "", line 1467, in exec_module > File "", line 1570, in get_code > File "", line 656, in _compile_bytecode > EOFError: marshal data too short > > > It worked this morning, and does this now. I hadn't changed anything. Since it crashes trying to unmarshal compiled dis bytecode, I would assume that the .pyc file is corrupted and remove it. Based on the above, it should be in .../py34/lib/python3.4/__pycache__/dis.*.pyc Python will then recompile dis and write a new .pyc file. -- Terry Jan Reedy From v+python at g.nevcal.com Tue Dec 29 03:01:00 2015 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 29 Dec 2015 00:01:00 -0800 Subject: EOFError: marshal data too short -- causes? In-Reply-To: References: <56822D4F.8070309@g.nevcal.com> Message-ID: <56823DBC.9010205@g.nevcal.com> On 12/28/2015 11:19 PM, Terry Reedy wrote: > On 12/29/2015 1:50 AM, Glenn Linderman wrote: >> Here's a sanatized stack trace off my web server: >> >> File ".../cgihelpers.py", line 10, in >> import cgitb >> File ".../py34/lib/python3.4/cgitb.py", line 24, in >> import inspect >> File ".../py34/lib/python3.4/inspect.py", line 54, in >> from dis import COMPILER_FLAG_NAMES as _flag_names >> File "", line 2237, in _find_and_load >> File "", line 2226, in _find_and_load_unlocked >> File "", line 1200, in _load_unlocked >> File "", line 1129, in _exec >> File "", line 1467, in exec_module >> File "", line 1570, in get_code >> File "", line 656, in _compile_bytecode >> EOFError: marshal data too short >> >> >> It worked this morning, and does this now. I hadn't changed anything. > > Since it crashes trying to unmarshal compiled dis bytecode, I would > assume that the .pyc file is corrupted and remove it. Based on the > above, it should be in > .../py34/lib/python3.4/__pycache__/dis.*.pyc > Python will then recompile dis and write a new .pyc file. > Thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you! The site is working now, again. Thank you, again. Because of the File "" lines, and the fact that there were recent comments about frozen import stuff on python-dev, I was thinking that the corruption was at a lower level, and never thought to zap a .pyc. OK, so I actually renamed it instead of zapping it. Them, actually, there were both .pyc and .pyo. Now the __pycache__ directory is full of .pyc and .pyo files (from the install? On April 19th? (the date on most of the files). But: areliabl at areliabledomain.com [~/py34/lib/python3.4/__pycache__]# ll dis* -rw-r--r-- 1 areliabl areliabl 14588 Dec 29 00:27 dis.cpython-34.pyc -rw-r--r-- 1 areliabl areliabl 8192 Dec 28 19:16 dis.cpython-34.pyc-xxx -rw-r--r-- 1 areliabl areliabl 14588 Apr 19 2015 dis.cpython-34.pyo-xxx (I renamed the existing .py* files by appending -xxx). So we can see that somehow, today at 19:16 (probably UTC) the dis.*.pyc file got chopped to 8192 bytes. That's a suspicious number, being a power of 2... but... I haven't updated Python since originally installing it on the web server, on April 19th. So why would _that_ .pyc file have today's date? Because of UTC, the replacement has tomorrow's date :) But it seems like it should have had Apr 19 2015 like all the rest. Except, all the rest don't have Apr 19 2015... most of them do, but there are a fair number from today, and a couple from Dec 15 (listed below). I don't quickly see any others that are suspiciously exactly a power of 2! But, under the assumption that the install created all these files in the first place, why would _any_ of them have newer dates? I haven't gone around deleting any .pyc files since April. And if they are already there, why would Python rebuild them? Isn't the point of the .pyc files to not need to recompile? And even if the original build didn't build them, since I haven't touch the python sources on this web server for months, shouldn't all the files be months old, at least? And isn't it rather suspicious that of the ones that are rebuilt, that all of them have exactly the same timestamp, rather than being sprinkled around with different dates? Well, the two from Dec 15 have the same time, and all the ones from today have the same time. But that doesn't seem like some sort of "random error or access conflict accessing file causing it to be rebuilt".... Should I accuse my web host of playing with these files? Are they backing up/restoring? Are they simply touching the files? Is their infrastructure flaky such that whole groups of files get deleted now and then (and either rebuilt or restored with a different date)? areliabl at areliabledomain.com [~/py34/lib/python3.4/__pycache__]# find -mtime -240 -ls 113654924 20 drwxr-xr-x 2 areliabl areliabl 20480 Dec 29 00:27 . 113639463 76 -rw-r--r-- 1 areliabl areliabl 76650 Dec 28 19:16 ./inspect.cpython-34.pyc 113639477 16 -rw-r--r-- 1 areliabl areliabl 14588 Dec 29 00:27 ./dis.cpython-34.pyc 113639458 16 -rw-r--r-- 1 areliabl areliabl 12361 Dec 28 19:16 ./ast.cpython-34.pyc 113639451 36 -rw-r--r-- 1 areliabl areliabl 32773 Dec 28 19:16 ./shutil.cpython-34.pyc 113639468 12 -rw-r--r-- 1 areliabl areliabl 10371 Dec 28 19:16 ./contextlib.cpython-34.pyc 113639469 16 -rw-r--r-- 1 areliabl areliabl 15916 Dec 28 19:16 ./lzma.cpython-34.pyc 113639475 16 -rw-r--r-- 1 areliabl areliabl 15130 Dec 28 19:16 ./bz2.cpython-34.pyc 113639486 68 -rw-r--r-- 1 areliabl areliabl 67747 Dec 28 19:16 ./tarfile.cpython-34.pyc 113639479 68 -rw-r--r-- 1 areliabl areliabl 65875 Dec 28 19:16 ./argparse.cpython-34.pyc 113639459 48 -rw-r--r-- 1 areliabl areliabl 45794 Dec 28 19:16 ./zipfile.cpython-34.pyc 113639484 32 -rw-r--r-- 1 areliabl areliabl 31374 Dec 28 19:16 ./platform.cpython-34.pyc 113639450 8 -rw-r--r-- 1 areliabl areliabl 4608 Dec 15 03:01 ./copyreg.cpython-34.pyc 113639474 16 -rw-r--r-- 1 areliabl areliabl 13665 Dec 28 19:16 ./textwrap.cpython-34.pyc 113639454 44 -rw-r--r-- 1 areliabl areliabl 43428 Dec 28 19:16 ./subprocess.cpython-34.pyc 113639452 40 -rw-r--r-- 1 areliabl areliabl 39051 Dec 15 03:01 ./threading.cpython-34.pyc 113639472 16 -rw-r--r-- 1 areliabl areliabl 12721 Dec 28 19:16 ./gettext.cpython-34.pyc 113639470 8 -rw-r--r-- 1 areliabl areliabl 8060 Dec 28 19:16 ./copy.cpython-34.pyc 113639467 8 -rw-r--r-- 1 areliabl areliabl 6370 Dec 28 19:16 ./hashlib.cpython-34.pyc 113639483 12 -rw-r--r-- 1 areliabl areliabl 11461 Dec 28 19:16 ./pprint.cpython-34.pyc 113639460 8 -rw-r--r-- 1 areliabl areliabl 7871 Dec 28 19:16 ./string.cpython-34.pyc 113639478 32 -rw-r--r-- 1 areliabl areliabl 29697 Dec 28 19:16 ./cgi.cpython-34.pyc 113639464 20 -rw-r--r-- 1 areliabl areliabl 17601 Dec 28 19:16 ./pkgutil.cpython-34.pyc 113639453 8 -rw-r--r-- 1 areliabl areliabl 6437 Dec 28 19:16 ./quopri.cpython-34.pyc 113639476 8 -rw-r--r-- 1 areliabl areliabl 8192 Dec 28 19:16 ./dis.cpython-34.pyc-xxx 113639466 92 -rw-r--r-- 1 areliabl areliabl 90383 Dec 28 19:16 ./pydoc.cpython-34.pyc 113639461 12 -rw-r--r-- 1 areliabl areliabl 8466 Dec 28 19:16 ./_weakrefset.cpython-34.pyc 113639465 20 -rw-r--r-- 1 areliabl areliabl 19060 Dec 28 19:16 ./random.cpython-34.pyc areliabl at areliabledomain.com [~/py34/lib/python3.4/__pycache__]# From malitician at gmail.com Tue Dec 29 03:49:56 2015 From: malitician at gmail.com (lee) Date: Tue, 29 Dec 2015 00:49:56 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <57a7133b-8ee0-4196-b2e5-6aa393a4e5fb@googlegroups.com> Message-ID: <87543121-d6b5-46da-8b0e-b3001a9afd69@googlegroups.com> On Monday, December 28, 2015 at 11:30:18 PM UTC+1, Cameron Simpson wrote: > On 28Dec2015 01:34, Prince Udoka wrote: > >bu i have come up with a solution, that will work but encounter a problem in the set, giving set not manipulated correctly: > > > >def manipulate_data(kind, data): > > if kind == 'list': > > return list(data)[::-1] > > elif kind == 'set': > > return set(data) > > elif kind == 'dictionary': > > return dict.keys(data) > >manipulate_data("list", range(1,6)) > >manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) > >manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) > > > >the thing now is the function to use in adding "ANDELA", "TIA", "AFRICA" > >pls 4give my use of language > > You are very close. Let me remind you of the original task text: > > add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the > resulting set > > Your previous attempt (with hardwired values inside the function) actually had > code to do it. > > While you have pulled out all the hardwired values from the function (good) and > put them in the external calls, note that the task explicitly says "add items > `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set". So _those_ values _are_ > supposed to be hardwired inside the function - they are a fixed part of the > task. So move them back in, as in your previous attempt. > > There is some ambiguity in that part of the question: should you return a _new_ > set consistint of the original set plus the three new values, or simply add the > three values to the original set? Your prior code modified the original set, > which may fit the task specification. > > However, it is a common design objective that functions do not, _normally_, > modify their arguments. So, consider this code: > > set1 = {"a", "b", "c", "d", "e"} > set2 = manipulate_data("set", set1) > > After running this, set2 should look like this: > > {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"} > > (in some order -- sets are not ordered). However, what about set1? In your > current code, set1 is modified, so it will be the same. But you can imagine > that it would be more useful for the caller if set1 were unchanged. > > In python, the convention is usually that if a function returns the new value > then it should not modify the original. So you should probably construct a copy > of the original set and modify that: > > data = set(data) > ... add the new values ... > return data > > Cheers, > Cameron Simpson thumbs up Cameron , you and others here are really wonderful From cs at zip.com.au Tue Dec 29 05:48:04 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 29 Dec 2015 21:48:04 +1100 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <87543121-d6b5-46da-8b0e-b3001a9afd69@googlegroups.com> References: <87543121-d6b5-46da-8b0e-b3001a9afd69@googlegroups.com> Message-ID: <20151229104804.GA15703@cskk.homeip.net> On 29Dec2015 00:49, lee wrote: >thumbs up Cameron , you and others here are really wonderful >https://mail.python.org/mailman/listinfo/python-list Hi Lee, While we're generally happy to help, these questions are better taken to the tutor list here: https://mail.python.org/mailman/listinfo/tutor Please join that list and ask you questions there. The "python-list" list is more for people who are already competent with Python and programming and who are asking broader questions. The tutor list is specificly aimed at people like yourself who are either very new to Python or new to programming (and learning to program in Python). Note that I have directed replies to this specific message to myself, we're off topic for python-list now... Cheers, Cameron Simpson From xeonmailinglist at gmail.com Tue Dec 29 06:15:33 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 03:15:33 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. Message-ID: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> 1. How do I create a global variable that can be accessed by all classes? 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? setter is the setter.py getter is the getter.py Memoize is the file in [1]. [1] my dogpile class `Memoize.py` from dogpile.cache import make_region region = make_region().configure('dogpile.cache.memory') def save(key, value): """ general purpose method to save data (value) in the cache :param key (string) key of the value to be saved in cache :param value (any type) the value to be saved """ region.set(key, value) def get(key): """ general purpose method to get data from the cache :param key (string) key of the data to be fetched :return value (any type) data to be returned from the cache """ return region.get(key) [2] My python example `setter.py` def myset(value): Memoize.save("myvalue", value) `getter.py` def myget(): return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE My class: setter.myset(123) getter.myget() From skybuck2000 at hotmail.com Tue Dec 29 06:23:53 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Tue, 29 Dec 2015 12:23:53 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: <1b7d$56826d33$d47876e2$47163@news.ziggo.nl> "Chris Angelico" wrote in message news:mailman.62.1450799815.2237.python-list at python.org... On Wed, Dec 23, 2015 at 2:46 AM, Skybuck Flying wrote: > One idea which immediatly comes to mind to fix this problem is to offer a > "PushTerminationFlag" onto stack and then a "ClearTerminationFlag" > instruction. > > Then a code section can be executed without breaking or terminating. > > Once that's done the code would then call "PopTerminationFlag". > > At least this offers some protection against arbitrarely breaking code > sections. " Here on python-list/comp.lang.python, we have all those high level facilities. " Ok, if that were true, please solve the problem then with python code ! ;) Bye, Skybuck. From skybuck2000 at hotmail.com Tue Dec 29 06:25:28 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Tue, 29 Dec 2015 12:25:28 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: <6f90e$56826d92$d47876e2$48098@news.ziggo.nl> "Grant Edwards" wrote in message news:n59k40$e27$1 at reader1.panix.com... On 2015-12-21, Dennis Lee Bieber wrote: > On Mon, 21 Dec 2015 13:40:21 +0100, "Skybuck Flying" > declaimed the following: > >>The original idea I posted is less about sending a signal to another >>processor. >> >>It is more about how to break out of an instruction sequence. >> >>Example of problem: >> >>Main: >>while Condition1 do >>begin >> while Condition2 do >> begin >> while Condition3 do >> begin >> Routine1 >> end >> end; >>end; >> > I do hope this is the result of over simplification for the example, as > otherwise I'd turn it into > > while C1 and C2 and C3: > R1 " Not that this means that all rest of what Skyhawk posted makes any sense at all. I've spent a lot of time programming on "bare metal", in assembly, Pascal, PL/M, and C (including using coroutines and various other "multi-thread" constructs with no OS support), and I really don't see the utility of his initial suggestion. " Great that means you will understand the example below: mov eax, 0 add eax, 10 mul eax, 4 There is an instruction sequence for you. This instruction sequence is too long believe it or not. The mission is to make the CPU break out of instruction 2 and execute something else. How would you do it ? Bye, Skybuck. From skybuck2000 at hotmail.com Tue Dec 29 06:42:58 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Tue, 29 Dec 2015 12:42:58 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> Message-ID: <8f4ad$568271ac$d47876e2$59302@news.ziggo.nl> "Grant Edwards" wrote in message news:n59k40$e27$1 at reader1.panix.com... On 2015-12-21, Dennis Lee Bieber wrote: > On Mon, 21 Dec 2015 13:40:21 +0100, "Skybuck Flying" > declaimed the following: > >>The original idea I posted is less about sending a signal to another >>processor. >> >>It is more about how to break out of an instruction sequence. >> >>Example of problem: >> >>Main: >>while Condition1 do >>begin >> while Condition2 do >> begin >> while Condition3 do >> begin >> Routine1 >> end >> end; >>end; >> > I do hope this is the result of over simplification for the example, as > otherwise I'd turn it into > > while C1 and C2 and C3: > R1 " That's not equivalent to what Skybuck posted. Think about what happens when Routine1 causes Condition1 and Condition2 to become false but Condition3 remains true. " Thanks for pointing that out to him, it's funny to see that at least that part of the logic you understand ! ;) " Not that this means that all rest of what Skyhawk posted makes any sense at all. " Perhaps it will help you if I tell you the following: 1. This is just pseudo code. 2. The conditions C1, C2, C3 can be functions/routines returning booleans. Bye, Skybuck. From malitician at gmail.com Tue Dec 29 07:39:02 2015 From: malitician at gmail.com (lee) Date: Tue, 29 Dec 2015 04:39:02 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <87543121-d6b5-46da-8b0e-b3001a9afd69@googlegroups.com> Message-ID: On Tuesday, December 29, 2015 at 11:48:42 AM UTC+1, Cameron Simpson wrote: > On 29Dec2015 00:49, lee wrote: > >thumbs up Cameron , you and others here are really wonderful > >https://mail.python.org/mailman/listinfo/python-list > > Hi Lee, > > While we're generally happy to help, these questions are better taken to the > tutor list here: > > https://mail.python.org/mailman/listinfo/tutor > > Please join that list and ask you questions there. > > The "python-list" list is more for people who are already competent with Python > and programming and who are asking broader questions. The tutor list is > specificly aimed at people like yourself who are either very new to Python or > new to programming (and learning to program in Python). > > Note that I have directed replies to this specific message to myself, we're off > topic for python-list now... > > Cheers, > Cameron Simpson thanks Cameron, i really appreciate your polite response and effort, i will join that list as you suggested. Thanks again From steve at pearwood.info Tue Dec 29 08:22:50 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Dec 2015 00:22:50 +1100 Subject: (Execution) Termination bit, Alternation bit. References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> <6f90e$56826d92$d47876e2$48098@news.ziggo.nl> Message-ID: <5682892c$0$1587$c3e8da3$5496439d@news.astraweb.com> On Tue, 29 Dec 2015 10:25 pm, Skybuck Flying wrote: > Great that means you will understand the example below: > > mov eax, 0 > add eax, 10 > mul eax, 4 > > There is an instruction sequence for you. Skybuck, this is completely off-topic for a Python forum like this. -- Steven From darcy at VybeNetworks.com Tue Dec 29 08:56:25 2015 From: darcy at VybeNetworks.com (D'Arcy J.M. Cain) Date: Tue, 29 Dec 2015 08:56:25 -0500 Subject: EOFError: marshal data too short -- causes? In-Reply-To: <56823DBC.9010205@g.nevcal.com> References: <56822D4F.8070309@g.nevcal.com> <56823DBC.9010205@g.nevcal.com> Message-ID: <20151229085625.036f548d@imp> On Tue, 29 Dec 2015 00:01:00 -0800 Glenn Linderman wrote: > OK, so I actually renamed it instead of zapping it. Them, actually, Really, just zap them. They are object code. Even if you zap a perfectly good .pyc file a perfectly good one will be re-created as soon as you import it. No need to clutter up you file system. -- D'Arcy J.M. Cain Vybe Networks Inc. http://www.VybeNetworks.com/ IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com From damien.ishacian at gmail.com Tue Dec 29 09:25:49 2015 From: damien.ishacian at gmail.com (damien.ishacian at gmail.com) Date: Tue, 29 Dec 2015 06:25:49 -0800 (PST) Subject: yaxis Message-ID: <7c62c35f-3c9d-420b-b453-1cc0f96ae5fe@googlegroups.com> hello I would only change the scale of the y-axis, how to deal with matplotlib.pyplot or another library ? From breamoreboy at yahoo.co.uk Tue Dec 29 10:18:19 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 29 Dec 2015 15:18:19 +0000 Subject: yaxis In-Reply-To: <7c62c35f-3c9d-420b-b453-1cc0f96ae5fe@googlegroups.com> References: <7c62c35f-3c9d-420b-b453-1cc0f96ae5fe@googlegroups.com> Message-ID: On 29/12/2015 14:25, damien.ishacian at gmail.com wrote: > hello I would only change the scale of the y-axis, how to deal with matplotlib.pyplot or another library ? > Please show us your code. The best way to deal with any library is to read the docs so start here http://matplotlib.org/contents.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From xeonmailinglist at gmail.com Tue Dec 29 10:20:45 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 07:20:45 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: > 1. How do I create a global variable that can be accessed by all classes? > > 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? > > setter is the setter.py > getter is the getter.py > Memoize is the file in [1]. > > > [1] my dogpile class `Memoize.py` > > from dogpile.cache import make_region > > region = make_region().configure('dogpile.cache.memory') > > def save(key, value): > """ > general purpose method to save data (value) in the cache > > :param key (string) key of the value to be saved in cache > :param value (any type) the value to be saved > """ > region.set(key, value) > > > def get(key): > """ > general purpose method to get data from the cache > > :param key (string) key of the data to be fetched > :return value (any type) data to be returned from the cache > """ > return region.get(key) > > > [2] My python example > > `setter.py` > > def myset(value): > Memoize.save("myvalue", value) > > `getter.py` > > def myget(): > return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE > > My class: > > setter.myset(123) > getter.myget() The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. From __peter__ at web.de Tue Dec 29 11:17:33 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Dec 2015 17:17:33 +0100 Subject: Cannot get the value from dogpile.cache from different modules. References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: >> 1. How do I create a global variable that can be accessed by all classes? >> >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I >> set and get the same key from different modules, I don't get the value. >> Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. >> Why this happens? >> region = make_region().configure('dogpile.cache.memory') The memory backend wraps a python dict whose contents are only available to a single script and forgotten when that script ends. My crystal ball tells me that you want to communicate between processes rather than "modules" and need a backend that implements persistence. "dogpile.cache.file" seems to be the one without dependencies outside the standard library. From daniel77 at vt.edu Tue Dec 29 11:24:52 2015 From: daniel77 at vt.edu (Daniel Lee) Date: Tue, 29 Dec 2015 11:24:52 -0500 Subject: Python.Exe Problem Message-ID: Hello, When I try to run python.exe on my computer with Windows 8, I get the following error: "Python.exe - Entry Point Not Found" "The Procedure entry point ?terminate@@YAXXZ could not be located in the dynamic link library C:\Program Files\Python3.5\python.exe." What does this error mean and how can I fix it? Thank you. From xeonmailinglist at gmail.com Tue Dec 29 12:13:43 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 09:13:43 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: <10871dc8-ee11-41d8-ad3c-c0aab267be64@googlegroups.com> On Tuesday, December 29, 2015 at 4:18:10 PM UTC, Peter Otten wrote: > xeon Mailinglist wrote: > > > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: > >> 1. How do I create a global variable that can be accessed by all classes? > >> > >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I > >> set and get the same key from different modules, I don't get the value. > >> Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. > >> Why this happens? > > >> region = make_region().configure('dogpile.cache.memory') > > The memory backend wraps a python dict whose contents are only available to > a single script and forgotten when that script ends. > > My crystal ball tells me that you want to communicate between processes > rather than "modules" and need a backend that implements persistence. > "dogpile.cache.file" seems to be the one without dependencies outside the > standard library. No. My problem is that I have method1() that calls method2() which calls myset(). method1() -> method2() -> myset(5). My problem is that, if I try to get the value of myset() inside method1(), I can't have it. It seems that the program has lost the value. From breamoreboy at yahoo.co.uk Tue Dec 29 12:14:19 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 29 Dec 2015 17:14:19 +0000 Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: On 29/12/2015 15:20, xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: >> 1. How do I create a global variable that can be accessed by all classes? >> >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? >> >> setter is the setter.py >> getter is the getter.py >> Memoize is the file in [1]. >> >> >> [1] my dogpile class `Memoize.py` >> >> from dogpile.cache import make_region >> >> region = make_region().configure('dogpile.cache.memory') >> >> def save(key, value): >> """ >> general purpose method to save data (value) in the cache >> >> :param key (string) key of the value to be saved in cache >> :param value (any type) the value to be saved >> """ >> region.set(key, value) >> >> >> def get(key): >> """ >> general purpose method to get data from the cache >> >> :param key (string) key of the data to be fetched >> :return value (any type) data to be returned from the cache >> """ >> return region.get(key) >> >> >> [2] My python example >> >> `setter.py` >> >> def myset(value): >> Memoize.save("myvalue", value) >> >> `getter.py` >> >> def myget(): >> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE >> >> My class: >> >> setter.myset(123) >> getter.myget() > > The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. > Then put everything in one file. Three files for the amount of code you show above is nonsensical. You might like to read http://dirtsimple.org/2004/12/python-is-not-java.html and in response to that http://dirtsimple.org/2004/12/java-is-not-python-either.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From xeonmailinglist at gmail.com Tue Dec 29 12:23:41 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 09:23:41 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: On Tuesday, December 29, 2015 at 5:15:24 PM UTC, Mark Lawrence wrote: > On 29/12/2015 15:20, xeon Mailinglist wrote: > > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: > >> 1. How do I create a global variable that can be accessed by all classes? > >> > >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? > >> > >> setter is the setter.py > >> getter is the getter.py > >> Memoize is the file in [1]. > >> > >> > >> [1] my dogpile class `Memoize.py` > >> > >> from dogpile.cache import make_region > >> > >> region = make_region().configure('dogpile.cache.memory') > >> > >> def save(key, value): > >> """ > >> general purpose method to save data (value) in the cache > >> > >> :param key (string) key of the value to be saved in cache > >> :param value (any type) the value to be saved > >> """ > >> region.set(key, value) > >> > >> > >> def get(key): > >> """ > >> general purpose method to get data from the cache > >> > >> :param key (string) key of the data to be fetched > >> :return value (any type) data to be returned from the cache > >> """ > >> return region.get(key) > >> > >> > >> [2] My python example > >> > >> `setter.py` > >> > >> def myset(value): > >> Memoize.save("myvalue", value) > >> > >> `getter.py` > >> > >> def myget(): > >> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE > >> > >> My class: > >> > >> setter.myset(123) > >> getter.myget() > > > > The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. > > > > Then put everything in one file. Three files for the amount of code you > show above is nonsensical. You might like to read > http://dirtsimple.org/2004/12/python-is-not-java.html and in response to > that http://dirtsimple.org/2004/12/java-is-not-python-either.html > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence No, that's not the answer. This is just an example. I will not give you the full code because it doesn't make any sense... I am trying to explain what is my problem, even though I cannot reproduce it in any simple example. I save several keys with the dogpile and everything is ok, but when I try to save that particular value, it seems that is going to store in a new dictionary, and not in the dictionary with all the values. From xeonmailinglist at gmail.com Tue Dec 29 12:27:02 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 09:27:02 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> Message-ID: <337dc80d-bd55-4976-a716-fc8f793a1322@googlegroups.com> On Tuesday, December 29, 2015 at 5:15:24 PM UTC, Mark Lawrence wrote: > On 29/12/2015 15:20, xeon Mailinglist wrote: > > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: > >> 1. How do I create a global variable that can be accessed by all classes? > >> > >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? > >> > >> setter is the setter.py > >> getter is the getter.py > >> Memoize is the file in [1]. > >> > >> > >> [1] my dogpile class `Memoize.py` > >> > >> from dogpile.cache import make_region > >> > >> region = make_region().configure('dogpile.cache.memory') > >> > >> def save(key, value): > >> """ > >> general purpose method to save data (value) in the cache > >> > >> :param key (string) key of the value to be saved in cache > >> :param value (any type) the value to be saved > >> """ > >> region.set(key, value) > >> > >> > >> def get(key): > >> """ > >> general purpose method to get data from the cache > >> > >> :param key (string) key of the data to be fetched > >> :return value (any type) data to be returned from the cache > >> """ > >> return region.get(key) > >> > >> > >> [2] My python example > >> > >> `setter.py` > >> > >> def myset(value): > >> Memoize.save("myvalue", value) > >> > >> `getter.py` > >> > >> def myget(): > >> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE > >> > >> My class: > >> > >> setter.myset(123) > >> getter.myget() > > > > The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. > > > > Then put everything in one file. Three files for the amount of code you > show above is nonsensical. You might like to read > http://dirtsimple.org/2004/12/python-is-not-java.html and in response to > that http://dirtsimple.org/2004/12/java-is-not-python-either.html > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence Here is the full class that I use to store the data. from dogpile.cache import make_region # my_dictionary = {} region = make_region().configure('dogpile.cache.memory') # arguments={"cache_dict":my_dictionary}) class Cache: @staticmethod def save(key, value): """ general purpose method to save data (value) in the cache :param key (string) key of the value to be saved in cache :param value (any type) the value to be saved """ region.set(key, value) @staticmethod def get(key): """ general purpose method to get data from the cache :param key (string) key of the data to be fetched :return value (any type) data to be returned from the cache """ return region.get(key) @staticmethod def get_or_create(key): """ General purpose method to get data from the cache. If the value does not exist, it creates a list :param: key (string) key of the data to be fetched :return value (any type) data to be returned from the cache """ return region.get_or_create(key, list) @staticmethod def set_job_predictions(rank_list): Cache.save("job_predictions", rank_list) @staticmethod def get_job_predictions(): return Cache.get("job_predictions") From __peter__ at web.de Tue Dec 29 12:33:18 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Dec 2015 18:33:18 +0100 Subject: Cannot get the value from dogpile.cache from different modules. References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <10871dc8-ee11-41d8-ad3c-c0aab267be64@googlegroups.com> Message-ID: xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 4:18:10 PM UTC, Peter Otten wrote: >> xeon Mailinglist wrote: >> >> > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist >> > wrote: >> >> 1. How do I create a global variable that can be accessed by all >> >> classes? >> >> >> >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I >> >> set and get the same key from different modules, I don't get the >> >> value. Here is an example in [2]. The value than I get is >> >> `NO_VALUE.NO_VALUE`. Why this happens? >> >> >> region = make_region().configure('dogpile.cache.memory') >> >> The memory backend wraps a python dict whose contents are only available >> to a single script and forgotten when that script ends. >> >> My crystal ball tells me that you want to communicate between processes >> rather than "modules" and need a backend that implements persistence. >> "dogpile.cache.file" seems to be the one without dependencies outside the >> standard library. > > > No. Does "No" mean "I have run my code with another backend, and the modified script showed the same behaviour"? > My problem is that I have method1() that calls method2() which calls > myset(). method1() -> method2() -> myset(5). My problem is that, if I try > to get the value of myset() inside method1(), I can't have it. It seems > that the program has lost the value. I can't make sense of that. You should be able to nest methods to your heart's content (as long as you don't reach the recursion limit). Can you post minimal versions of your modules in such a way that I can easily run them over here? If you have only one process you probably have somehow managed to get two backend dicts. Unfortunately there's a blind spot on my crystal ball, and I can't see how exactly you did it... From xeonmailinglist at gmail.com Tue Dec 29 12:38:06 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 09:38:06 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <10871dc8-ee11-41d8-ad3c-c0aab267be64@googlegroups.com> Message-ID: <8c87a009-57f7-45c6-bbf8-5c51411758e1@googlegroups.com> On Tuesday, December 29, 2015 at 5:33:43 PM UTC, Peter Otten wrote: > xeon Mailinglist wrote: > > > On Tuesday, December 29, 2015 at 4:18:10 PM UTC, Peter Otten wrote: > >> xeon Mailinglist wrote: > >> > >> > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist > >> > wrote: > >> >> 1. How do I create a global variable that can be accessed by all > >> >> classes? > >> >> > >> >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I > >> >> set and get the same key from different modules, I don't get the > >> >> value. Here is an example in [2]. The value than I get is > >> >> `NO_VALUE.NO_VALUE`. Why this happens? > >> > >> >> region = make_region().configure('dogpile.cache.memory') > >> > >> The memory backend wraps a python dict whose contents are only available > >> to a single script and forgotten when that script ends. > >> > >> My crystal ball tells me that you want to communicate between processes > >> rather than "modules" and need a backend that implements persistence. > >> "dogpile.cache.file" seems to be the one without dependencies outside the > >> standard library. > > > > > > No. > > Does "No" mean "I have run my code with another backend, and the modified > script showed the same behaviour"? > > > My problem is that I have method1() that calls method2() which calls > > myset(). method1() -> method2() -> myset(5). My problem is that, if I try > > to get the value of myset() inside method1(), I can't have it. It seems > > that the program has lost the value. > > I can't make sense of that. You should be able to nest methods to your > heart's content (as long as you don't reach the recursion limit). > > Can you post minimal versions of your modules in such a way that I can > easily run them over here? > > If you have only one process you probably have somehow managed to get two > backend dicts. Unfortunately there's a blind spot on my crystal ball, and I > can't see how exactly you did it... No, I cannot get a simpler example. The simpler example works, and in my code, it doesn't. I thought that it was something related to the variable `region`, but I declare it as global. So, I think that all the sets will go to the same variable. From xeonmailinglist at gmail.com Tue Dec 29 13:22:12 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 10:22:12 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: <8c87a009-57f7-45c6-bbf8-5c51411758e1@googlegroups.com> References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <10871dc8-ee11-41d8-ad3c-c0aab267be64@googlegroups.com> <8c87a009-57f7-45c6-bbf8-5c51411758e1@googlegroups.com> Message-ID: <57353bd4-e089-4cbf-9551-4aed24849c3b@googlegroups.com> On Tuesday, December 29, 2015 at 5:38:17 PM UTC, xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 5:33:43 PM UTC, Peter Otten wrote: > > xeon Mailinglist wrote: > > > > > On Tuesday, December 29, 2015 at 4:18:10 PM UTC, Peter Otten wrote: > > >> xeon Mailinglist wrote: > > >> > > >> > On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist > > >> > wrote: > > >> >> 1. How do I create a global variable that can be accessed by all > > >> >> classes? > > >> >> > > >> >> 2. I am using `dogpile.cache` to store data in the cache [1], but if I > > >> >> set and get the same key from different modules, I don't get the > > >> >> value. Here is an example in [2]. The value than I get is > > >> >> `NO_VALUE.NO_VALUE`. Why this happens? > > >> > > >> >> region = make_region().configure('dogpile.cache.memory') > > >> > > >> The memory backend wraps a python dict whose contents are only available > > >> to a single script and forgotten when that script ends. > > >> > > >> My crystal ball tells me that you want to communicate between processes > > >> rather than "modules" and need a backend that implements persistence. > > >> "dogpile.cache.file" seems to be the one without dependencies outside the > > >> standard library. > > > > > > > > > No. > > > > Does "No" mean "I have run my code with another backend, and the modified > > script showed the same behaviour"? > > > > > My problem is that I have method1() that calls method2() which calls > > > myset(). method1() -> method2() -> myset(5). My problem is that, if I try > > > to get the value of myset() inside method1(), I can't have it. It seems > > > that the program has lost the value. > > > > I can't make sense of that. You should be able to nest methods to your > > heart's content (as long as you don't reach the recursion limit). > > > > Can you post minimal versions of your modules in such a way that I can > > easily run them over here? > > > > If you have only one process you probably have somehow managed to get two > > backend dicts. Unfortunately there's a blind spot on my crystal ball, and I > > can't see how exactly you did it... > > No, I cannot get a simpler example. The simpler example works, and in my code, it doesn't. I thought that it was something related to the variable `region`, but I declare it as global. So, I think that all the sets will go to the same variable. Strangely enough, when I put the set values in the method1(), it works ok. Is it because method2() is in a submodule of method1? From pkpearson at nowhere.invalid Tue Dec 29 13:44:36 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 29 Dec 2015 18:44:36 GMT Subject: yaxis References: <7c62c35f-3c9d-420b-b453-1cc0f96ae5fe@googlegroups.com> Message-ID: On Tue, 29 Dec 2015 06:25:49 -0800 (PST), damien.ishacian at gmail.com wrote: > hello I would only change the scale of the y-axis, how to deal with > matplotlib.pyplot or another library ? Here's a function I use. ax is an "axes" object, which you can get by calling the get-current-axes (gca()) method of some plot object, for example from matplotlib import pyplot as plt expand_limits(plt.gca(), 0.08) plt.show() Anyway, here's the function: def expand_limits(ax, factor): """Expand the limits on a plotting area by the specified factor. """ def expand(xmin, xmax): d = xmax - xmin return xmin - 0.5*factor*d, xmax + 0.5*factor*d ax.set_xlim(*expand(*ax.get_xlim())) ax.set_ylim(*expand(*ax.get_ylim())) -- To email me, substitute nowhere->runbox, invalid->com. From __peter__ at web.de Tue Dec 29 14:11:17 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Dec 2015 20:11:17 +0100 Subject: Cannot get the value from dogpile.cache from different modules. References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <10871dc8-ee11-41d8-ad3c-c0aab267be64@googlegroups.com> <8c87a009-57f7-45c6-bbf8-5c51411758e1@googlegroups.com> Message-ID: xeon Mailinglist wrote: > No, I cannot get a simpler example. The simpler example works, and in my > code, it doesn't. Then you have to add/remove complexity until you find the problematic statements. > I thought that it was something related to the variable > `region`, but I declare it as global. The "global" statement tells a function that a name in the module namespace should be used even though there is an assignment to that name inside the function. Example: _value = 0 def next_int(): global _value _value += 1 return _value It is unlikely that this feature will affect your problem. > So, I think that all the sets will > go to the same variable. You can add print statements to your getters/setters >>> from dogpile.cache import make_region >>> region = make_region() >>> region.configure("dogpile.cache.memory") >>> region.backend to see if the object IDs are the same (I bet they aren't). Another shot in the dark: an unobvious source of running code twice is when you import (directly or indirectly) the main script: $ cat demo.py import demo print "demo" $ python demo.py demo demo From breamoreboy at yahoo.co.uk Tue Dec 29 14:22:44 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 29 Dec 2015 19:22:44 +0000 Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: <337dc80d-bd55-4976-a716-fc8f793a1322@googlegroups.com> References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <337dc80d-bd55-4976-a716-fc8f793a1322@googlegroups.com> Message-ID: On 29/12/2015 17:27, xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 5:15:24 PM UTC, Mark Lawrence wrote: >> On 29/12/2015 15:20, xeon Mailinglist wrote: >>> On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: >>>> 1. How do I create a global variable that can be accessed by all classes? >>>> >>>> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? >>>> >>>> setter is the setter.py >>>> getter is the getter.py >>>> Memoize is the file in [1]. >>>> >>>> >>>> [1] my dogpile class `Memoize.py` >>>> >>>> from dogpile.cache import make_region >>>> >>>> region = make_region().configure('dogpile.cache.memory') >>>> >>>> def save(key, value): >>>> """ >>>> general purpose method to save data (value) in the cache >>>> >>>> :param key (string) key of the value to be saved in cache >>>> :param value (any type) the value to be saved >>>> """ >>>> region.set(key, value) >>>> >>>> >>>> def get(key): >>>> """ >>>> general purpose method to get data from the cache >>>> >>>> :param key (string) key of the data to be fetched >>>> :return value (any type) data to be returned from the cache >>>> """ >>>> return region.get(key) >>>> >>>> >>>> [2] My python example >>>> >>>> `setter.py` >>>> >>>> def myset(value): >>>> Memoize.save("myvalue", value) >>>> >>>> `getter.py` >>>> >>>> def myget(): >>>> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE >>>> >>>> My class: >>>> >>>> setter.myset(123) >>>> getter.myget() >>> >>> The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. >>> >> >> Then put everything in one file. Three files for the amount of code you >> show above is nonsensical. You might like to read >> http://dirtsimple.org/2004/12/python-is-not-java.html and in response to >> that http://dirtsimple.org/2004/12/java-is-not-python-either.html >> >> -- >> My fellow Pythonistas, ask not what our language can do for you, ask >> what you can do for our language. >> >> Mark Lawrence > > Here is the full class that I use to store the data. > > from dogpile.cache import make_region > > > # my_dictionary = {} > region = make_region().configure('dogpile.cache.memory') > # arguments={"cache_dict":my_dictionary}) > class Cache: > > @staticmethod > def save(key, value): > """ > general purpose method to save data (value) in the cache > > :param key (string) key of the value to be saved in cache > :param value (any type) the value to be saved > """ > region.set(key, value) > > @staticmethod > def get(key): > """ > general purpose method to get data from the cache > > :param key (string) key of the data to be fetched > :return value (any type) data to be returned from the cache > """ > return region.get(key) > > > @staticmethod > def get_or_create(key): > """ > General purpose method to get data from the cache. If the value does not exist, it creates a list > > :param: key (string) key of the data to be fetched > :return value (any type) data to be returned from the cache > """ > return region.get_or_create(key, list) > > @staticmethod > def set_job_predictions(rank_list): > Cache.save("job_predictions", rank_list) > > @staticmethod > def get_job_predictions(): > return Cache.get("job_predictions") > I get the strong impression that you're reinventing wheels and doing it so badly that they're triangular. Have you tried pypi https://pypi.python.org/pypi for proven code that could do the job 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 tjreedy at udel.edu Tue Dec 29 15:44:47 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Dec 2015 15:44:47 -0500 Subject: Python.Exe Problem In-Reply-To: References: Message-ID: On 12/29/2015 11:24 AM, Daniel Lee wrote: > Hello, > > When I try to run python.exe on my computer with Windows 8, Which exact version? From what source? How did you download (from where) or compile? How did you install? How do you try to run it? > I get the following error: > > "Python.exe - Entry Point Not Found" > > "The Procedure entry point ?terminate@@YAXXZ could not be located in the > dynamic link library C:\Program Files\Python3.5\python.exe." Google return 76000 hits for 'terminate@@YAXXZ', so this appears to not be a unique issue in some form or another. > What does this error mean and how can I fix it? It seems like your installed python.exe is corrupt. Make sure you have a final release. I would re-install, possibly after re-downloading from python.org. If you download from anywhere else, *they* are responsible for getting the compile options correct. -- Terry Jan Reedy From tjreedy at udel.edu Tue Dec 29 16:00:53 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Dec 2015 16:00:53 -0500 Subject: EOFError: marshal data too short -- causes? In-Reply-To: <56823DBC.9010205@g.nevcal.com> References: <56822D4F.8070309@g.nevcal.com> <56823DBC.9010205@g.nevcal.com> Message-ID: On 12/29/2015 3:01 AM, Glenn Linderman wrote: > Now the __pycache__ directory is full of .pyc and .pyo files (from the > install? The installer optionally runs compileall on /Lib and recursively on its subpackages. The option defaults to 'yes', at least for 'install for everyone', as writing files within the default Program Files location requires Admin permission. On April 19th? (the date on most of the files). But: > > areliabl at areliabledomain.com [~/py34/lib/python3.4/__pycache__]# ll dis* > -rw-r--r-- 1 areliabl areliabl 14588 Dec 29 00:27 dis.cpython-34.pyc > -rw-r--r-- 1 areliabl areliabl 8192 Dec 28 19:16 dis.cpython-34.pyc-xxx > -rw-r--r-- 1 areliabl areliabl 14588 Apr 19 2015 dis.cpython-34.pyo-xxx > > (I renamed the existing .py* files by appending -xxx). > > So we can see that somehow, today at 19:16 (probably UTC) the dis.*.pyc > file got chopped to 8192 bytes. That's a suspicious number, being a > power of 2... but... I haven't updated Python since originally > installing it on the web server, on April 19th. So why would _that_ > .pyc file have today's date? Because of UTC, the replacement has > tomorrow's date :) But it seems like it should have had Apr 19 2015 > like all the rest. I updated to 2.7.11, 3.4.4, and 3.5.1 a couple of weeks ago, so the timestamps are all fresh. So I don't know what happened with 3.4.3 timestamps from last April and whether Windows itself touches the files. I just tried importing a few and Python did not. > And isn't it rather suspicious that of the ones that are rebuilt, that > all of them have exactly the same timestamp, rather than being sprinkled > around with different dates? Well, the two from Dec 15 have the same > time, and all the ones from today have the same time. But that doesn't > seem like some sort of "random error or access conflict accessing file > causing it to be rebuilt".... > > Should I accuse my web host of playing with these files? Are they > backing up/restoring? Are they simply touching the files? Is their > infrastructure flaky such that whole groups of files get deleted now and > then (and either rebuilt or restored with a different date)? You could ask, without 'accusing'. Or you could re-run compileall yourself. Or you could upgrade to 3.4.4 (I recommend this) and let the installer do so, or not. -- Terry Jan Reedy From skybuck2000 at hotmail.com Tue Dec 29 16:43:18 2015 From: skybuck2000 at hotmail.com (Skybuck Flying) Date: Tue, 29 Dec 2015 22:43:18 +0100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: <5682892c$0$1587$c3e8da3$5496439d@news.astraweb.com> References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> <6f90e$56826d92$d47876e2$48098@news.ziggo.nl> <5682892c$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <45686$5682fe60$d47876e2$14175@news.ziggo.nl> "Steven D'Aprano" wrote in message news:5682892c$0$1587$c3e8da3$5496439d at news.astraweb.com... On Tue, 29 Dec 2015 10:25 pm, Skybuck Flying wrote: > Great that means you will understand the example below: > > mov eax, 0 > add eax, 10 > mul eax, 4 > > There is an instruction sequence for you. " Skybuck, this is completely off-topic for a Python forum like this. " Not at all, these assembler statements can be replaced with python statements and then you have the exact same problem ! ;) Bye, Skybuck. From techtonik at gmail.com Tue Dec 29 17:13:37 2015 From: techtonik at gmail.com (anatoly techtonik) Date: Wed, 30 Dec 2015 01:13:37 +0300 Subject: [Twisted-Python] Twisted 15.4 was the last release to support Python 2.6; or: a HawkOwl Can't Words Situation In-Reply-To: References: Message-ID: Is it possible to fix the documentation? https://twistedmatrix.com/trac/browser/tags/releases/twisted-15.5.0/NEWS?format=raw On Mon, Dec 7, 2015 at 4:06 PM, Amber "Hawkie" Brown wrote: > Hi everyone! > > It's been brought to my attention that I misworded something in the release notes and it slipped through the cracks. In the NEWS I said: > >> This is the last Twisted release where Python 2.6 is supported, on any platform. > > However, I meant that this is the first Twisted release to drop 2.6 support wholesale, preventing import on this platform. Twisted 15.4 will still operate, so if you have Python 2.6 deployment requirements, bracket the maximum to 15.4 on that platform by using an if statement in your setup.py, and `Twisted >=*minreq*,<=15.4; python_version < '2.7'` under requires_dist in your setup.cfg, where minreq is the minimum required Twisted. > > Sorry for the inconvenience! > > - Amber "HawkOwl" Brown > Twisted Release Manager > > _______________________________________________ > Twisted-Python mailing list > Twisted-Python at twistedmatrix.com > http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python > -- anatoly t. From xeonmailinglist at gmail.com Tue Dec 29 17:57:39 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 14:57:39 -0800 (PST) Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <337dc80d-bd55-4976-a716-fc8f793a1322@googlegroups.com> Message-ID: On Tuesday, December 29, 2015 at 7:23:40 PM UTC, Mark Lawrence wrote: > On 29/12/2015 17:27, xeon Mailinglist wrote: > > On Tuesday, December 29, 2015 at 5:15:24 PM UTC, Mark Lawrence wrote: > >> On 29/12/2015 15:20, xeon Mailinglist wrote: > >>> On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: > >>>> 1. How do I create a global variable that can be accessed by all classes? > >>>> > >>>> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? > >>>> > >>>> setter is the setter.py > >>>> getter is the getter.py > >>>> Memoize is the file in [1]. > >>>> > >>>> > >>>> [1] my dogpile class `Memoize.py` > >>>> > >>>> from dogpile.cache import make_region > >>>> > >>>> region = make_region().configure('dogpile.cache.memory') > >>>> > >>>> def save(key, value): > >>>> """ > >>>> general purpose method to save data (value) in the cache > >>>> > >>>> :param key (string) key of the value to be saved in cache > >>>> :param value (any type) the value to be saved > >>>> """ > >>>> region.set(key, value) > >>>> > >>>> > >>>> def get(key): > >>>> """ > >>>> general purpose method to get data from the cache > >>>> > >>>> :param key (string) key of the data to be fetched > >>>> :return value (any type) data to be returned from the cache > >>>> """ > >>>> return region.get(key) > >>>> > >>>> > >>>> [2] My python example > >>>> > >>>> `setter.py` > >>>> > >>>> def myset(value): > >>>> Memoize.save("myvalue", value) > >>>> > >>>> `getter.py` > >>>> > >>>> def myget(): > >>>> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE > >>>> > >>>> My class: > >>>> > >>>> setter.myset(123) > >>>> getter.myget() > >>> > >>> The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. > >>> > >> > >> Then put everything in one file. Three files for the amount of code you > >> show above is nonsensical. You might like to read > >> http://dirtsimple.org/2004/12/python-is-not-java.html and in response to > >> that http://dirtsimple.org/2004/12/java-is-not-python-either.html > >> > >> -- > >> My fellow Pythonistas, ask not what our language can do for you, ask > >> what you can do for our language. > >> > >> Mark Lawrence > > > > Here is the full class that I use to store the data. > > > > from dogpile.cache import make_region > > > > > > # my_dictionary = {} > > region = make_region().configure('dogpile.cache.memory') > > # arguments={"cache_dict":my_dictionary}) > > class Cache: > > > > @staticmethod > > def save(key, value): > > """ > > general purpose method to save data (value) in the cache > > > > :param key (string) key of the value to be saved in cache > > :param value (any type) the value to be saved > > """ > > region.set(key, value) > > > > @staticmethod > > def get(key): > > """ > > general purpose method to get data from the cache > > > > :param key (string) key of the data to be fetched > > :return value (any type) data to be returned from the cache > > """ > > return region.get(key) > > > > > > @staticmethod > > def get_or_create(key): > > """ > > General purpose method to get data from the cache. If the value does not exist, it creates a list > > > > :param: key (string) key of the data to be fetched > > :return value (any type) data to be returned from the cache > > """ > > return region.get_or_create(key, list) > > > > @staticmethod > > def set_job_predictions(rank_list): > > Cache.save("job_predictions", rank_list) > > > > @staticmethod > > def get_job_predictions(): > > return Cache.get("job_predictions") > > > > I get the strong impression that you're reinventing wheels and doing it > so badly that they're triangular. Have you tried pypi > https://pypi.python.org/pypi for proven code that could do the job for you? > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence @Mark I don't understand your remark. Pypi is a repository. What this has to do with my problem? @Peter I have solve the problem, although it is a little bit unclear to me what is the reason. I start to think that this is a problem related to packages and sub-packages. Eg. method1() is in the mypkg/file1.py, and method2() is in mypkg/scheduler/file2.py. From xeonmailinglist at gmail.com Tue Dec 29 18:21:24 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Tue, 29 Dec 2015 15:21:24 -0800 (PST) Subject: Path problems when I am in bash Message-ID: <09513926-226a-4099-a9d4-775ba4b09beb@googlegroups.com> I have my source code inside the directory `medusa`, and my unit tests inside `tests` dir. Both dirs are inside `medusa-2.0` dir. Here is my file structure [1]. When I run my tests inside pycharm, everything works fine, but when I try to run my unit tests inside in the prompt [2], the `scheduler/predictionranking.py` can't find the `hdfs` import [3]. I have set my environment inside the `medusa-2.0` dir with the virtualenv, I even have set `medusa-2.0` in the PYTHON_PATH [4]. The error that I have is in [5]. The question is, why the import is not being done correctly? [1] My file structure medusa-2.0$ medusa (source code) hdfs.py scheduler (dir with my schedulers) predictionranking.py tests (my unit tests) [2] I run the unit test like this. medusa-2.0$ python -v tests/testSimpleRun.py [3] The header in `predictionranking.py` import hdfs def get_prediction_metrics(clusters, pinput): """ :param pinput (list) list of input paths """ input_size = hdfs.get_total_size(pinput) [4] My python path export MEDUSA_HOME=$HOME/repositories/git/medusa-2.0 export PYTHONPATH=${PYTHONPATH}:${MEDUSA_HOME}/medusa [5] error that I have medusa-2.0$ python -v tests/testSimpleRun.py # /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/local.py import medusa.local # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc # /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/ranking.py import medusa.ranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc # /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/decors.py import medusa.decors # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc # /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/settings.py import medusa.settings # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc import medusa.scheduler # directory /home/xeon/repositories/git/medusa-2.0/medusa/scheduler # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.py import medusa.scheduler # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py import medusa.scheduler.predictionranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc Traceback (most recent call last): File "tests/simpleRun.py", line 4, in from medusa.simplealgorithm import run_simple_execution File "/home/xeon/repositories/git/medusa-2.0/medusa/simplealgorithm.py", line 8, in import accidentalfaults File "/home/xeon/repositories/git/medusa-2.0/medusa/accidentalfaults.py", line 5, in import hdfs File "/home/xeon/repositories/git/medusa-2.0/medusa/hdfs.py", line 6, in from system import execute_command File "/home/xeon/repositories/git/medusa-2.0/medusa/system.py", line 10, in from ranking import rank_clusters File "/home/xeon/repositories/git/medusa-2.0/medusa/ranking.py", line 9, in from scheduler.predictionranking import get_prediction_metrics File "/home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py", line 6, in import hdfs From breamoreboy at yahoo.co.uk Tue Dec 29 18:30:31 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 29 Dec 2015 23:30:31 +0000 Subject: Cannot get the value from dogpile.cache from different modules. In-Reply-To: References: <7c8df879-b03a-4323-90c5-3221dd1eced2@googlegroups.com> <337dc80d-bd55-4976-a716-fc8f793a1322@googlegroups.com> Message-ID: On 29/12/2015 22:57, xeon Mailinglist wrote: > On Tuesday, December 29, 2015 at 7:23:40 PM UTC, Mark Lawrence wrote: >> On 29/12/2015 17:27, xeon Mailinglist wrote: >>> On Tuesday, December 29, 2015 at 5:15:24 PM UTC, Mark Lawrence wrote: >>>> On 29/12/2015 15:20, xeon Mailinglist wrote: >>>>> On Tuesday, December 29, 2015 at 11:16:10 AM UTC, xeon Mailinglist wrote: >>>>>> 1. How do I create a global variable that can be accessed by all classes? >>>>>> >>>>>> 2. I am using `dogpile.cache` to store data in the cache [1], but if I set and get the same key from different modules, I don't get the value. Here is an example in [2]. The value than I get is `NO_VALUE.NO_VALUE`. Why this happens? >>>>>> >>>>>> setter is the setter.py >>>>>> getter is the getter.py >>>>>> Memoize is the file in [1]. >>>>>> >>>>>> >>>>>> [1] my dogpile class `Memoize.py` >>>>>> >>>>>> from dogpile.cache import make_region >>>>>> >>>>>> region = make_region().configure('dogpile.cache.memory') >>>>>> >>>>>> def save(key, value): >>>>>> """ >>>>>> general purpose method to save data (value) in the cache >>>>>> >>>>>> :param key (string) key of the value to be saved in cache >>>>>> :param value (any type) the value to be saved >>>>>> """ >>>>>> region.set(key, value) >>>>>> >>>>>> >>>>>> def get(key): >>>>>> """ >>>>>> general purpose method to get data from the cache >>>>>> >>>>>> :param key (string) key of the data to be fetched >>>>>> :return value (any type) data to be returned from the cache >>>>>> """ >>>>>> return region.get(key) >>>>>> >>>>>> >>>>>> [2] My python example >>>>>> >>>>>> `setter.py` >>>>>> >>>>>> def myset(value): >>>>>> Memoize.save("myvalue", value) >>>>>> >>>>>> `getter.py` >>>>>> >>>>>> def myget(): >>>>>> return Memoize.get("myvalue") <- this value is NO_VALUE. NO_VALUE >>>>>> >>>>>> My class: >>>>>> >>>>>> setter.myset(123) >>>>>> getter.myget() >>>>> >>>>> The idea that I get from dogpile, is that in each module (getter.py, or setter.py) there is a dictionary where the values are stored in the backend. Hence, getter.py has its dictionary and setter.py has its dictionary also. In the end, there is not a single dictionary where all the values should be put. And I want a single dictionary. >>>>> >>>> >>>> Then put everything in one file. Three files for the amount of code you >>>> show above is nonsensical. You might like to read >>>> http://dirtsimple.org/2004/12/python-is-not-java.html and in response to >>>> that http://dirtsimple.org/2004/12/java-is-not-python-either.html >>>> >>>> -- >>>> My fellow Pythonistas, ask not what our language can do for you, ask >>>> what you can do for our language. >>>> >>>> Mark Lawrence >>> >>> Here is the full class that I use to store the data. >>> >>> from dogpile.cache import make_region >>> >>> >>> # my_dictionary = {} >>> region = make_region().configure('dogpile.cache.memory') >>> # arguments={"cache_dict":my_dictionary}) >>> class Cache: >>> >>> @staticmethod >>> def save(key, value): >>> """ >>> general purpose method to save data (value) in the cache >>> >>> :param key (string) key of the value to be saved in cache >>> :param value (any type) the value to be saved >>> """ >>> region.set(key, value) >>> >>> @staticmethod >>> def get(key): >>> """ >>> general purpose method to get data from the cache >>> >>> :param key (string) key of the data to be fetched >>> :return value (any type) data to be returned from the cache >>> """ >>> return region.get(key) >>> >>> >>> @staticmethod >>> def get_or_create(key): >>> """ >>> General purpose method to get data from the cache. If the value does not exist, it creates a list >>> >>> :param: key (string) key of the data to be fetched >>> :return value (any type) data to be returned from the cache >>> """ >>> return region.get_or_create(key, list) >>> >>> @staticmethod >>> def set_job_predictions(rank_list): >>> Cache.save("job_predictions", rank_list) >>> >>> @staticmethod >>> def get_job_predictions(): >>> return Cache.get("job_predictions") >>> >> >> I get the strong impression that you're reinventing wheels and doing it >> so badly that they're triangular. Have you tried pypi >> https://pypi.python.org/pypi for proven code that could do the job for you? >> >> -- >> My fellow Pythonistas, ask not what our language can do for you, ask >> what you can do for our language. >> >> Mark Lawrence > > @Mark > I don't understand your remark. Pypi is a repository. What this has to do with my problem? > It might well have working code that you can just use, instead of a dreadful pile of code that has the appalling smell of Java coming out of every seam. -- 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 Tue Dec 29 19:00:03 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Dec 2015 11:00:03 +1100 Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: <45686$5682fe60$d47876e2$14175@news.ziggo.nl> References: <9Bldy.3723$Bz5.1578@fx04.iad> <864af$56760c5f$d47876e2$48630@news.ziggo.nl> <6f90e$56826d92$d47876e2$48098@news.ziggo.nl> <5682892c$0$1587$c3e8da3$5496439d@news.astraweb.com> <45686$5682fe60$d47876e2$14175@news.ziggo.nl> Message-ID: On Wed, Dec 30, 2015 at 8:43 AM, Skybuck Flying wrote: > Not at all, these assembler statements can be replaced with python > statements and then you have the exact same problem ! ;) Then do so. Give us an example where this problem occurs in pure Python. ChrisA From kliateni at gmail.com Tue Dec 29 21:30:24 2015 From: kliateni at gmail.com (Karim) Date: Wed, 30 Dec 2015 03:30:24 +0100 Subject: Path problems when I am in bash In-Reply-To: <09513926-226a-4099-a9d4-775ba4b09beb@googlegroups.com> References: <09513926-226a-4099-a9d4-775ba4b09beb@googlegroups.com> Message-ID: <568341C0.90201@gmail.com> On 30/12/2015 00:21, xeon Mailinglist wrote: > I have my source code inside the directory `medusa`, and my unit tests inside `tests` dir. Both dirs are inside `medusa-2.0` dir. Here is my file structure [1]. > > When I run my tests inside pycharm, everything works fine, but when I try to run my unit tests inside in the prompt [2], the `scheduler/predictionranking.py` can't find the `hdfs` import [3]. I have set my environment inside the `medusa-2.0` dir with the virtualenv, I even have set `medusa-2.0` in the PYTHON_PATH [4]. The error that I have is in [5]. > > The question is, why the import is not being done correctly? > > > [1] My file structure > > medusa-2.0$ > medusa (source code) > hdfs.py > scheduler (dir with my schedulers) > predictionranking.py > tests (my unit tests) > > > [2] I run the unit test like this. > > medusa-2.0$ python -v tests/testSimpleRun.py > > > [3] The header in `predictionranking.py` > > import hdfs > > def get_prediction_metrics(clusters, pinput): > """ > :param pinput (list) list of input paths > > """ > > input_size = hdfs.get_total_size(pinput) > > [4] My python path > > export MEDUSA_HOME=$HOME/repositories/git/medusa-2.0 > > export PYTHONPATH=${PYTHONPATH}:${MEDUSA_HOME}/medusa > > [5] error that I have > > medusa-2.0$ python -v tests/testSimpleRun.py > # /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/local.py > import medusa.local # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc > # /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/ranking.py > import medusa.ranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc > # /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/decors.py > import medusa.decors # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc > # /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/settings.py > import medusa.settings # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc > import medusa.scheduler # directory /home/xeon/repositories/git/medusa-2.0/medusa/scheduler > # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.py > import medusa.scheduler # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc > # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py > import medusa.scheduler.predictionranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc > Traceback (most recent call last): > File "tests/simpleRun.py", line 4, in > from medusa.simplealgorithm import run_simple_execution > File "/home/xeon/repositories/git/medusa-2.0/medusa/simplealgorithm.py", line 8, in > import accidentalfaults > File "/home/xeon/repositories/git/medusa-2.0/medusa/accidentalfaults.py", line 5, in > import hdfs > File "/home/xeon/repositories/git/medusa-2.0/medusa/hdfs.py", line 6, in > from system import execute_command > File "/home/xeon/repositories/git/medusa-2.0/medusa/system.py", line 10, in > from ranking import rank_clusters > File "/home/xeon/repositories/git/medusa-2.0/medusa/ranking.py", line 9, in > from scheduler.predictionranking import get_prediction_metrics > File "/home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py", line 6, in > import hdfs Hello, Can you try to set your PYTHONPATH like that: export PYTHONPATH=${PYTHONPATH}:${MEDUSA_HOME} Regards Karim From rustompmody at gmail.com Tue Dec 29 23:07:04 2015 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 29 Dec 2015 20:07:04 -0800 (PST) Subject: (Execution) Termination bit, Alternation bit. In-Reply-To: References: Message-ID: <8ea4ae8f-23e8-49b9-a24a-9438a65d8a1e@googlegroups.com> On Saturday, December 19, 2015 at 11:26:55 PM UTC+5:30, Skybuck Flying wrote: > Hello, > > I'd like to see instruction execution enhanced with the following two ideas: > > 1. A termination bit, and a terminator pointer. > 2. A alternation bit, and a alternate pointer. > > The purpose of these bits is as follows: > > Before a processor/core executes an instruction both bits are examined. > > 1. If the termination bit is set the instruction is not executed and instead > the processor sets the instruction pointer to the termination pointer. > 2. If the alternation bit is set the instruction is not executed and instead > the processor sets the instruction pointer to the alternation pointer. > > The idea behind this is support multi threading/parallelism better. > > The idea is that Thread A could terminate Thread B immediately so that > Thread B does not continue execution. > The idea is also that Thread A could influence Thread B to start executing a > different path. > > Hopefully these bits are enough for operating systems to add support for > this. Some issues remaining could be items pushed on the stack. > Perhaps operating system can deal with that, or perhaps compiler or perhaps > some other special instructions or software methods can be added. > Hopefully operating systems can include data structures per thread that can > be loaded into the core, and into these bits and pointers so that it becomes > active. > During a context switch these bits and pointers should be loaded > accordingly. > So these two bits and these two pointers become part of the context. > > I think these two features would be usefull to make multi-threading more > responsive and faster reaction time to changes/events occuring. > > (Eventually it would be nice if these low level features would end up in > high level languages like Python ;)) > > Bye, > Skybuck. By some coincidence was just reading: from http://www.wordyard.com/2006/10/18/dijkstra-humble/ which has the following curious extract. [Yeah its outlandish] ---------------------------------------------- I consider the absolute worst programming construct to be subroutine or the function. We've used it for over 50 years now and we're still having difficulty reducing complexity. What if the unthinkable were true? What if the subroutine was the cause of all our problems? I can prove how the subroutine causes all parts of our software to become coupled and as such cannot support this as the basic building blocks of software. I find the subroutine and all the technology around it (OOP, functional, AOP, etc.) are like a sinking ship where you keep throwing more lifeboats when what you really need is a new boat. (The ship being the subroutine and the lifeboats are OOP, funcional, AOP, etc.). I posit a fourth "condition" for being able to produce better software and that is being able to recognise what specifically isn't working and be ready to ditch it. I see no indication of this for at least another 20 or 70 years give or take 100 years. Computing Industry's Best Kept Secret: The function is *NOT* necessary to build software and may in fact be a bad tool. : : [In response to questions of whats the answer to functions] With functions, it's stack based. You have to wait until the function returns in order to process the next function unless it's an internal function. This is the first in, last out rule just like a stack. I don't mean that functions are bad in of themselves for certain things. I mean that maybe they're not the *only* way. Just like different data structures have different uses. Right now, everyone is using the function. Imagine if the stack was the only data structure you could use. What a horrible world. Yet this is what we have with the function. Unix has pipes. These are queues. As data is piped, software on both ends of the queue can execute at the same time. As data passes from one end of the queue to the other, there is no concept of execution point. Only data transformations and transfers. Another example is the Internet where messages (real ones) get passed back and forth. Simple idea that scales and is in active use. We've look into the stack based way of programming to death. Maybe the queue or other data processing model can be looked at, especially to solve concurrency. I feel it's a shame that there are perfectly acceptable tools available that get sidelined for the status quo. BTW, history dictates that the function is not reusable. Well, maybe it's reusable like sand is reusable to build glass. Once it's actually used, it is forever transformed into something else that can no longer be separated from the whole. From xeonmailinglist at gmail.com Wed Dec 30 06:17:37 2015 From: xeonmailinglist at gmail.com (xeon Mailinglist) Date: Wed, 30 Dec 2015 03:17:37 -0800 (PST) Subject: Path problems when I am in bash In-Reply-To: References: <09513926-226a-4099-a9d4-775ba4b09beb@googlegroups.com> Message-ID: On Wednesday, December 30, 2015 at 2:30:40 AM UTC, Karim wrote: > On 30/12/2015 00:21, xeon Mailinglist wrote: > > I have my source code inside the directory `medusa`, and my unit tests inside `tests` dir. Both dirs are inside `medusa-2.0` dir. Here is my file structure [1]. > > > > When I run my tests inside pycharm, everything works fine, but when I try to run my unit tests inside in the prompt [2], the `scheduler/predictionranking.py` can't find the `hdfs` import [3]. I have set my environment inside the `medusa-2.0` dir with the virtualenv, I even have set `medusa-2.0` in the PYTHON_PATH [4]. The error that I have is in [5]. > > > > The question is, why the import is not being done correctly? > > > > > > [1] My file structure > > > > medusa-2.0$ > > medusa (source code) > > hdfs.py > > scheduler (dir with my schedulers) > > predictionranking.py > > tests (my unit tests) > > > > > > [2] I run the unit test like this. > > > > medusa-2.0$ python -v tests/testSimpleRun.py > > > > > > [3] The header in `predictionranking.py` > > > > import hdfs > > > > def get_prediction_metrics(clusters, pinput): > > """ > > :param pinput (list) list of input paths > > > > """ > > > > input_size = hdfs.get_total_size(pinput) > > > > [4] My python path > > > > export MEDUSA_HOME=$HOME/repositories/git/medusa-2.0 > > > > export PYTHONPATH=${PYTHONPATH}:${MEDUSA_HOME}/medusa > > > > [5] error that I have > > > > medusa-2.0$ python -v tests/testSimpleRun.py > > # /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/local.py > > import medusa.local # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/local.pyc > > # /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/ranking.py > > import medusa.ranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/ranking.pyc > > # /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/decors.py > > import medusa.decors # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/decors.pyc > > # /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/settings.py > > import medusa.settings # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/settings.pyc > > import medusa.scheduler # directory /home/xeon/repositories/git/medusa-2.0/medusa/scheduler > > # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.py > > import medusa.scheduler # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/__init__.pyc > > # /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc matches /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py > > import medusa.scheduler.predictionranking # precompiled from /home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.pyc > > Traceback (most recent call last): > > File "tests/simpleRun.py", line 4, in > > from medusa.simplealgorithm import run_simple_execution > > File "/home/xeon/repositories/git/medusa-2.0/medusa/simplealgorithm.py", line 8, in > > import accidentalfaults > > File "/home/xeon/repositories/git/medusa-2.0/medusa/accidentalfaults.py", line 5, in > > import hdfs > > File "/home/xeon/repositories/git/medusa-2.0/medusa/hdfs.py", line 6, in > > from system import execute_command > > File "/home/xeon/repositories/git/medusa-2.0/medusa/system.py", line 10, in > > from ranking import rank_clusters > > File "/home/xeon/repositories/git/medusa-2.0/medusa/ranking.py", line 9, in > > from scheduler.predictionranking import get_prediction_metrics > > File "/home/xeon/repositories/git/medusa-2.0/medusa/scheduler/predictionranking.py", line 6, in > > import hdfs > > Hello, > > Can you try to set your PYTHONPATH like that: > > export PYTHONPATH=${PYTHONPATH}:${MEDUSA_HOME} > > Regards > Karim Thanks. From cts.private.yahoo at gmail.com Wed Dec 30 06:51:19 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 11:51:19 -0000 (UTC) Subject: how to get names of attributes Message-ID: Hi, How can I get *all* the names of an object's attributes? I have legacy code with mixed new style classes and old style classes and I need to write methods which deal with both. That's the immediate problem, but I'm always running into the need to understand how objects are linked, in particular when in pdb. The answers one always sees on StackOverflow is that you don't need to understand, understanding is not the pythonic way to do things. Alternatively, is there are map documented somewhere - more complete than python/python-2.7.3-docs-html/library/stdtypes.html? highlight=class#special-attributes Or, is the code available uncompiled somewhere on my machine? Does anyone know *why* the __members__ method was deprecated, to be replaced by dir(), which doesn't tell the truth (if only it took an optional parameter to say: "be truthful") cts From rosuav at gmail.com Wed Dec 30 06:58:56 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Dec 2015 22:58:56 +1100 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 10:51 PM, Charles T. Smith wrote: > Does anyone know *why* the __members__ method was deprecated, to be > replaced by dir(), which doesn't tell the truth (if only it took an > optional parameter to say: "be truthful") Does vars() help here? It works on old-style and new-style classes, and it's doing broadly the same sort of thing as you're talking about. ChrisA From cts.private.yahoo at gmail.com Wed Dec 30 07:16:46 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 12:16:46 -0000 (UTC) Subject: how to get names of attributes References: Message-ID: On Wed, 30 Dec 2015 11:51:19 +0000, Charles T. Smith wrote: > Hi, > > How can I get *all* the names of an object's attributes? I have legacy > code with mixed new style classes and old style classes and I need to > write methods which deal with both. That's the immediate problem, but > I'm always running into the need to understand how objects are linked, > in particular when in pdb. The answers one always sees on StackOverflow > is that you don't need to understand, understanding is not the pythonic > way to do things. > > Alternatively, is there are map documented somewhere - more complete > than python/python-2.7.3-docs-html/library/stdtypes.html? > highlight=class#special-attributes > > Or, is the code available uncompiled somewhere on my machine? > > Does anyone know *why* the __members__ method was deprecated, to be > replaced by dir(), which doesn't tell the truth (if only it took an > optional parameter to say: "be truthful") > > cts For example: (PDB)pp dir (newclass.__class__) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm2'] (PDB)pp dir (oldclass.__class__) ['__doc__', '__module__', 'm3'] (PDB)pp (oldclass.__class__.__name__) 'C3' (PDB)pp (newclass.__class__.__name__) 'C2' Both dir() invocations are lying to me. The old-style class even ignores the pretty-print command. I'm glad I discovered __mro__(), but how can I do the same thing for old- style classes? From rosuav at gmail.com Wed Dec 30 07:34:03 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Dec 2015 23:34:03 +1100 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 11:16 PM, Charles T. Smith wrote: > I'm glad I discovered __mro__(), but how can I do the same thing for old- > style classes? You should be able to track through __bases__ and use vars() at every level: >>> class X: pass ... >>> class Y(X): pass ... >>> class Z(Y): pass ... >>> X.x=1 >>> Y.y=2 >>> Z.z=3 >>> inst=Z() >>> inst.i=4 >>> def class_vars(old_style_class): ... v = {} ... for cls in old_style_class.__bases__: ... v.update(class_vars(cls)) ... v.update(vars(old_style_class)) ... return v ... >>> def all_vars(old_style_inst): ... v = class_vars(old_style_inst.__class__) ... v.update(vars(old_style_inst)) ... return v ... >>> all_vars(inst) {'i': 4, '__module__': '__main__', 'y': 2, 'x': 1, 'z': 3, '__doc__': None} I'm not 100% sure I've matched the MRO here, but if all you want is the complete set of attribute names, this should work - I think. ChrisA From cts.private.yahoo at gmail.com Wed Dec 30 07:40:09 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 12:40:09 -0000 (UTC) Subject: how to get names of attributes References: Message-ID: On Wed, 30 Dec 2015 11:51:19 +0000, Charles T. Smith wrote: > Hi, > > How can I get *all* the names of an object's attributes? I have legacy > code with mixed new style classes and old style classes and I need to > write methods which deal with both. That's the immediate problem, but > I'm always running into the need to understand how objects are linked, > in particular when in pdb. The answers one always sees on StackOverflow > is that you don't need to understand, understanding is not the pythonic > way to do things. > > Alternatively, is there are map documented somewhere - more complete > than python/python-2.7.3-docs-html/library/stdtypes.html? > highlight=class#special-attributes > > Or, is the code available uncompiled somewhere on my machine? > > Does anyone know *why* the __members__ method was deprecated, to be > replaced by dir(), which doesn't tell the truth (if only it took an > optional parameter to say: "be truthful") > > cts Oh! Although the referenced doc says: "For compatibility reasons, classes are still old-style by default." is it true that dictionaries are by default always new-style objects? (PDB)c6 = { "abc" : 123, "def" : 456} (PDB)isinstance (c6, dict) True (PDB)isinstance (c6, object) True From rosuav at gmail.com Wed Dec 30 07:50:03 2015 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Dec 2015 23:50:03 +1100 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 11:40 PM, Charles T. Smith wrote: > Oh! > > Although the referenced doc says: > > "For compatibility reasons, classes are still old-style by default." > > is it true that dictionaries are by default always new-style objects? > > (PDB)c6 = { "abc" : 123, "def" : 456} > > (PDB)isinstance (c6, dict) > True > > (PDB)isinstance (c6, object) > True I believe that's true, yes. The meaning of "by default" there is that "class X: pass" will make an old-style class. All built-in types are now new-style classes. ChrisA From steve at pearwood.info Wed Dec 30 07:56:41 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Dec 2015 23:56:41 +1100 Subject: (Execution) Termination bit, Alternation bit. References: <8ea4ae8f-23e8-49b9-a24a-9438a65d8a1e@googlegroups.com> Message-ID: <5683d48b$0$1612$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Dec 2015 03:07 pm, Rustom Mody wrote: > By some coincidence was just reading: > from http://www.wordyard.com/2006/10/18/dijkstra-humble/ > > which has the following curious extract. > [Yeah its outlandish] > > ---------------------------------------------- > I consider the absolute worst programming construct to be > subroutine or the function. [...] Rustom, your quote was (I trust inadvertently!) horribly misleading. I thought this was said by Dijkstra, not some random crank on the Internet. The comment from some random person Cleo Saulnier, who starts off with the provocative comment that the *subroutine* is the "the absolute worst programming construct", then goes on to sing the praises of Unix pipes. What are small Unix programs communicating via pipes if not subroutines? Functions are subroutines, but not all subroutines are functions. It is fashionable to dismiss 1970s-style BASIC as a serious language, and for good reason, but let's not forget that for all its problems, a large number of programmers cut their teeth on it. BASIC is, in some ways, like a machine language except with a friendly syntax. There are subroutines, but you can jump into the middle of them, or out from the middle. There are no functions, just jumps to the instruction you want to execute next. Only a limited set of data types to work with. I think every programmer would learn something from trying to write, and maintain, an actual useful piece of code using only a BASIC-like language. At the least, they would appreciate what a huge step-up it was to introduce procedural programming. (A friend of mine once worked under a manager who insisted that writing functions and procedures was a terrible idea, that GOTO was vital, because it was far more efficient to jump to a line of code than call a function. And this was in the late 1990s.) Cleo continues: > I can prove how the subroutine causes all > parts of our software to become coupled and as such cannot > support this as the basic building blocks of software. This is a remarkable claim, considering that one of the advantages of the function is that it can, when used correctly, *reduce* coupling. In non-procedural code, any line of code may be used by any other chunk of code. You can jump to any line, and people did (because they had no alternatives), consequently coupling was very high. In procedural code, any line of code can only be reached from exactly one place: the previous line of code. (Well, a few more, in specialised circumstances: for- and while-loops, branches, etc.) Lines of code *within* a procedure can only couple with other lines within the same procedure; it's true that procedures can have high-coupling or low-coupling, but at least you know that you can change the inside of a procedure as much as you want, and so long as it accepts the same input and generates the same output (and has the same side-effects) it will continue to work. That's reduced coupling. > Unix has pipes. These are queues. As data is piped, software on > both ends of the queue can execute at the same time. As data > passes from one end of the queue to the other, there is no > concept of execution point. That's arguable. When I learned about Unix multi-processing, it was based on a single CPU model: each process would run for a few ticks, before being interrupted by the OS and the next process being allowed to run for a few ticks. A sequential process that merely appeared to be parallel because the CPU was so fast. Perhaps these days Unix is capable of actually running multiple programs in parallel on separate cores or multiple CPUs? As I said earlier, of course Unix programs communicating via pipes are a kind of subroutine. We also have generators, and coroutines, and threads, and other forms of parallel processing. The unsurprising reality is that such kinds of code are *harder* to get right than functions with their simple-minded stack-based sequential execution model. -- Steven From cts.private.yahoo at gmail.com Wed Dec 30 07:57:51 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 12:57:51 -0000 (UTC) Subject: using __getitem()__ correctly Message-ID: Hello, I thought __getitem__() was invoked when an object is postfixed with an expression in brackets: - abc[n] and __getattr__() was invoked when an object is postfixed with an dot: - abc.member but my __getitem__ is being invoked at this time, where there's no subscript (going into a spiral recursion death): self.mcc = self.attrs.mcc Can anybody explain to me why __getitem__() would be invoked here? I'm using __getitem__() AND __getattr__() to handle an array of objects which don't exist yet (autovivification). My __getattr__() could handle the line above, but I don't know how to handle that in __getitem__(): attrdict:av:__getitem__: entered for mcc That's printed by this line: print "attrdict:av:__getitem__: entered for ", key I expected that "key" would always be numeric or a slice TIA cts From rosuav at gmail.com Wed Dec 30 08:11:24 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 00:11:24 +1100 Subject: using __getitem()__ correctly In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 11:57 PM, Charles T. Smith wrote: > Hello, > > I thought __getitem__() was invoked when an object is postfixed with an > expression in brackets: > > - abc[n] > > and __getattr__() was invoked when an object is postfixed with an dot: > > - abc.member That would be normal (with the caveat that __getattr__ is called only if the attribute isn't found; __getattribute__ is called unconditionally). > but my __getitem__ is being invoked at this time, where there's no > subscript (going into a spiral recursion death): > > self.mcc = self.attrs.mcc > > Can anybody explain to me why __getitem__() would be invoked here? Can you post your entire class, or at least __getattr__? Also check superclasses, if there are any. ChrisA From steve at pearwood.info Wed Dec 30 08:18:32 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 00:18:32 +1100 Subject: Is it safe to assume floats always have a 53-bit mantissa? Message-ID: <5683d9aa$0$1618$c3e8da3$5496439d@news.astraweb.com> We know that Python floats are equivalent to C doubles, which are 64-bit IEEE-754 floating point numbers. Well, actually, C doubles are not strictly defined. The only promise the C standard makes is that double is no smaller than float. (That's C float, not Python float.) And of course, not all Python implementations use C. Nevertheless, it's well known (in the sense that "everybody knows") that Python floats are equivalent to C 64-bit IEEE-754 doubles. How safe is that assumption? I have a function with two implementations: a fast implementation that converts an int to a float, does some processing, then converts it back to int. That works fine so long as the int can be represented exactly as a float. The other implementation uses integer maths only, and is much slower but exact. As an optimization, I want to write: def func(n): if n <= 2**53: # use the floating point fast implementation else: # fall back on the slower, but exact, int algorithm (The optimization makes a real difference: for large n, the float version is about 500 times faster.) But I wonder whether I need to write this instead? def func(n): if n <= 2**sys.float_info.mant_dig: # ...float else: # ...int I don't suppose it really makes any difference performance-wise, but I can't help but wonder if it is really necessary. If sys.float_info.mant_dig is guaranteed to always be 53, why not just write 53? -- Steven From rdhkgrvr1 at gmail.com Wed Dec 30 08:24:50 2015 From: rdhkgrvr1 at gmail.com (Radhika Grover) Date: Wed, 30 Dec 2015 05:24:50 -0800 (PST) Subject: PEAK-Rules package. Message-ID: <1fa318c3-787b-4b63-91c2-27a4eefb42be@googlegroups.com> Hi, I don't see any package available under https://pypi.python.org/simple/PEAK-Rules/. Could you please let me know if it has seen a change recently. I need PEAK-Rules>=0.5a1.dev-r2600 using easy_install default behavior. Any help is appreciated. Thanks in advance! - Radhika From cts.private.yahoo at gmail.com Wed Dec 30 08:31:57 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 13:31:57 -0000 (UTC) Subject: how to get names of attributes References: Message-ID: On Wed, 30 Dec 2015 23:50:03 +1100, Chris Angelico wrote: > On Wed, Dec 30, 2015 at 11:40 PM, Charles T. Smith > wrote: >> Oh! >> >> Although the referenced doc says: >> >> "For compatibility reasons, classes are still old-style by default." >> >> is it true that dictionaries are by default always new-style objects? >> >> (PDB)c6 = { "abc" : 123, "def" : 456} >> >> (PDB)isinstance (c6, dict) >> True >> >> (PDB)isinstance (c6, object) >> True > > I believe that's true, yes. The meaning of "by default" there is that > "class X: pass" will make an old-style class. All built-in types are now > new-style classes. > > ChrisA Okay, thank you. I'm trying to understand your program. Unfortunately, I haven't gotten the same output you had, using python 2.6 or 2.7. Maybe I haven't been able to restore the indentation correctly after having been filtered through pan(1). I wonder what the difference is between vars() and items() From rosuav at gmail.com Wed Dec 30 08:45:05 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 00:45:05 +1100 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On Thu, Dec 31, 2015 at 12:31 AM, Charles T. Smith wrote: > Okay, thank you. I'm trying to understand your program. > > Unfortunately, I haven't gotten the same output you had, using python 2.6 > or 2.7. Maybe I haven't been able to restore the indentation correctly > after having been filtered through pan(1). > > I wonder what the difference is between vars() and items() What I sent you was a log of interactive Python, so there are prompts and continuation prompts. Here's a script version of the same thing (running under CPython 2.7): class X: pass class Y(X): pass class Z(Y): pass X.x=1 Y.y=2 Z.z=3 inst=Z() inst.i=4 def class_vars(old_style_class): v = {} for cls in old_style_class.__bases__: v.update(class_vars(cls)) v.update(vars(old_style_class)) return v def all_vars(old_style_inst): v = class_vars(old_style_inst.__class__) v.update(vars(old_style_inst)) return v print(all_vars(inst)) # {'i': 4, '__module__': '__main__', 'y': 2, 'x': 1, 'z': 3, '__doc__': None} Does that work better? ChrisA From breamoreboy at yahoo.co.uk Wed Dec 30 09:10:14 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Dec 2015 14:10:14 +0000 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On 30/12/2015 11:51, Charles T. Smith wrote: > Hi, > > Does anyone know *why* the __members__ method was deprecated, to be > replaced by dir(), which doesn't tell the truth (if only it took an > optional parameter to say: "be truthful") https://bugs.python.org/issue456420 https://bugs.python.org/issue449989 -- 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 Wed Dec 30 09:16:32 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Dec 2015 14:16:32 +0000 Subject: how to get names of attributes In-Reply-To: References: Message-ID: On 30/12/2015 13:31, Charles T. Smith wrote: > > I wonder what the difference is between vars() and items() > Not much. From https://docs.python.org/3/library/functions.html#vars vars([object]) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a dictproxy to prevent direct dictionary updates). Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. -- 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 Dec 30 09:19:30 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 30 Dec 2015 16:19:30 +0200 Subject: Is it safe to assume floats always have a 53-bit mantissa? References: <5683d9aa$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87h9j03tot.fsf@elektro.pacujo.net> Steven D'Aprano : > Nevertheless, it's well known (in the sense that "everybody knows") > that Python floats are equivalent to C 64-bit IEEE-754 doubles. How > safe is that assumption? You'd need to have it in writing, wouldn't you? The only spec I know of promises no such thing: Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info. > As an optimization, I want to write: > > def func(n): > if n <= 2**53: > # use the floating point fast implementation > else: > # fall back on the slower, but exact, int algorithm > > [...] > > But I wonder whether I need to write this instead? > > def func(n): > if n <= 2**sys.float_info.mant_dig: > # ...float > else: > # ...int > > I don't suppose it really makes any difference performance-wise, but I > can't help but wonder if it is really necessary. If > sys.float_info.mant_dig is guaranteed to always be 53, why not just > write 53? Mainly because 2**sys.float_info.mant_dig looks much better than 2**53 Marko From tjreedy at udel.edu Wed Dec 30 09:35:29 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Dec 2015 09:35:29 -0500 Subject: Is it safe to assume floats always have a 53-bit mantissa? In-Reply-To: <5683d9aa$0$1618$c3e8da3$5496439d@news.astraweb.com> References: <5683d9aa$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 12/30/2015 8:18 AM, Steven D'Aprano wrote: > We know that Python floats are equivalent to C doubles, Yes > which are 64-bit IEEE-754 floating point numbers. I believe that this was not true on all systems when Python was first released. Not all 64-bit floats divided them the same way. I believe there has been some discussion on pydev whether the python code itself should assume IEEE now. I do not believe that there are currently any buildbots that are not IEEE. Does the standard allow exposing the 80 bit floats of FP processors? > Well, actually, C doubles are not strictly defined. The only promise the C > standard makes is that double is no smaller than float. (That's C float, > not Python float.) And of course, not all Python implementations use C. > > Nevertheless, it's well known (in the sense that "everybody knows") that > Python floats are equivalent to C 64-bit IEEE-754 doubles. How safe is that > assumption? > > I have a function with two implementations: a fast implementation that > converts an int to a float, does some processing, then converts it back to > int. That works fine so long as the int can be represented exactly as a > float. > > The other implementation uses integer maths only, and is much slower but > exact. > > As an optimization, I want to write: > > > def func(n): > if n <= 2**53: The magic number 53 should be explained in the code. > # use the floating point fast implementation > else: > # fall back on the slower, but exact, int algorithm > > > (The optimization makes a real difference: for large n, the float version is > about 500 times faster.) > > But I wonder whether I need to write this instead? > > def func(n): > if n <= 2**sys.float_info.mant_dig: > # ...float > else: > # ...int Pull the calculation of the constant out of the function. Naming the constant documents it and allows easy change. There is pretty standard in scientific computing (or was once). finmax = 2 ** sys.float_info.mant_dig # -1? def func(n): if n <= finmax: ... -- Terry Jan Reedy From cts.private.yahoo at gmail.com Wed Dec 30 09:40:28 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 14:40:28 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Thu, 31 Dec 2015 00:11:24 +1100, Chris Angelico wrote: > On Wed, Dec 30, 2015 at 11:57 PM, Charles T. Smith > wrote: >> Hello, >> >> I thought __getitem__() was invoked when an object is postfixed with an >> expression in brackets: >> >> - abc[n] >> >> and __getattr__() was invoked when an object is postfixed with an dot: >> >> - abc.member > > That would be normal (with the caveat that __getattr__ is called only if > the attribute isn't found; __getattribute__ is called unconditionally). > >> but my __getitem__ is being invoked at this time, where there's no >> subscript (going into a spiral recursion death): >> >> self.mcc = self.attrs.mcc >> >> Can anybody explain to me why __getitem__() would be invoked here? > > Can you post your entire class, or at least __getattr__? Also check > superclasses, if there are any. > > ChrisA (PDB)isinstance (self.attrs, attrdict) True As is so often the case, in composing my answer to your question, I discovered a number of problems in my class (e.g. I was calling __getitem__() myself!), but I'm puzzled now how to proceed. I thought the way you avoid triggering __getattr__() from within that was to use self.__dict__[name] but that doesn't work: (PDB)p self.attrs.keys() ['mcc', 'abc'] (PDB)p self.attrs.__dict__['abc'] *** KeyError: KeyError('abc',) class attrdict(dict): def __init__ (self, name = None): if name: self.update (name) print "attrdict: instantiated: ", name # AutoVivification def __getattr__ (self, name): print "attrdict:av:__getattr__: entered for ", name #, " in ", self #if not name in self.__dict__.keys(): if not name in self.keys(): print "attrdict:av:__getattr__: autovivifying ", name #self.__dict__.__setitem__ (name, self.__class__()) #self.__setitem__ (name, self.__class__()) self.__setattr__ (name, self.__class__()) #return self.__getitem__(name) #return self.__dict__.__getitem__(name) return self.__getattribute__ (name) def __getitem__ (self, key): print "attrdict:av:__getitem__: entered for ", key #, " in ", self return self.__getitem__(key) def __getattr__deprecated (self, name): return self[name] def __setattr__(self, name, value): self[name] = value From cts.private.yahoo at gmail.com Wed Dec 30 09:50:54 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 14:50:54 -0000 (UTC) Subject: how to get names of attributes References: Message-ID: On Wed, 30 Dec 2015 14:10:14 +0000, Mark Lawrence wrote: > On 30/12/2015 11:51, Charles T. Smith wrote: >> Hi, >> >> Does anyone know *why* the __members__ method was deprecated, to be >> replaced by dir(), which doesn't tell the truth (if only it took an >> optional parameter to say: "be truthful") > > https://bugs.python.org/issue456420 > https://bugs.python.org/issue449989 Thank you, that was what I asked for, kinda. According to the experts, the reason that the __members__() method was deprecated is that it was an "ugly hack". *Why* it was an ugly hack wasn't made clear (to me), unfortunately. My other postings to this topic show, I think, why the ability to know what's available (in the way of attributes) is a good thing, as I try to figure out how to get at my attributes without triggering __getattr__(), which I'm implementing. From ian.g.kelly at gmail.com Wed Dec 30 10:35:57 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 30 Dec 2015 08:35:57 -0700 Subject: using __getitem()__ correctly In-Reply-To: References: Message-ID: On Dec 30, 2015 7:46 AM, "Charles T. Smith" wrote: > As is so often the case, in composing my answer to your question, I discovered > a number of problems in my class (e.g. I was calling __getitem__() myself!), but > I'm puzzled now how to proceed. I thought the way you avoid triggering __getattr__() > from within that was to use self.__dict__[name] but that doesn't work: > > (PDB)p self.attrs.keys() > ['mcc', 'abc'] > (PDB)p self.attrs.__dict__['abc'] > *** KeyError: KeyError('abc',) What leads you to believe that this is triggering a call to __getattr__? The KeyError probably just means that the key 'abc' wasn't found in the dict. > class attrdict(dict): > def __init__ (self, name = None): > if name: > self.update (name) > print "attrdict: instantiated: ", name > > # AutoVivification > def __getattr__ (self, name): > print "attrdict:av:__getattr__: entered for ", name #, " in ", self > #if not name in self.__dict__.keys(): > if not name in self.keys(): Use the "not in" operator, e.g. "if name not in self.keys()". > print "attrdict:av:__getattr__: autovivifying ", name > #self.__dict__.__setitem__ (name, self.__class__()) > #self.__setitem__ (name, self.__class__()) > self.__setattr__ (name, self.__class__()) No reason to explicitly call __setitem__ or __setattr__ here. I'd probably just do self[name] = self.__class__() > #return self.__getitem__(name) > #return self.__dict__.__getitem__(name) > return self.__getattribute__ (name) You shouldn't call __getattribute__ from __getattr__, because __getattr__ is called from __getattribute__, so this would cause an infinite loop. Based on the preceding, you probably want to return the value you just set in the dict, correct? So just return self[name]. From cts.private.yahoo at gmail.com Wed Dec 30 11:58:36 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 16:58:36 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Wed, 30 Dec 2015 08:35:57 -0700, Ian Kelly wrote: > On Dec 30, 2015 7:46 AM, "Charles T. Smith" > wrote: >> As is so often the case, in composing my answer to your question, I >> discovered a number of problems in my class (e.g. I was calling >> __getitem__() myself!), but I'm puzzled now how to proceed. I thought >> the way you avoid triggering __getattr__() from within that was to use >> self.__dict__[name] but that doesn't work: >> >> (PDB)p self.attrs.keys() >> ['mcc', 'abc'] >> (PDB)p self.attrs.__dict__['abc'] >> *** KeyError: KeyError('abc',) > > What leads you to believe that this is triggering a call to __getattr__? > The KeyError probably just means that the key 'abc' wasn't found in the > dict. I meant, it doesn't work because I'm not getting at the attribute Although keys() sees it, it's not in the __dict__ attribute of attrs. If it's not there, where is it? > print "attrdict:av:__getattr__: autovivifying ", name > #self.__dict__.__setitem__ (name, self.__class__()) > #self.__setitem__ (name, self.__class__()) self.__setattr__ > (name, self.__class__()) > > No reason to explicitly call __setitem__ or __setattr__ here. I'd > probably just do self[name] = self.__class__() The reason I used this is to avoid trigging the __setitem__() method: self.__setattr__(name, self.__class__()) which is invoked if I use the "self[name]" syntax. But that didn't work. Is it just impossible to get at attributes without going through either __getattr__() or __getitem__()? > Based on the preceding, you probably want to return the value you just > set in the dict, correct? So just return self[name]. The problem is that then triggers the __getitem__() method and I don't know how to get to the attributes without triggering __getattr__(). It's the interplay of the two that's killing me. In the example, if I have: self.mcc = self.attrs.mcc The crux: Then __getattr__() triggers for the mcc. If I try to use self.attrs['mcc'] to get it, then that triggers __getitem__(). Okay, if the key is not an int, I'll go and get it and return it... unfortunately that triggers __getattr__(), an infinite loop. I tried using: attrdict.__getattr__ (self, 'mcc') but that didn't help, of course. I also tried so, but I've got this wrong, somehow: super (attrdict, self).__getattr__ ('mcc') class attrdict(dict): def __init__ (self, name = None): if name: self.update (name) print "attrdict: instantiated: ", name # AutoVivification def __getattr__ (self, name): print "attrdict:av:__getattr__: entered for ", name if name not in self.keys(): print "attrdict:av:__getattr__: autovivifying ", name self[name] = self.__class__() return self[name] def __getitem__ (self, key): print "attrdict:av:__getitem__: entered for ", key if type (key) is int: # TODO: support slices return self.__getitem__(key) return attrdict.__getattr__(self, key) def __setattr__(self, name, value): self[name] = value From random832 at fastmail.com Wed Dec 30 12:04:43 2015 From: random832 at fastmail.com (Random832) Date: Wed, 30 Dec 2015 12:04:43 -0500 Subject: how to get names of attributes In-Reply-To: References: Message-ID: <1451495083.3899875.479298458.71309BB4@webmail.messagingengine.com> On Wed, Dec 30, 2015, at 07:50, Chris Angelico wrote: > I believe that's true, yes. The meaning of "by default" there is that > "class X: pass" will make an old-style class. All built-in types are > now new-style classes. To be clear, AFAIK, built-in types were never old-style classes - prior to the introduction of the new type system (i.e. in Python 2.1 and earlier) they were not classes, and afterwards they were immediately new-style classes. From princeudo52 at gmail.com Wed Dec 30 13:21:10 2015 From: princeudo52 at gmail.com (Won Chang) Date: Wed, 30 Dec 2015 10:21:10 -0800 (PST) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: i have these task which i believe i have done well to some level Create a function get_algorithm_result to implement the algorithm below 1- Get a list of numbers L1, L2, L3....LN as argument 2- Assume L1 is the largest, Largest = L1 3- Take next number Li from the list and do the following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last number from the list then 7- return Largest and come out 8- Else repeat same process starting from step 3 Create a function prime_number that does the following Takes as parameter an integer and Returns boolean value true if the value is prime or Returns boolean value false if the value is not prime so i came up with this code below def get_algorithm_result(my_list): if not any(not type(y) is int for y in my_list): largest = 0 for item in range(0,len(my_list)): if largest < my_list[item]: largest = my_list[item] return largest else: return(my_list[-1]) def prime_number(integer): if integer%2==0 and 2!=integer: return False else: return True get_algorithm_result([1, 78, 34, 12, 10, 3]) get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) prime_number(1) prime_number(78) prime_number(11) for the question above, there is a unittes which reads import unittest class AlgorithmTestCases(unittest.TestCase): def test_maximum_number_one(self): result = get_algorithm_result([1, 78, 34, 12, 10, 3]) self.assertEqual(result, 78, msg="Incorrect number") def test_maximum_number_two(self): result = get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) self.assertEqual(result, "zoo", msg="Incorrect number") def test_prime_number_one(self): result = prime_number(1) self.assertEqual(result, True, msg="Result is invalid") def test_prime_number_two(self): result = prime_number(78) self.assertEqual(result, False, msg="Result is invalid") def test_prime_number_three(self): result = prime_number(11) self.assertEqual(result, True, msg="Result is invalid") but once i run my code ,it returns error saying Test Spec Failed Your solution failed to pass all the tests what is actually wrong with my code? From carlos.barera at gmail.com Wed Dec 30 14:14:21 2015 From: carlos.barera at gmail.com (Carlos Barera) Date: Wed, 30 Dec 2015 21:14:21 +0200 Subject: subprocess check_output Message-ID: Hi, Trying to run a specific command (ibstat) installed in /usr/sbin on an Ubuntu 15.04 machine, using subprocess.check_output and getting "/bin/sh: /usr/sbin/ibstat: No such file or directory" I tried the following: - running the command providing full path - running with executable=bash - running with (['/bin/bash', '-c' , "/usr/sbin/ibstat"]) Nothing worked ... Any idea? -carlos From joel.goldstick at gmail.com Wed Dec 30 15:06:44 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 30 Dec 2015 15:06:44 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Wed, Dec 30, 2015 at 1:21 PM, Won Chang wrote: > > i have these task which i believe i have done well to some level > > Create a function get_algorithm_result to implement the algorithm below > > 1- Get a list of numbers L1, L2, L3....LN as argument 2- Assume L1 is the > largest, Largest = L1 3- Take next number Li from the list and do the > following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last > number from the list then 7- return Largest and come out 8- Else repeat > same process starting from step 3 > > Create a function prime_number that does the following Takes as parameter > an integer and Returns boolean value true if the value is prime or Returns > boolean value false if the value is not prime > > so i came up with this code below > > def get_algorithm_result(my_list): > if not any(not type(y) is int for y in my_list): > largest = 0 > for item in range(0,len(my_list)): > if largest < my_list[item]: > largest = my_list[item] > return largest > else: > > return(my_list[-1]) > > def prime_number(integer): > if integer%2==0 and 2!=integer: > return False > else: > return True > > get_algorithm_result([1, 78, 34, 12, 10, 3]) > get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) > prime_number(1) > prime_number(78) > prime_number(11) > for the question above, there is a unittes which reads > > import unittest > > class AlgorithmTestCases(unittest.TestCase): > def test_maximum_number_one(self): > result = get_algorithm_result([1, 78, 34, 12, 10, 3]) > self.assertEqual(result, 78, msg="Incorrect number") > > def test_maximum_number_two(self): > result = get_algorithm_result(["apples", "oranges", "mangoes", > "banana", "zoo"]) > self.assertEqual(result, "zoo", msg="Incorrect number") > > def test_prime_number_one(self): > result = prime_number(1) > self.assertEqual(result, True, msg="Result is invalid") > > def test_prime_number_two(self): > result = prime_number(78) > self.assertEqual(result, False, msg="Result is invalid") > > def test_prime_number_three(self): > result = prime_number(11) > self.assertEqual(result, True, msg="Result is invalid") > but once i run my code ,it returns error saying Test Spec Failed > > Your solution failed to pass all the tests > what is actually wrong with my code? > You need to copy and paste the complete results and or traceback. There is no string "Test Spec Failed" in anything you have shown > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From joel.goldstick at gmail.com Wed Dec 30 15:11:27 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 30 Dec 2015 15:11:27 -0500 Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " In-Reply-To: References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> Message-ID: On Wed, Dec 30, 2015 at 3:06 PM, Joel Goldstick wrote: > > > On Wed, Dec 30, 2015 at 1:21 PM, Won Chang wrote: > >> >> i have these task which i believe i have done well to some level >> >> Create a function get_algorithm_result to implement the algorithm below >> >> 1- Get a list of numbers L1, L2, L3....LN as argument 2- Assume L1 is the >> largest, Largest = L1 3- Take next number Li from the list and do the >> following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last >> number from the list then 7- return Largest and come out 8- Else repeat >> same process starting from step 3 >> >> Create a function prime_number that does the following Takes as parameter >> an integer and Returns boolean value true if the value is prime or Returns >> boolean value false if the value is not prime >> >> so i came up with this code below >> >> def get_algorithm_result(my_list): >> if not any(not type(y) is int for y in my_list): >> > Not sure what above line is trying to do? Check that item is int? That won't help with the case of strings in my_list > largest = 0 >> for item in range(0,len(my_list)): >> > The above line can be more pythonically expressed as for item in my_list: if largest < item: largest = item return largest Then below is gone. Not sure what the else clause below is for > if largest < my_list[item]: >> largest = my_list[item] >> return largest >> else: >> >> return(my_list[-1]) >> >> def prime_number(integer): >> if integer%2==0 and 2!=integer: >> return False >> else: >> return True >> >> get_algorithm_result([1, 78, 34, 12, 10, 3]) >> get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) >> prime_number(1) >> prime_number(78) >> prime_number(11) >> for the question above, there is a unittes which reads >> >> import unittest >> >> class AlgorithmTestCases(unittest.TestCase): >> def test_maximum_number_one(self): >> result = get_algorithm_result([1, 78, 34, 12, 10, 3]) >> self.assertEqual(result, 78, msg="Incorrect number") >> >> def test_maximum_number_two(self): >> result = get_algorithm_result(["apples", "oranges", "mangoes", >> "banana", "zoo"]) >> self.assertEqual(result, "zoo", msg="Incorrect number") >> >> def test_prime_number_one(self): >> result = prime_number(1) >> self.assertEqual(result, True, msg="Result is invalid") >> >> def test_prime_number_two(self): >> result = prime_number(78) >> self.assertEqual(result, False, msg="Result is invalid") >> >> def test_prime_number_three(self): >> result = prime_number(11) >> self.assertEqual(result, True, msg="Result is invalid") >> but once i run my code ,it returns error saying Test Spec Failed >> >> Your solution failed to pass all the tests >> what is actually wrong with my code? >> > > You need to copy and paste the complete results and or traceback. There > is no string "Test Spec Failed" in anything you have shown > >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Joel Goldstick > http://joelgoldstick.com/stats/birthdays > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From joel.goldstick at gmail.com Wed Dec 30 15:13:37 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 30 Dec 2015 15:13:37 -0500 Subject: PEAK-Rules package. In-Reply-To: <1fa318c3-787b-4b63-91c2-27a4eefb42be@googlegroups.com> References: <1fa318c3-787b-4b63-91c2-27a4eefb42be@googlegroups.com> Message-ID: On Wed, Dec 30, 2015 at 8:24 AM, Radhika Grover wrote: > Hi, > > I don't see any package available under > https://pypi.python.org/simple/PEAK-Rules/. Could you please let me know > if it has seen a change recently. > > I need PEAK-Rules>=0.5a1.dev-r2600 using easy_install default behavior. > Any help is appreciated. Thanks in advance! > > - Radhika > -- > https://mail.python.org/mailman/listinfo/python-list > https://pypi.python.org/pypi/PEAK-Rules maybe? -- Joel Goldstick http://joelgoldstick.com/stats/birthdays From v+python at g.nevcal.com Wed Dec 30 15:35:11 2015 From: v+python at g.nevcal.com (Glenn Linderman) Date: Wed, 30 Dec 2015 12:35:11 -0800 Subject: EOFError: marshal data too short -- causes? In-Reply-To: <20151229085625.036f548d@imp> References: <56822D4F.8070309@g.nevcal.com> <56823DBC.9010205@g.nevcal.com> <20151229085625.036f548d@imp> Message-ID: <56843FFF.7070209@g.nevcal.com> On 12/29/2015 5:56 AM, D'Arcy J.M. Cain wrote: > On Tue, 29 Dec 2015 00:01:00 -0800 > Glenn Linderman wrote: >> OK, so I actually renamed it instead of zapping it. Them, actually, > Really, just zap them. They are object code. Even if you zap a > perfectly good .pyc file a perfectly good one will be re-created as > soon as you import it. No need to clutter up you file system. > Yes, the only value would be if the type of corruption could be determined from the content. From ian.g.kelly at gmail.com Wed Dec 30 15:40:44 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 30 Dec 2015 13:40:44 -0700 Subject: using __getitem()__ correctly In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith wrote: > On Wed, 30 Dec 2015 08:35:57 -0700, Ian Kelly wrote: > >> On Dec 30, 2015 7:46 AM, "Charles T. Smith" >> wrote: >>> As is so often the case, in composing my answer to your question, I >>> discovered a number of problems in my class (e.g. I was calling >>> __getitem__() myself!), but I'm puzzled now how to proceed. I thought >>> the way you avoid triggering __getattr__() from within that was to use >>> self.__dict__[name] but that doesn't work: >>> >>> (PDB)p self.attrs.keys() >>> ['mcc', 'abc'] >>> (PDB)p self.attrs.__dict__['abc'] >>> *** KeyError: KeyError('abc',) >> >> What leads you to believe that this is triggering a call to __getattr__? >> The KeyError probably just means that the key 'abc' wasn't found in the >> dict. > > > I meant, it doesn't work because I'm not getting at the attribute Although keys() > sees it, it's not in the __dict__ attribute of attrs. If it's not there, where is it? I think you're probably getting confused because there are three different dicts at play here: * Since your attrdict class inherits from dict, self.attrs is a dict. * self.attrs.__dict__ is a *different* dict, used to store the instance attributes of self.attrs. * self.attrs.__class__.__dict__ is another different dict, used to store the class attributes of attrdict. The keys method that you're calling above is a method of the self.attrs dict, which is where your attrdict's __setattr__ is setting it. That's why you find it there but not in self.attrs.__dict__. >> print "attrdict:av:__getattr__: autovivifying ", name >> #self.__dict__.__setitem__ (name, self.__class__()) >> #self.__setitem__ (name, self.__class__()) self.__setattr__ >> (name, self.__class__()) >> >> No reason to explicitly call __setitem__ or __setattr__ here. I'd >> probably just do self[name] = self.__class__() > > > The reason I used this is to avoid trigging the __setitem__() method: > > self.__setattr__(name, self.__class__()) > > which is invoked if I use the "self[name]" syntax. But that didn't work. But the body of your __setattr__ method is just "self[name] = self.__class__()", which is the exact same code as what I suggested and will still invoke __setitem__. That said, I don't get why you're trying to avoid calling __setitem__. If you're trying to store the attribute as a dict item, as you seem to be doing, why shouldn't that dict's __setitem__ be involved? > Is it just impossible to get at attributes without going through either > __getattr__() or __getitem__()? No. >> Based on the preceding, you probably want to return the value you just >> set in the dict, correct? So just return self[name]. > > > The problem is that then triggers the __getitem__() method and I don't > know how to get to the attributes without triggering __getattr__(). > > It's the interplay of the two that's killing me. The only interplay of the two is what you have written into your class. > In the example, if I have: > > self.mcc = self.attrs.mcc > > > The crux: > > Then __getattr__() triggers for the mcc. If I try to use self.attrs['mcc'] > to get it, then that triggers __getitem__(). Okay, if the key is not an int, > I'll go and get it and return it... unfortunately that triggers __getattr__(), > an infinite loop. How precisely are you trying to store these: as an attribute, or as a dict item? If it's supposed to be in the dict, then why is your __getitem__ trying to look up an attribute to begin with? > class attrdict(dict): > def __init__ (self, name = None): > if name: > self.update (name) > print "attrdict: instantiated: ", name > > # AutoVivification > def __getattr__ (self, name): > print "attrdict:av:__getattr__: entered for ", name > if name not in self.keys(): > print "attrdict:av:__getattr__: autovivifying ", name > self[name] = self.__class__() > return self[name] > > def __getitem__ (self, key): > print "attrdict:av:__getitem__: entered for ", key > if type (key) is int: # TODO: support slices > return self.__getitem__(key) Here the method as written is just going to end up calling itself. You probably want super(attrdict, self).__getitem__(key) > return attrdict.__getattr__(self, key) And here if you really want to access the instance attributes without using __getattr__, just use self.__dict__[key]. I don't understand what it is that you're trying to accomplish here by looking the key up in the instance attributes, though. It looks very circular. I think you should clearly define where you expect the items to be stored and then only check that location. From v+python at g.nevcal.com Wed Dec 30 15:43:06 2015 From: v+python at g.nevcal.com (Glenn Linderman) Date: Wed, 30 Dec 2015 12:43:06 -0800 Subject: EOFError: marshal data too short -- causes? In-Reply-To: References: <56822D4F.8070309@g.nevcal.com> <56823DBC.9010205@g.nevcal.com> Message-ID: <568441DA.9000107@g.nevcal.com> On 12/29/2015 1:00 PM, Terry Reedy wrote: > I updated to 2.7.11, 3.4.4, and 3.5.1 a couple of weeks ago, so the > timestamps are all fresh. So I don't know what happened with 3.4.3 > timestamps from last April and whether Windows itself touches the > files. I just tried importing a few and Python did not. I'm a Windows user, too, generally, but the web host runs Linux. I suppose, since the install does the compileall, that I could set all the __pycache__ files to read-only, even for "owner". Like you said, those files _can't_ be updated without Admin/root permission when it is a root install... so there would be no need, once compileall has been done, for the files to be updated until patches would be applied. This isn't a root install, though, but a "user" install. Level1 support at the web host claims they never touch user files unless the user calls and asks them to help with something that requires it. And maybe Level1 support religiously follows that policy, but other files have changed, so that policy doesn't appear to be universally applied for all personnel there... so the answer isn't really responsive to the question, but the tech I talked to was as much a parrot as a tech... Glenn From cs at zip.com.au Wed Dec 30 16:02:27 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 31 Dec 2015 08:02:27 +1100 Subject: subprocess check_output In-Reply-To: References: Message-ID: <20151230210227.GA88234@cskk.homeip.net> On 30Dec2015 21:14, Carlos Barera wrote: >Trying to run a specific command (ibstat) installed in /usr/sbin on an >Ubuntu 15.04 machine, using subprocess.check_output and getting "/bin/sh: >/usr/sbin/ibstat: No such file or directory" > >I tried the following: >- running the command providing full path >- running with executable=bash >- running with (['/bin/bash', '-c' , "/usr/sbin/ibstat"]) > >Nothing worked ... The first check is to run the command from a shell. Does it work? Does "which ibstat" confirm that the command exist at that path? Is it even installed? If it does, you should be able to run it directly without using a shell: subprocess.call(['/usr/sbin/ibstat'], ...) or just plain ['ibstat']. Also remember that using "sh -c blah" or "bash -c blah" is subject to all the same security issues that subprocess' "shell=True" parameter is, and that it should be avoided without special reason. Finally, remember to drop the common Linux fetish with "bash". Just use "sh"; on many systems it _is_ bash, but it will provide portable use. The bash is just a partiular Bourne style shell, not installed everywhere, and rarely of any special benefit for scripts over the system /bin/sh (which _every_ UNIX system has). If none of this solves your problem, please reply including the failing code and a transcript of the failure output. Thanks, Cameron Simpson From rosuav at gmail.com Wed Dec 30 17:26:40 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 09:26:40 +1100 Subject: how to get names of attributes In-Reply-To: <1451495083.3899875.479298458.71309BB4@webmail.messagingengine.com> References: <1451495083.3899875.479298458.71309BB4@webmail.messagingengine.com> Message-ID: On Thu, Dec 31, 2015 at 4:04 AM, Random832 wrote: > On Wed, Dec 30, 2015, at 07:50, Chris Angelico wrote: >> I believe that's true, yes. The meaning of "by default" there is that >> "class X: pass" will make an old-style class. All built-in types are >> now new-style classes. > > To be clear, AFAIK, built-in types were never old-style classes - prior > to the introduction of the new type system (i.e. in Python 2.1 and > earlier) they were not classes, and afterwards they were immediately > new-style classes. > -- > https://mail.python.org/mailman/listinfo/python-list Thanks Random. I wasn't actively using Python until about 2.5ish, and wasn't following python-dev until even more recently, so I didn't keep track of all that. And frankly, old-style classes have just been something I avoid whereever possible. ChrisA From rosuav at gmail.com Wed Dec 30 17:32:48 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 09:32:48 +1100 Subject: subprocess check_output In-Reply-To: <20151230210227.GA88234@cskk.homeip.net> References: <20151230210227.GA88234@cskk.homeip.net> Message-ID: On Thu, Dec 31, 2015 at 8:02 AM, Cameron Simpson wrote: > On 30Dec2015 21:14, Carlos Barera wrote: >> >> Trying to run a specific command (ibstat) installed in /usr/sbin on an >> Ubuntu 15.04 machine, using subprocess.check_output and getting "/bin/sh: >> /usr/sbin/ibstat: No such file or directory" >> >> I tried the following: >> - running the command providing full path >> - running with executable=bash >> - running with (['/bin/bash', '-c' , "/usr/sbin/ibstat"]) >> >> Nothing worked ... > > > The first check is to run the command from a shell. Does it work? Does > "which ibstat" confirm that the command exist at that path? Is it even > installed? And do those checks as the same user as your script runs as, with the same environment and all. You might find that a file is executable for one user but not for another, or something. ChrisA From otaksoftspamtrap at gmail.com Wed Dec 30 17:46:48 2015 From: otaksoftspamtrap at gmail.com (otaksoftspamtrap at gmail.com) Date: Wed, 30 Dec 2015 14:46:48 -0800 (PST) Subject: Newbie: How to convert a tuple of strings into a tuple of ints Message-ID: How do I get from here t = ('1024', '1280') to t = (1024, 1280) Thanks for all help! From rosuav at gmail.com Wed Dec 30 17:52:41 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 09:52:41 +1100 Subject: Newbie: How to convert a tuple of strings into a tuple of ints In-Reply-To: References: Message-ID: On Thu, Dec 31, 2015 at 9:46 AM, wrote: > How do I get from here > > t = ('1024', '1280') > > to > > t = (1024, 1280) > > > Thanks for all help! t = (int(t[0]), int(t[1])) If the situation is more general than that, post your actual code and we can help out more. Working with a single line isn't particularly easy. :) ChrisA From cts.private.yahoo at gmail.com Wed Dec 30 17:54:44 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 22:54:44 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Wed, 30 Dec 2015 13:40:44 -0700, Ian Kelly wrote: > On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith >> The problem is that then triggers the __getitem__() method and I don't >> know how to get to the attributes without triggering __getattr__(). >> >> It's the interplay of the two that's killing me. > > The only interplay of the two is what you have written into your class. > >> In the example, if I have: >> >> self.mcc = self.attrs.mcc >> >> >> The crux: >> >> Then __getattr__() triggers for the mcc. If I try to use >> self.attrs['mcc'] to get it, then that triggers __getitem__(). Okay, >> if the key is not an int, I'll go and get it and return it... >> unfortunately that triggers __getattr__(), an infinite loop. > > How precisely are you trying to store these: as an attribute, or as a > dict item? If it's supposed to be in the dict, then why is your > __getitem__ trying to look up an attribute to begin with? I don't understand this distinction between an "attribute" and a "dict item". attrdict is a stupid legacy class that inherits from a dictionary. I think the intent was to be faster than a normal class, but I doubt there's any value to that. In any case, I thought that class attributes were, in fact, items of __dict__? The reason that my __getitem__() is trying to look up an attribute is, I think, because this syntax triggers __getitem__ with a key of "mcc": return self[name] Is that assumption wrong? That was the reason I was looking to find another way to get at the attributes, because return self.__getattr__(name) does, too, and this doesn't even find them: return self.__getattribute__(name) Just to establish the concept, this horrible thing is showing some promise: attriter = self.iteritems() for attr in attriter: if attr[0] == name: return attr[1] (because the subscripts there are on a tuple type) But I concede I must be doing something fundamentally wrong because this assert is triggering: def __getattr__ (self, name): print "attrdict:av:__getattr__: entered for ", name assert name not in self.keys(), "attrdict:__getattr__: who lied?" From ben+python at benfinney.id.au Wed Dec 30 17:57:22 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 09:57:22 +1100 Subject: Newbie: How to convert a tuple of strings into a tuple of ints References: Message-ID: <85wprvtui5.fsf@benfinney.id.au> otaksoftspamtrap at gmail.com writes: > How do I get from here > > t = ('1024', '1280') > > to > > t = (1024, 1280) Both of those are assignment statements, so I'm not sure what you mean by ?get from ? to?. To translate one assignment statement to a different assignment statement, re-write the statement. But I think you want to produce a new sequence from an existing sequence. The ?map? built-in function is useful for that:: sequence_of_numbers_as_text = ['1024', '1280'] sequence_of_integers = map(int, sequence_of_numbers_as_text) That sequence can then be iterated. Another (more broadly useful) way is to use a generator expression:: sequence_of_integers = (int(item) for item in sequence_of_numbers_as_text) If you really want a tuple, just pass that sequence to the ?tuple? callable:: tuple_of_integers = tuple( int(item) for item in sequence_of_numbers_as_text) or:: tuple_of_integers = tuple(map(int, sequence_of_numbers_as_text)) -- \ ?Nothing is more sacred than the facts.? ?Sam Harris, _The End | `\ of Faith_, 2004 | _o__) | Ben Finney From cts.private.yahoo at gmail.com Wed Dec 30 17:58:51 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 22:58:51 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Wed, 30 Dec 2015 22:54:44 +0000, Charles T. Smith wrote: > But I concede I must be doing something fundamentally wrong because this > assert is triggering: > def __getattr__ (self, name): > print "attrdict:av:__getattr__: entered for ", name > assert name not in self.keys(), "attrdict:__getattr__: who lied?" Tt's really a hassle how pan(1) sometimes wraps and sometimes doesn't. Is there a better way to do this? From ian.g.kelly at gmail.com Wed Dec 30 18:00:29 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 30 Dec 2015 16:00:29 -0700 Subject: Newbie: How to convert a tuple of strings into a tuple of ints In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 3:46 PM, wrote: > How do I get from here > > t = ('1024', '1280') > > to > > t = (1024, 1280) Deja vu: https://mail.python.org/pipermail/python-list/2015-December/701017.html From otaksoftspamtrap at gmail.com Wed Dec 30 18:00:29 2015 From: otaksoftspamtrap at gmail.com (otaksoftspamtrap at gmail.com) Date: Wed, 30 Dec 2015 15:00:29 -0800 (PST) Subject: Newbie: How to convert a tuple of strings into a tuple of ints In-Reply-To: References: Message-ID: <720808ec-ef8d-44b3-ae93-3a730b8d0922@googlegroups.com> Thanks much - both solutions work well for me On Wednesday, December 30, 2015 at 2:57:50 PM UTC-8, Ben Finney wrote: > kierkegaard at gmail.com writes: > > > How do I get from here > > > > t = ('1024', '1280') > > > > to > > > > t = (1024, 1280) > > Both of those are assignment statements, so I'm not sure what you mean > by "get from ... to". To translate one assignment statement to a different > assignment statement, re-write the statement. > > > But I think you want to produce a new sequence from an existing sequence. > > The 'map' built-in function is useful for that:: > > sequence_of_numbers_as_text = ['1024', '1280'] > sequence_of_integers = map(int, sequence_of_numbers_as_text) > > That sequence can then be iterated. > > Another (more broadly useful) way is to use a generator expression:: > > sequence_of_integers = (int(item) for item in sequence_of_numbers_as_text) > > > If you really want a tuple, just pass that sequence to the 'tuple' > callable:: > > tuple_of_integers = tuple( > int(item) for item in sequence_of_numbers_as_text) > > or:: > > tuple_of_integers = tuple(map(int, sequence_of_numbers_as_text)) > > -- > \ "Nothing is more sacred than the facts." --Sam Harris, _The End | > `\ of Faith_, 2004 | > _o__) | > Ben Finney From ben+python at benfinney.id.au Wed Dec 30 18:13:53 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 10:13:53 +1100 Subject: using __getitem()__ correctly References: Message-ID: <85k2nvttqm.fsf@benfinney.id.au> "Charles T. Smith" writes: > I don't understand this distinction between an "attribute" and a "dict > item". When did you most recently work through the Python tutorial > You may want to work through it again, from start to finish and exercising each example, to be sure you have a solid understanding of basic concepts like these. In brief: Objects have attributes; looking up an attribute on an object has specific syntax. Dictionaries are collections of items; the items are looked up by key, using a quite different syntax. Those two different syntaxes translate to distinct special methods. You may be familiar with other languages where the distinction between ?attribute of an object? is not distinct from ?item in a dictionary?. Python is not one of those languages; the distinction is real and important. You'll need to do some remedial learning of Python, and I recommend working through the Python tutorial. -- \ ?But it is permissible to make a judgment after you have | `\ examined the evidence. In some circles it is even encouraged.? | _o__) ?Carl Sagan, _The Burden of Skepticism_, 1987 | Ben Finney From cts.private.yahoo at gmail.com Wed Dec 30 18:18:58 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Wed, 30 Dec 2015 23:18:58 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Thu, 31 Dec 2015 10:13:53 +1100, Ben Finney wrote: > "Charles T. Smith" writes: > >> I don't understand this distinction between an "attribute" and a "dict >> item". > > When did you most recently work through the Python tutorial > > You may want to work through > it again, from start to finish and exercising each example, to be sure > you have a solid understanding of basic concepts like these. > > In brief: Objects have attributes; looking up an attribute on an object > has specific syntax. Dictionaries are collections of items; the items > are looked up by key, using a quite different syntax. Those two > different syntaxes translate to distinct special methods. > > You may be familiar with other languages where the distinction between > ?attribute of an object? is not distinct from ?item in a dictionary?. > Python is not one of those languages; the distinction is real and > important. You'll need to do some remedial learning of Python, and I > recommend working through the Python tutorial. Thanks, Ben, for your advice. Actually, I think that Ian and Chris and I are making fine progress. I think you misread my question. From steve at pearwood.info Wed Dec 30 18:50:53 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 10:50:53 +1100 Subject: using __getitem()__ correctly References: Message-ID: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 10:13 am, Ben Finney wrote: > You may be familiar with other languages where the distinction between > ?attribute of an object? is not distinct from ?item in a dictionary?. > Python is not one of those languages; the distinction is real and > important. I'm not sure what distinction you're referring to, can you explain? Obviously there is a syntax difference between x.attr and x['key'], but attributes *are* items in a dictionary (ignoring __slots__ and __getattr__ for the time being). Either the instance __dict__, the class __dict__, or a superclass __dict__. -- Steven From steve at pearwood.info Wed Dec 30 18:58:17 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 10:58:17 +1100 Subject: how to get names of attributes References: Message-ID: <56846f9b$0$1586$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Dec 2015 10:51 pm, Charles T. Smith wrote: > Hi, > > How can I get *all* the names of an object's attributes? In the most general case, you cannot. Classes can define a __getattr__ method (and a __getattribute__ method, for new-style classes only) which implement dynamic attributes. These can be *extremely* dynamic and impossible to predict ahead of time. Starting from the simplest cases to the most horrible: def __getattr__(self, name): if name == "spam": return 1 elif name == self._attribute_name: return 2 elif name == some_function(10, 20, 30): return 3 elif name.lower() in ("x", "y") or name.startswith("foo"): return 4 elif 1626740500 <= hash(name) <= 1626740600: return 5 elif name == "surprise" and random.random() < 0.5: return 6 raise AttributeError So you can see that even in principle, there is no way for the Python interpreter to look inside the __getattr__ method and determine what attributes exist. Fortunately, there's a way around that: you can customise the list of attribute names returned by dir(): py> class X: ... def __dir__(self): ... return dir(X) + ["a", "b"] ... def spam(self): ... pass ... py> x = X() py> dir(x) ['__dir__', '__doc__', '__module__', 'a', 'b', 'spam'] So if you have dynamic attributes generated by __getattr__, the polite thing to do is to return their names from __dir__. > I have legacy > code with mixed new style classes and old style classes and I need to > write methods which deal with both. That's the immediate problem, but > I'm always running into the need to understand how objects are linked, in > particular when in pdb. The answers one always sees on StackOverflow is > that you don't need to understand, understanding is not the pythonic way > to do things. That's why I don't think much of the majority of StackOverflow answers. > Alternatively, is there are map documented somewhere - more complete than > python/python-2.7.3-docs-html/library/stdtypes.html? > highlight=class#special-attributes > > Or, is the code available uncompiled somewhere on my machine? That depends on how you installed Python. If you installed it from source, then it will be, unless you deleted it after compiling. But it is easy enough to get the Python source code: https://www.python.org/downloads/source/ https://docs.python.org/devguide/setup.html#checkout https://hg.python.org/cpython/file/tip > Does anyone know *why* the __members__ method was deprecated, to be > replaced by dir(), which doesn't tell the truth (if only it took an > optional parameter to say: "be truthful") dir() is intentionally meant for use in the interactive interpreter, to return "interesting" attributes. It isn't really intended for programmatic use. For that, you might wish to write your own version of dir(). Here is some pseudo-code: def mydir(obj): if type(obj) defines __dir__, return the output of __dir__ names = set() if obj is an instance: if obj has __slots__, then add each slot to names; try: add each key from vars(obj) to names; except TypeError: # no instance __dict__ pass call mydir(type(obj)) and add the names it returns to names; else obj must be a class or type: add each key from vars(obj) to names; if obj is an old-style class: do the same for each class in obj.__bases__; else obj must be a new-style class: do the same for each class in obj.__mro__ return sorted(names) But I expect that the differences between this and what the built-in dir() return will be minimal, and only attributes which are part of the machinery used to get classes themselves working, not part of your class or instance. -- Steven From steve at pearwood.info Wed Dec 30 19:09:27 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 11:09:27 +1100 Subject: raise None Message-ID: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> I have a lot of functions that perform the same argument checking each time: def spam(a, b): if condition(a) or condition(b): raise TypeError if other_condition(a) or something_else(b): raise ValueError if whatever(a): raise SomethingError ... def eggs(a, b): if condition(a) or condition(b): raise TypeError if other_condition(a) or something_else(b): raise ValueError if whatever(a): raise SomethingError ... Since the code is repeated, I naturally pull it out into a function: def _validate(a, b): if condition(a) or condition(b): raise TypeError if other_condition(a) or something_else(b): raise ValueError if whatever(a): raise SomethingError def spam(a, b): _validate(a, b) ... def eggs(a, b): _validate(a, b) ... But when the argument checking fails, the traceback shows the error occurring in _validate, not eggs or spam. (Naturally, since that is where the exception is raised.) That makes the traceback more confusing than it need be. So I can change the raise to return in the _validate function: def _validate(a, b): if condition(a) or condition(b): return TypeError if other_condition(a) or something_else(b): return ValueError if whatever(a): return SomethingError and then write spam and eggs like this: def spam(a, b): ex = _validate(a, b) if ex is not None: raise ex ... It's not much of a gain though. I save an irrelevant level in the traceback, but only at the cost of an extra line of code everywhere I call the argument checking function. But suppose we allowed "raise None" to do nothing. Then I could rename _validate to _if_error and write this: def spam(a, b): raise _if_error(a, b) ... and have the benefits of "Don't Repeat Yourself" without the unnecessary, and misleading, extra level in the traceback. Obviously this doesn't work now, since raise None is an error, but if it did work, what do you think? -- Steven From no.email at nospam.invalid Wed Dec 30 19:19:54 2015 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 30 Dec 2015 16:19:54 -0800 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87d1tnxydx.fsf@jester.gateway.pace.com> Steven D'Aprano writes: > def _validate(a, b): > if condition(a) or condition(b): return TypeError > ... > Obviously this doesn't work now, since raise None is an error, but if it did > work, what do you think? Never occurred to me. But in some analogous situations I've caught the exception inside _validate, then peeled away some layers of the traceback from the exception output before throwing again. From ben+python at benfinney.id.au Wed Dec 30 19:21:59 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 11:21:59 +1100 Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85fuyjtql4.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 31 Dec 2015 10:13 am, Ben Finney wrote: > > > You may be familiar with other languages where the distinction > > between ?attribute of an object? is not distinct from ?item in a > > dictionary?. Python is not one of those languages; the distinction > > is real and important. > > I'm not sure what distinction you're referring to, can you explain? Tersely: the relationship between an object and its attributes, is not the same as the relationship between a dictionary and its items. > Obviously there is a syntax difference between x.attr and x['key'] Not merely syntax; the attributes of an object are not generally available as items of the container. > but attributes *are* items in a dictionary That's like saying everything in Python is a number: it conflates the implementation with the semantics. The distinction between a Python integer and a Python boolean value is real and important, despite the incidental fact of their both being implemented as numbers. > Either the instance __dict__, the class __dict__, or a superclass > __dict__. No, I'm not referring to the ?__dict__? attribute of an object; I'm referring to the object itself. To talk about the attributes of an object ?foo? is distinct from talking about the items in a dictionary ?foo?. That distinction is real, and important. -- \ ?? correct code is great, code that crashes could use | `\ improvement, but incorrect code that doesn?t crash is a | _o__) horrible nightmare.? ?Chris Smith, 2008-08-22 | Ben Finney From ben+python at benfinney.id.au Wed Dec 30 19:26:14 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 11:26:14 +1100 Subject: Validation in Python (was: raise None) References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85bn97tqe1.fsf@benfinney.id.au> Steven D'Aprano writes: > I have a lot of functions that perform the same argument checking each > time: Not an answer to the question you ask, but: Have you tried the data validation library ?voluptuous?? Voluptuous, despite the name, is a Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc. It has three goals: Simplicity. Support for complex data structures. Provide useful error messages. Seems like a good way to follow Don't Repeat Yourself in code that needs a lot of validation of inputs. -- \ ?It's my belief we developed language because of our deep inner | `\ need to complain.? ?Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From ian.g.kelly at gmail.com Wed Dec 30 19:31:11 2015 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 30 Dec 2015 17:31:11 -0700 Subject: using __getitem()__ correctly In-Reply-To: References: Message-ID: On Wed, Dec 30, 2015 at 3:54 PM, Charles T. Smith wrote: > On Wed, 30 Dec 2015 13:40:44 -0700, Ian Kelly wrote: > >> On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith >>> The problem is that then triggers the __getitem__() method and I don't >>> know how to get to the attributes without triggering __getattr__(). >>> >>> It's the interplay of the two that's killing me. >> >> The only interplay of the two is what you have written into your class. >> >>> In the example, if I have: >>> >>> self.mcc = self.attrs.mcc >>> >>> >>> The crux: >>> >>> Then __getattr__() triggers for the mcc. If I try to use >>> self.attrs['mcc'] to get it, then that triggers __getitem__(). Okay, >>> if the key is not an int, I'll go and get it and return it... >>> unfortunately that triggers __getattr__(), an infinite loop. >> >> How precisely are you trying to store these: as an attribute, or as a >> dict item? If it's supposed to be in the dict, then why is your >> __getitem__ trying to look up an attribute to begin with? > > > > I don't understand this distinction between an "attribute" and a "dict item". > attrdict is a stupid legacy class that inherits from a dictionary. I think > the intent was to be faster than a normal class, but I doubt there's any value > to that. > > In any case, I thought that class attributes were, in fact, items of __dict__? That's correct, but as I said in my previous message, self.attrs and self.attrs.__dict__ are two different dicts, and you're confusing one for the other. Maybe this will be illuminating: >>> class mydict(dict): pass ... >>> md = mydict() >>> md['foo'] = 42 # Set an item in md >>> md['foo'] # 'foo' exists as an item 42 >>> md.foo # but not as an attribute Traceback (most recent call last): File "", line 1, in AttributeError: 'mydict' object has no attribute 'foo' >>> md.__dict__['foo'] # and it's not in md.__dict__ Traceback (most recent call last): File "", line 1, in KeyError: 'foo' >>> md.bar = 43 # Set an attribute on md >>> md.bar # 'bar' exists as an attribute 43 >>> md.__dict__['bar'] # and it's in md.__dict__ 43 >>> md['bar'] # but it's not in md itself Traceback (most recent call last): File "", line 1, in KeyError: 'bar' And to hopefully drive the point home: >>> md.items() [('foo', 42)] >>> md.__dict__.items() [('bar', 43)] > The reason that my __getitem__() is trying to look up an attribute is, I > think, because this syntax triggers __getitem__ with a key of "mcc": > > return self[name] > > Is that assumption wrong? That assumption is correct, but this still doesn't explain to me why you want __getitem__ to be looking up attributes, i.e. looking in self.__dict__ when the expectation is that it would just look in self. Is the goal here that self.foo and self['foo'] are the same thing? If so, then you shouldn't need to worry about __getitem__ and __setitem__ at all. Just override your __getattr__ and __setattr__ to store attributes in self instead of self.__dict__. > Just to establish the concept, this horrible thing is showing some promise: > > attriter = self.iteritems() > for attr in attriter: > if attr[0] == name: > return attr[1] This is equivalent to but slower than "return self.get(name)". What method is this in and what's the rest of the code? It's hard to analyze your code in any helpful way when you keep changing it. > (because the subscripts there are on a tuple type) I don't know what this has to do with anything. > But I concede I must be doing something fundamentally wrong because this > assert is triggering: > def __getattr__ (self, name): > print "attrdict:av:__getattr__: entered for ", name > assert name not in self.keys(), "attrdict:__getattr__: who lied?" When does this trigger? What's calling it? What name is passed in? From rosuav at gmail.com Wed Dec 30 19:38:12 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 11:38:12 +1100 Subject: raise None In-Reply-To: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Dec 31, 2015 at 11:09 AM, Steven D'Aprano wrote: > I have a lot of functions that perform the same argument checking each time: > > def spam(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > def eggs(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > > Since the code is repeated, I naturally pull it out into a function: > > def _validate(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > > def spam(a, b): > _validate(a, b) > ... > > def eggs(a, b): > _validate(a, b) > ... > > > But when the argument checking fails, the traceback shows the error > occurring in _validate, not eggs or spam. (Naturally, since that is where > the exception is raised.) That makes the traceback more confusing than it > need be. If the validation really is the same in all of them, then is it a problem to see the validation function in the traceback? Its purpose isn't simply "raise an exception", but "validate a specific set of inputs". That sounds like a perfectly reasonable traceback line to me (imagine if your validation function has a bug). ChrisA From steve at pearwood.info Wed Dec 30 20:26:00 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 12:26:00 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 11:38 am, Chris Angelico wrote: > On Thu, Dec 31, 2015 at 11:09 AM, Steven D'Aprano > wrote: >> I have a lot of functions that perform the same argument checking each >> time: >> >> def spam(a, b): >> if condition(a) or condition(b): raise TypeError >> if other_condition(a) or something_else(b): raise ValueError >> if whatever(a): raise SomethingError >> ... >> >> def eggs(a, b): >> if condition(a) or condition(b): raise TypeError >> if other_condition(a) or something_else(b): raise ValueError >> if whatever(a): raise SomethingError >> ... >> >> >> Since the code is repeated, I naturally pull it out into a function: >> >> def _validate(a, b): >> if condition(a) or condition(b): raise TypeError >> if other_condition(a) or something_else(b): raise ValueError >> if whatever(a): raise SomethingError >> >> def spam(a, b): >> _validate(a, b) >> ... >> >> def eggs(a, b): >> _validate(a, b) >> ... >> >> >> But when the argument checking fails, the traceback shows the error >> occurring in _validate, not eggs or spam. (Naturally, since that is where >> the exception is raised.) That makes the traceback more confusing than it >> need be. > > If the validation really is the same in all of them, then is it a > problem to see the validation function in the traceback? Its purpose > isn't simply "raise an exception", but "validate a specific set of > inputs". That sounds like a perfectly reasonable traceback line to me > (imagine if your validation function has a bug). Right -- that's *exactly* why it is harmful that the _validate function shows up in the traceback. If _validate itself has a bug, then it will raise, and you will see the traceback: Traceback (most recent call last): File "spam", line 19, in this File "spam", line 29, in that File "spam", line 39, in other File "spam", line 5, in _validate ThingyError: ... which tells you that _validate raised an exception and therefore has a bug. Whereas if _validate does what it is supposed to do, and is working correctly, you will see: Traceback (most recent call last): File "spam", line 19, in this File "spam", line 29, in that File "spam", line 39, in other File "spam", line 5, in _validate ThingyError: ... and the reader has to understand the internal workings of _validate sufficiently to infer that this exception is not a bug in _validate but an expected failure mode of other when you pass a bad argument. Now obviously one can do that. It's often not even very hard: most bugs are obviously bugs, and the ThingyError will surely come with a descriptive error message like "Argument out of range" in the second case. In the case where _validate *returns* the exception instead of raising it, and the calling function (in this case other) raises, you see this in the case of a bug in _validate: Traceback (most recent call last): File "spam", line 19, in this File "spam", line 29, in that File "spam", line 39, in other File "spam", line 5, in _validate ThingyError: ... and this is the case of a bad argument to other: Traceback (most recent call last): File "spam", line 19, in this File "spam", line 29, in that File "spam", line 39, in other ThingyError: ... I think this is a win for debuggability. (Is that a word?) But it's a bit annoying to do it today, since you have to save the return result and explicitly compare it to None. If "raise None" was a no-op, it would feel more natural to just say raise _validate() and trust that if _validate falls out the end and returns None, the raise will be a no-op. -- Steven From ben+python at benfinney.id.au Wed Dec 30 20:44:01 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 12:44:01 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: <857fjvtmse.fsf@benfinney.id.au> Steven D'Aprano writes: > Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other > File "spam", line 5, in _validate > ThingyError: ... > > and the reader has to understand the internal workings of _validate > sufficiently to infer that this exception is not a bug in _validate > but an expected failure mode of other when you pass a bad argument. This point seems to advocate for suppressing *any* code that deliberately raises an exception. Is that your intent? -- \ ?I don't want to live peacefully with difficult realities, and | `\ I see no virtue in savoring excuses for avoiding a search for | _o__) real answers.? ?Paul Z. Myers, 2009-09-12 | Ben Finney From rosuav at gmail.com Wed Dec 30 21:12:37 2015 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Dec 2015 13:12:37 +1100 Subject: raise None In-Reply-To: <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Dec 31, 2015 at 12:26 PM, Steven D'Aprano wrote: > Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other > ThingyError: ... > > > I think this is a win for debuggability. (Is that a word?) But it's a bit > annoying to do it today, since you have to save the return result and > explicitly compare it to None. If "raise None" was a no-op, it would feel > more natural to just say raise _validate() and trust that if _validate > falls out the end and returns None, the raise will be a no-op. (Yes, it is.) Gotcha. So here's an alternative possibility. Instead of raising None doing nothing, what you really want is to have _validate signal an error with one less level of traceback - that is, you want it to raise an exception from the calling function. class remove_traceback_level: def __enter__(self): return self def __exit__(self, type, value, traceback): if type is None: return tb = traceback while tb.tb_next: tb = tb.tb_next tb.tb_next = None raise value from traceback def _validate(a, b): with remove_traceback_level(): if condition(a) or condition(b): raise TypeError if other_condition(a) or something_else(b): raise ValueError if whatever(a): raise SomethingError The trouble is that this doesn't actually work, because tb_next is read-only. But is there something along these lines that would make a function raise exceptions as if it were in another function? ChrisA From toledoivanor at gmail.com Wed Dec 30 21:53:51 2015 From: toledoivanor at gmail.com (ivanor toledo) Date: Thu, 31 Dec 2015 00:53:51 -0200 Subject: Error 0x80070570 Message-ID: Good evening! I am trying to install Python , however is me presenting Error 0x80070570 saying that the folder or file is corrupted or unreadable. is attached the log file with the aforementioned error , already realized some procedures did not work .. procedures such as error correction, defragment files .. How can I resolve this error ? thanks Ivanor From steve at pearwood.info Wed Dec 30 22:51:22 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 14:51:22 +1100 Subject: Stupid Python tricks Message-ID: <5684a63b$0$1595$c3e8da3$5496439d@news.astraweb.com> Stolen^W Inspired from a post by Tim Peters back in 2001: https://mail.python.org/pipermail/python-dev/2001-January/011911.html Suppose you have a huge string, and you want to quote it. Here's the obvious way: mystring = "spam"*100000 result = '"' + mystring + '"' But that potentially involves a lot of copying. How fast is it? Using Jython2.5, I get these results on my computer: jy> from timeit import Timer jy> t = Timer("""'"' + mystring + '"'""", 'mystring = "spam"*100000') jy> min(t.repeat(number=1000)) 2.4110000133514404 Perhaps % interpolation is faster? jy> t = Timer("""'"%s"' % mystring""", 'mystring = "spam"*100000') jy> min(t.repeat(number=1000)) 2.9660000801086426 Ouch, that's actually worse. But now we have the Stupid Python Trick: result = mystring.join('""') How fast is this? jy> t = Timer("""mystring.join('""')""", 'mystring = "spam"*100000') jy> min(t.repeat(number=1000)) 2.171999931335449 That's Jython, which is not known for its speed. (If you want speed in Jython, you ought to be calling Java libraries.) Here are some results using Python 3.3: py> from timeit import Timer py> t = Timer("""'"' + mystring + '"'""", 'mystring = "spam"*100000') py> min(t.repeat(number=1000)) 0.22504080459475517 Using % interpolation and the format method: py> t = Timer("""'"{}"'.format(mystring)""", 'mystring = "spam"*100000') py> min(t.repeat(number=1000)) 0.4634905573911965 py> t = Timer("""'"%s"' % mystring""", 'mystring = "spam"*100000') py> min(t.repeat(number=1000)) 0.474040764849633 And the Stupid Python Trick: py> t = Timer("""mystring.join('""')""", 'mystring = "spam"*100000') py> min(t.repeat(number=1000)) 0.19407050590962172 Fifteen years later, and Tim Peters' Stupid Python Trick is still the undisputed champion! -- Steven From tjreedy at udel.edu Wed Dec 30 23:00:16 2015 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Dec 2015 23:00:16 -0500 Subject: raise None In-Reply-To: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 12/30/2015 7:09 PM, Steven D'Aprano wrote: > I have a lot of functions that perform the same argument checking each time: > > def spam(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > def eggs(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > > Since the code is repeated, I naturally pull it out into a function: > > def _validate(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > > def spam(a, b): > _validate(a, b) > ... > > def eggs(a, b): > _validate(a, b) > ... > > > But when the argument checking fails, the traceback shows the error > occurring in _validate, not eggs or spam. (Naturally, since that is where > the exception is raised.) That makes the traceback more confusing than it > need be. > > So I can change the raise to return in the _validate function: > > def _validate(a, b): > if condition(a) or condition(b): return TypeError > if other_condition(a) or something_else(b): return ValueError > if whatever(a): return SomethingError > > > and then write spam and eggs like this: > > def spam(a, b): > ex = _validate(a, b) > if ex is not None: raise ex > ... > > > It's not much of a gain though. I save an irrelevant level in the traceback, > but only at the cost of an extra line of code everywhere I call the > argument checking function. It is nicer than the similar standard idiom try: _validate(a, b) except Exception as e: raise e from None If you could compute a reduced traceback, by copying one, then this might work (based on Chris' idea. def _validate(a, b): ex = None if condition(a) or condition(b): ex = TypeError elif other_condition(a) or something_else(b): ex = ValueError elif whatever(a): ex = SomethingError if ex: try: 1/0 except ZeroDivisionError as err: tb = err.__traceback__ tb = raise ex.with_traceback(tb) > But suppose we allowed "raise None" to do nothing. Then I could rename > _validate to _if_error and write this: > > def spam(a, b): > raise _if_error(a, b) > ... > > > and have the benefits of "Don't Repeat Yourself" without the unnecessary, > and misleading, extra level in the traceback. > > Obviously this doesn't work now, since raise None is an error, but if it did > work, what do you think? Perhaps a bit too magical, but maybe not. -- Terry Jan Reedy From cs at zip.com.au Wed Dec 30 23:03:20 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 31 Dec 2015 15:03:20 +1100 Subject: raise None In-Reply-To: <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> References: <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20151231040320.GA6597@cskk.homeip.net> On 31Dec2015 12:26, Steven D'Aprano wrote: >On Thu, 31 Dec 2015 11:38 am, Chris Angelico wrote: >>> [... functions calling common _validate function ...] >>> But when the argument checking fails, the traceback shows the error >>> occurring in _validate, not eggs or spam. (Naturally, since that is where >>> the exception is raised.) That makes the traceback more confusing than it >>> need be. >> >> If the validation really is the same in all of them, then is it a >> problem to see the validation function in the traceback? Its purpose >> isn't simply "raise an exception", but "validate a specific set of >> inputs". That sounds like a perfectly reasonable traceback line to me >> (imagine if your validation function has a bug). > >Right -- that's *exactly* why it is harmful that the _validate function >shows up in the traceback. I think I'm still disagreeing, but only on this point of distinguishing _validate bug exceptions from _validate test failures. >If _validate itself has a bug, then it will raise, and you will see the >traceback: > >Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other > File "spam", line 5, in _validate >ThingyError: ... > >which tells you that _validate raised an exception and therefore has a bug. Ok.... >Whereas if _validate does what it is supposed to do, and is working >correctly, you will see: > >Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other > File "spam", line 5, in _validate >ThingyError: ... > >and the reader has to understand the internal workings of _validate >sufficiently to infer that this exception is not a bug in _validate but an >expected failure mode of other when you pass a bad argument. Would it not be useful then to name the including function in the exception text? >In the case where _validate *returns* the exception instead of raising it, >and the calling function (in this case other) raises, you see this in the >case of a bug in _validate: > >Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other > File "spam", line 5, in _validate >ThingyError: ... > >and this is the case of a bad argument to other: > >Traceback (most recent call last): > File "spam", line 19, in this > File "spam", line 29, in that > File "spam", line 39, in other >ThingyError: ... I confess that when I want to check several things I would like to return several failure indications. So thing on that line, how about this: for blam in _validate(a, b): raise blam which leaves you open to gatheroing them all up instead of aborting on the first complaint. >I think this is a win for debuggability. (Is that a word?) But it's a bit >annoying to do it today, since you have to save the return result and >explicitly compare it to None. If "raise None" was a no-op, it would feel >more natural to just say raise _validate() and trust that if _validate >falls out the end and returns None, the raise will be a no-op. This is a nice idea though. Succinct and expressive, though people would have to learn that: raise foo() does not unconditionally abort at this point. Cheers, Cameron Simpson From steve at pearwood.info Wed Dec 30 23:07:53 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 15:07:53 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 12:44 pm, Ben Finney wrote: > Steven D'Aprano writes: > >> Traceback (most recent call last): >> File "spam", line 19, in this >> File "spam", line 29, in that >> File "spam", line 39, in other >> File "spam", line 5, in _validate >> ThingyError: ... >> >> and the reader has to understand the internal workings of _validate >> sufficiently to infer that this exception is not a bug in _validate >> but an expected failure mode of other when you pass a bad argument. > > This point seems to advocate for suppressing *any* code that > deliberately raises an exception. Is that your intent? No. The issue isn't that an exception is deliberately raised. The issue is that it is deliberately raised in a function separate from where the exception conceptually belongs. The exception is conceptually part of function "other", and was only refactored into a separate function _validate to avoid repeating the same validation code in multiple places. It is a mere implementation detail that the exception is actually raised inside _validate rather than other. As an implementation detail, exposing it to the user (in the form of a line in the stacktrace) doesn't help debugging. At best it is neutral (the user reads the error message and immediately realises that the problem lies with bad arguments passed to other, and _validate has nothing to do with it). At worst it actively misleads the user into thinking that there is a bug in _validate. -- Steven From rantingrickjohnson at gmail.com Thu Dec 31 00:02:19 2015 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Wed, 30 Dec 2015 21:02:19 -0800 (PST) Subject: Stupid Python tricks In-Reply-To: <5684a63b$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <5684a63b$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wednesday, December 30, 2015 at 9:51:48 PM UTC-6, Steven D'Aprano wrote: > Fifteen years later, and Tim Peters' Stupid Python Trick is still the > undisputed champion! And should we be happy about that revelation, or sad? From steve at pearwood.info Thu Dec 31 00:12:43 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 16:12:43 +1100 Subject: raise None References: <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5684b94d$0$1586$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 03:03 pm, Cameron Simpson wrote: [...] Steven D'Aprano (that's me) wrote this: >>Whereas if _validate does what it is supposed to do, and is working >>correctly, you will see: >> >>Traceback (most recent call last): >> File "spam", line 19, in this >> File "spam", line 29, in that >> File "spam", line 39, in other >> File "spam", line 5, in _validate >>ThingyError: ... >> >>and the reader has to understand the internal workings of _validate >>sufficiently to infer that this exception is not a bug in _validate but an >>expected failure mode of other when you pass a bad argument. > > Would it not be useful then to name the including function in the > exception text? You mean change the signature of _validate to: def _validate(a, b, name_of_caller): ... and have function "other" call it like this: def other(arg1, arg2): _validate(arg1, arg2, "other") # if we reach this line, the arguments were validated # and we can continue ... I think that's pretty horrible. I'm not sure whether that would be more, or less, horrible than having _validate automagically determine the caller's name by looking in the call stack. [...] > I confess that when I want to check several things I would like to return > several failure indications. So thing on that line, how about this: > > for blam in _validate(a, b): > raise blam > > which leaves you open to gatheroing them all up instead of aborting on the > first complaint. Are you sure? I would have expected that raising the first exception would exit the loop. >>I think this is a win for debuggability. (Is that a word?) But it's a bit >>annoying to do it today, since you have to save the return result and >>explicitly compare it to None. If "raise None" was a no-op, it would feel >>more natural to just say raise _validate() and trust that if _validate >>falls out the end and returns None, the raise will be a no-op. > > This is a nice idea though. Succinct and expressive, though people would > have to learn that: > > raise foo() > > does not unconditionally abort at this point. Yes, that crossed my mind. Maybe if there was a second keyword: raiseif foo() which only raised if foo() returned a non-None value. That's kind of like the "or die" idiom from Perl, I guess. But of course requiring a second keyword will almost certainly doom this proposal -- it is only of benefit at the margins as it is. -- Steven From cs at zip.com.au Thu Dec 31 00:45:03 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 31 Dec 2015 16:45:03 +1100 Subject: raise None In-Reply-To: <5684b94d$0$1586$c3e8da3$5496439d@news.astraweb.com> References: <5684b94d$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20151231054503.GA60695@cskk.homeip.net> On 31Dec2015 16:12, Steven D'Aprano wrote: >On Thu, 31 Dec 2015 03:03 pm, Cameron Simpson wrote: >Steven D'Aprano (that's me) wrote this: >>>Whereas if _validate does what it is supposed to do, and is working >>>correctly, you will see: >>> >>>Traceback (most recent call last): >>> File "spam", line 19, in this >>> File "spam", line 29, in that >>> File "spam", line 39, in other >>> File "spam", line 5, in _validate >>>ThingyError: ... >>> >>>and the reader has to understand the internal workings of _validate >>>sufficiently to infer that this exception is not a bug in _validate but an >>>expected failure mode of other when you pass a bad argument. >> >> Would it not be useful then to name the including function in the >> exception text? > >You mean change the signature of _validate to: > >def _validate(a, b, name_of_caller): > ... > >and have function "other" call it like this: > >def other(arg1, arg2): > _validate(arg1, arg2, "other") > # if we reach this line, the arguments were validated > # and we can continue > ... > >I think that's pretty horrible. I'm not sure whether that would be more, or >less, horrible than having _validate automagically determine the caller's >name by looking in the call stack. No, I meant your latter suggestion above: consult the call stack to fish out the calling function name. Something like: from cs.py.stack import caller ... def _validate(...): frame = caller() funcname = frame.functionname and then use funcname in the messages, or greater detail. Caller() is available here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/py/stack.py?fileviewer=file-view-default for the fiddliness. The horribleness is at least concealed, unless you're nesting _validate implementations. >> I confess that when I want to check several things I would like to return >> several failure indications. So thing on that line, how about this: >> >> for blam in _validate(a, b): >> raise blam >> >> which leaves you open to gatheroing them all up instead of aborting on the >> first complaint. > >Are you sure? I would have expected that raising the first exception would >exit the loop. In the bare form, surely, just like your "if". But in principle you could gather all the exceptions together and raise a new exception with details attached. >>>I think this is a win for debuggability. (Is that a word?) But it's a bit >>>annoying to do it today, since you have to save the return result and >>>explicitly compare it to None. If "raise None" was a no-op, it would feel >>>more natural to just say raise _validate() and trust that if _validate >>>falls out the end and returns None, the raise will be a no-op. >> >> This is a nice idea though. Succinct and expressive, though people would >> have to learn that: >> >> raise foo() >> >> does not unconditionally abort at this point. > >Yes, that crossed my mind. Maybe if there was a second keyword: > > raiseif foo() > >which only raised if foo() returned a non-None value. That's kind of like >the "or die" idiom from Perl, I guess. But of course requiring a second >keyword will almost certainly doom this proposal -- it is only of benefit >at the margins as it is. I'd rather your original myself: plain "raise". Another keyword seems a reach, and I don't like it. And I don't like "raiseif"; I've got a bunch of "blahif" functions of similar flavour and I'm stuff unhappy with their names. I think it is a small thing to learn, especially as "raise None" is already an error. Cheers, Cameron Simpson From steve at pearwood.info Thu Dec 31 01:09:29 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Dec 2015 17:09:29 +1100 Subject: Stupid Python tricks References: <5684a63b$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5684c69a$0$1589$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 04:02 pm, Rick Johnson wrote: > On Wednesday, December 30, 2015 at 9:51:48 PM UTC-6, Steven D'Aprano > wrote: >> Fifteen years later, and Tim Peters' Stupid Python Trick is still the >> undisputed champion! > > And should we be happy about that revelation, or sad? Yes! -- Steven From ankur.cse at gmail.com Thu Dec 31 02:18:09 2015 From: ankur.cse at gmail.com (Ankur Agrawal) Date: Thu, 31 Dec 2015 07:18:09 +0000 Subject: fabric.network.disconnect_all() Message-ID: hi team, I am not sure that disconnect_all() works correctly for task marked as @parallel Following is code snippet - @parallel def diagnoseTransaction(): with hide('stdout', 'stderr'): output = run(command) main.py: execute(diagnoseTransaction,hosts=hosts_transaction) disconnect_all() In the console I see all the commands ran but I never saw 'Disconnecting message' in the console. While if I remove @parallel decorator and then if I run the same code then I do see 'Disconnecting messages' in the console. Am I missing something or ? Thanks, Ankur From rdhkgrvr1 at gmail.com Thu Dec 31 02:23:09 2015 From: rdhkgrvr1 at gmail.com (Radhika Grover) Date: Thu, 31 Dec 2015 12:53:09 +0530 Subject: PEAK-Rules package. In-Reply-To: References: <1fa318c3-787b-4b63-91c2-27a4eefb42be@googlegroups.com> Message-ID: Hi, Thanks for the reply! I do see different revisions of PEAK-Rules listed on - http://peak.telecommunity.com/snapshots/. However, earlier as part our product installation PEAK-Rules>=0.5a1.dev-r2600 dependency was being fulfilled using easy_install default behavior. So, I think https://pypi.python.org/simple/PEAK-Rules/ had the right package available earlier. Could you please let me know if the above link has been changed. - Radhika On Thu, Dec 31, 2015 at 1:43 AM, Joel Goldstick wrote: > > > On Wed, Dec 30, 2015 at 8:24 AM, Radhika Grover > wrote: > >> Hi, >> >> I don't see any package available under >> https://pypi.python.org/simple/PEAK-Rules/. Could you please let me know >> if it has seen a change recently. >> >> I need PEAK-Rules>=0.5a1.dev-r2600 using easy_install default behavior. >> Any help is appreciated. Thanks in advance! >> >> - Radhika >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > https://pypi.python.org/pypi/PEAK-Rules maybe? > > -- > Joel Goldstick > http://joelgoldstick.com/stats/birthdays > From cts.private.yahoo at gmail.com Thu Dec 31 05:46:43 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Thu, 31 Dec 2015 10:46:43 -0000 (UTC) Subject: how to get names of attributes References: <56846f9b$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 31 Dec 2015 10:58:17 +1100, Steven D'Aprano wrote: (some very good information) Thank you. From cts.private.yahoo at gmail.com Thu Dec 31 06:17:31 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Thu, 31 Dec 2015 11:17:31 -0000 (UTC) Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 31 Dec 2015 10:50:53 +1100, Steven D'Aprano wrote: > I'm not sure what distinction you're referring to, can you explain? Ian Kelly had said: >> How precisely are you trying to store these: as an attribute, or as a >> dict item? If it's supposed to be in the dict, then why is your >> __getitem__ trying to look up an attribute to begin with? to which I answered: >> In any case, I thought that class attributes were, in fact, items of >>__dict__? > > Obviously there is a syntax difference between x.attr and x['key'], but > attributes *are* items in a dictionary (ignoring __slots__ and > __getattr__ for the time being). Either the instance __dict__, the class > __dict__, or a superclass __dict__. That was my understanding but I wasn't sure what Ian meant when he went on to say: >> If it's supposed to be in the dict, then why is your __getitem__ >> trying to look up an attribute to begin with? Which raises the question of where they would be if not in a dictionary. This brings up a fundamental unclarity of mine: an object has attributes, one of which is __dict__, which has attributes. - how does one access the attributes in e.g. self - where do I find the attribute 'mcc' by cruising around in pdb, given the objs below? (PDB)pp dir (self) ['__class__', '__cmp__', ... '__dict__', ... '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] (PDB)pp dir (self.__dict__) ['__class__', '__cmp__', ... '__delitem__', '__doc__', ... '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] (PDB)pp (self.keys()) ['mcc'] It was recommended that I use the obj[name] syntax in __getattr__() but that then invoked __getitem__(), complicating the matter. To be specific, if an attribute is not available, I want to assume it's a graph node and create it. If the attribute has an index, I want to create and access an array of those nodes. It seems to fall perfectly within the definition of __getattr__() and __getitem__(), but I suspect that slight programming errors (i.e. mine) are hiding the proper functionality of these methods. Thanks everybody, for your help so far, and hopefully you can me pointed in the right direction. Happy New Year! cts From cts.private.yahoo at gmail.com Thu Dec 31 06:30:21 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Thu, 31 Dec 2015 11:30:21 -0000 (UTC) Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 31 Dec 2015 11:21:59 +1100, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 31 Dec 2015 10:13 am, Ben Finney wrote: >> >> > You may be familiar with other languages where the distinction >> > between ?attribute of an object? is not distinct from ?item in a >> > dictionary?. Python is not one of those languages; the distinction is >> > real and important. ... > > Tersely: the relationship between an object and its attributes, is not > the same as the relationship between a dictionary and its items. I understand this to mean that the relationship between a dictionary and its items is less complex than the relationship between an object and its attributes. I'd like to catalog the different attribute types/implications: - perhaps a hierarchy of meta-ism - or user-relevance - those things in the __dict__ - those things not in the __dict__ but without the "__" - ??? > >> Obviously there is a syntax difference between x.attr and x['key'] > > Not merely syntax; the attributes of an object are not generally > available as items of the container. What are the set of ways that an attribute is accessible? Including implementation implications? > >> Either the instance __dict__, the class __dict__, or a superclass >> __dict__. > > No, I'm not referring to the ?__dict__? attribute of an object; I'm > referring to the object itself. > > To talk about the attributes of an object ?foo? is distinct from talking > about the items in a dictionary ?foo?. That distinction is real, and > important. But wanting to deal with the attributes of an object without considering the way it's implemented - although possible - requires a complete virtual model that covers all implications. It's easier to simply understand how the objects work under the covers. From ben+python at benfinney.id.au Thu Dec 31 06:51:47 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Dec 2015 22:51:47 +1100 Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85vb7esung.fsf@benfinney.id.au> "Charles T. Smith" writes: > On Thu, 31 Dec 2015 11:21:59 +1100, Ben Finney wrote: > > > Tersely: the relationship between an object and its attributes, is > > not the same as the relationship between a dictionary and its items. > > I understand this to mean that the relationship between a dictionary > and its items is less complex than the relationship between an object > and its attributes. That's not implied by the above, nor is it what I meant. I meant that the relationship is not the same. * The attributes of an object ?foo? are what you access via ?foo.bar? syntax. You don't access those attributes via ?foo[bar]?. * The items of a dictionary ?foo? are what you access via ?foo[bar]? syntax. You don't access those items via ?foo.bar?. That's an important, and real, difference. And it's much better learned as part of a comprehensive course on Python, not in a deep dive into the magic methods. I really don't know why it's been so difficult to talk about this, but I hope my meaning is clear now. Have a wonderful end of year, folks. -- \ ?There are no chaplains in foxholes.? ?Sergeant Justin | `\ Griffith, 2011-07-27 | _o__) | Ben Finney From oscar.j.benjamin at gmail.com Thu Dec 31 07:12:43 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Dec 2015 12:12:43 +0000 Subject: using __getitem()__ correctly In-Reply-To: References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31 December 2015 at 11:30, Charles T. Smith wrote: >>> Obviously there is a syntax difference between x.attr and x['key'] >> >> Not merely syntax; the attributes of an object are not generally >> available as items of the container. > > > What are the set of ways that an attribute is accessible? Including > implementation implications? > > >> >>> Either the instance __dict__, the class __dict__, or a superclass >>> __dict__. >> >> No, I'm not referring to the ?__dict__? attribute of an object; I'm >> referring to the object itself. >> >> To talk about the attributes of an object ?foo? is distinct from talking >> about the items in a dictionary ?foo?. That distinction is real, and >> important. > > > But wanting to deal with the attributes of an object without considering > the way it's implemented - although possible - requires a complete virtual > model that covers all implications. It's easier to simply understand how the > objects work under the covers. When you write x.attr the name 'attr' is looked up on the object x. This calls x.__getattribute__('attr'). In turn this checks the dict associated with the object x i.e. x.__dict__['attr']. This in turn calls x.__dict__.__getitem__('attr'). The lookup of x.__dict__ is special and doesn't use the normal __getattribute__ mechanism (otherwise this would be an infinite recursion). Generally special attributes (with double underscores) are looked up in a different way. If x.__dict__ does not have the attribute then the dict associated with the class/type of x is checked i.e. x.__class__.__dict__['attr']. The lookup of x.__class__ is also special. Failing this the other classes in x.__class__.__mro__ are checked i.e. x.__class__.__mro__[1].__dict__['attr']. Once these are exhausted x.__getattribute__('attr') falls back on calling x.__getattr__('attr'). IIUC you're trying to create an attribute dict where the same attributes can be looked up via x.attr or x['attr'] (i.e. x.__getattribute__('attr') or x.__getitem__('attr')). One way to do this is to subclass dict and then set each instances __dict__ to be itself. This way __getattribute__ will search the instance (which is a dict subclass) as its own attribute dict. You can then use __getattr__ as the fallback for attributes that are not found. A simple implementation of this could look like: class attrdict(dict): def __init__(self, name=None): self.__dict__ = self kwargs = {'name':name} if name is not None else {} super(attrdict, self).__init__(**kwargs) def __getattr__(self, attrname): ob = self[attrname] = type(self)(name=attrname) return ob >>> d = attrdict('foo') >>> d {'name': 'foo'} >>> d.bar {'name': 'bar'} >>> d {'bar': {'name': 'bar'}, 'name': 'foo'} The problem with this as with any dict subclass approach is that a dict has a load of methods (.items() .keys() .pop() ...) that will now become conflated with your dict keys when you use the attribute access: >>> d.items This means that you can't use any of the dict method names in whatever you're doing. This is the reason that a dict uses a different mechanism __getitem__ so that it can store arbitrary keys at the same time as having named methods which must be attributes. Personally I think that the best approach is to ditch the idea of conflating attributes and keys and just use the subscript x['attr'] syntax. -- Oscar From oscar.j.benjamin at gmail.com Thu Dec 31 07:19:56 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Dec 2015 12:19:56 +0000 Subject: raise None In-Reply-To: <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31 December 2015 at 04:07, Steven D'Aprano wrote: > On Thu, 31 Dec 2015 12:44 pm, Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> Traceback (most recent call last): >>> File "spam", line 19, in this >>> File "spam", line 29, in that >>> File "spam", line 39, in other >>> File "spam", line 5, in _validate >>> ThingyError: ... >>> >>> and the reader has to understand the internal workings of _validate >>> sufficiently to infer that this exception is not a bug in _validate >>> but an expected failure mode of other when you pass a bad argument. >> >> This point seems to advocate for suppressing *any* code that >> deliberately raises an exception. Is that your intent? > > No. The issue isn't that an exception is deliberately raised. The issue is > that it is deliberately raised in a function separate from where the > exception conceptually belongs. The exception is conceptually part of > function "other", and was only refactored into a separate function > _validate to avoid repeating the same validation code in multiple places. > It is a mere implementation detail that the exception is actually raised > inside _validate rather than other. > > As an implementation detail, exposing it to the user (in the form of a line > in the stacktrace) doesn't help debugging. At best it is neutral (the user > reads the error message and immediately realises that the problem lies with > bad arguments passed to other, and _validate has nothing to do with it). At > worst it actively misleads the user into thinking that there is a bug in > _validate. You're overthinking this. It's fine for the error to come from _validate. Conceptually the real error is not in _validate or the function that calls _validate but in whatever function further up the stack trace created the wrong type of object to pass in. If the user can see the stack trace and work back to the point where they passed something in to your function then how does the extra level hurt? If it really bothers you then you can use a comment that will show up in the traceback output _validate(a, b) # Verify arguments to myfunc(a, b) but really I don't think it's a big deal. The traceback gives you useful information about where to look for an error/bug but it's still the programmer's job to interpret that, look at the code, and try to understand what they have done to cause the problem. -- Oscar From cts.private.yahoo at gmail.com Thu Dec 31 07:45:55 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Thu, 31 Dec 2015 12:45:55 -0000 (UTC) Subject: using __getitem()__ correctly References: Message-ID: On Wed, 30 Dec 2015 17:31:11 -0700, Ian Kelly wrote: >> In any case, I thought that class attributes were, in fact, items of >> __dict__? > > That's correct, but as I said in my previous message, self.attrs and > self.attrs.__dict__ are two different dicts, and you're confusing one > for the other. Maybe this will be illuminating: > >>>> class mydict(dict): pass > ... >>>> md = mydict() >>>> md['foo'] = 42 # Set an item in md >>>> md['foo'] # 'foo' exists as an item > 42 >>>> md.foo # but not as an attribute > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'mydict' object has no attribute 'foo' >>>> md.__dict__['foo'] # and it's not in md.__dict__ > Traceback (most recent call last): > File "", line 1, in > KeyError: 'foo' >>>> md.bar = 43 # Set an attribute on md md.bar # 'bar' exists as an >>>> attribute > 43 >>>> md.__dict__['bar'] # and it's in md.__dict__ > 43 >>>> md['bar'] # but it's not in md itself > Traceback (most recent call last): > File "", line 1, in > KeyError: 'bar' > > And to hopefully drive the point home: > >>>> md.items() > [('foo', 42)] >>>> md.__dict__.items() > [('bar', 43)] Okay, I think I got an important point that you said earlier but I didn't get the full ramifications thereof: class md (... more about this ...): pass md is a class that has an dictionary attribute __dict__: - md['level1'] puts attributes in md - md.level2 puts attributes in md.__dict__ is that correct? Now, as to the superclass, if that's, say, object, then it has two levels: md -> object (containing a dict) if the superclass is dict, then it only has one level: md -> dict I'll have to look at my methods again with those understandings. From cts.private.yahoo at gmail.com Thu Dec 31 08:39:30 2015 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Thu, 31 Dec 2015 13:39:30 -0000 (UTC) Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 31 Dec 2015 12:12:43 +0000, Oscar Benjamin wrote: > When you write x.attr the name 'attr' is looked up on the object x. This > calls x.__getattribute__('attr'). In turn this checks the dict > associated with the object x i.e. x.__dict__['attr']. This in turn calls > x.__dict__.__getitem__('attr'). The lookup of x.__dict__ is special and > doesn't use the normal __getattribute__ mechanism (otherwise this would > be an infinite recursion). Generally special attributes (with double > underscores) are looked up in a different way. If x.__dict__ does not > have the attribute then the dict associated with the class/type of x is > checked i.e. x.__class__.__dict__['attr']. The lookup of x.__class__ is > also special. Failing this the other classes in x.__class__.__mro__ are > checked i.e. x.__class__.__mro__[1].__dict__['attr']. Once these are > exhausted x.__getattribute__('attr') falls back on calling > x.__getattr__('attr'). Very good overview of the steps, thank you. ...> > The problem with this as with any dict subclass approach is that a dict > has a load of methods (.items() .keys() .pop() ...) that will now become > conflated with your dict keys when you use the attribute access: > >>>> d.items > Yeah, this makes it confusing, too. :) From steve at pearwood.info Thu Dec 31 09:43:25 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 01:43:25 +1100 Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56853f0e$0$1583$c3e8da3$5496439d@news.astraweb.com> Hmmm, you seem to be pasting in text from multiple messages, and jumping around in time ("Ian had said, to which I answered") which may get a bit confusing. Hopefully I can answer without getting lost :-) On Thu, 31 Dec 2015 10:17 pm, Charles T. Smith wrote: > On Thu, 31 Dec 2015 10:50:53 +1100, Steven D'Aprano wrote: > >> I'm not sure what distinction you're referring to, can you explain? I'm pretty sure I was directing that question to Ben, who has explained his position. > Ian Kelly had said: > >>> How precisely are you trying to store these: as an attribute, or as a >>> dict item? If it's supposed to be in the dict, then why is your >>> __getitem__ trying to look up an attribute to begin with? > > to which I answered: > >>> In any case, I thought that class attributes were, in fact, items of >>>__dict__? Ah, but *which* __dict__? There could be many. Let's put aside some of the technical details which add complexity, and consider just a simple case: we have an instance "x" of some class X, and we write "x.spam" to look up the attribute "spam". What happens? This is equivalent to the function call getattr(x, "spam"), which looks for an instance attribute, then a class attribute, then in each of the superclasses (if any). What does getattr do? We can imagine that it looks something like this simplified version: def getattr(obj, name): try: return obj.__dict__[name] except KeyError: for cls in type(obj).__mro__: try: return cls.__dict__[name] except KeyError: pass # Still here? raise AttributeError('not found') I've skipped a lot of detail -- calling of __getattribute__ and __getattr__ methods, the possibility of __slots__, the possibility that the instance doesn't have a __dict__, descriptors, the influence of the metaclass, differences between classic and new-style classes -- but the above shows the essentials: an attribute lookup may look in multiple dicts to find the attribute. The astute reader will notice that inside getattr() I'm doing an attribute lookup "obj.__dict__". How does that not trigger an endless series of recursive calls to getattr? The answer is that a handful of special attributes, including __dict__, are built into the structure of the object itself, not part of the __dict__, and so the Python interpreter can find them without looking in the dict. Don't worry about it -- it's not relevant except in the senses: (1) the problem of endless recursive calls to getattr() is solved; and (2) objects can have attributes which aren't actually stored in a dict, such as __dict__ itself, and __slots__, and probably others. What those attributes are is, I think, an implementation detail and irrelevant. So long as you use the existing mechanisms for doing lookups: x.spam getattr(x, "spam") it will just work. I wrote to Ben: >> Obviously there is a syntax difference between x.attr and x['key'], but >> attributes *are* items in a dictionary (ignoring __slots__ and >> __getattr__ for the time being). Either the instance __dict__, the class >> __dict__, or a superclass __dict__. > > > That was my understanding but I wasn't sure what Ian meant when he went on > to say: > >>> If it's supposed to be in the dict, then why is your __getitem__ >>> trying to look up an attribute to begin with? > > Which raises the question of where they would be if not in a dictionary. They could be created on the fly by __getattr__ or __getattribute__, they could be in a __slot__, or they could be a special attribute built into the object structure. But I don't think that is relevant to Ian's question. > This brings up a fundamental unclarity of mine: an object has attributes, > one of which is __dict__, which has attributes. > > - how does one access the attributes in e.g. self self.attribute_name getattr(self, "attribute_name") > - where do I find the attribute 'mcc' by cruising around in pdb, given > the objs below? What is the object "self" below? What makes you think that 'mcc' is an attribute? The evidence suggests that it is not. You write: dir(self) and the result does *not* include 'mcc', which is very strong evidence that 'mcc' is not an attribute. > (PDB)pp dir (self) [...] > 'clear', > 'copy', > 'fromkeys', > 'get', > 'has_key', etc. This suggests that "self" is a dict, or specifically a subclass of dict. So you would have: class MyDict(dict): ... x = MyDict() x.some_method() and then dropped into the debugger. Now you're looking at the instance x from inside one of the methods, where it is known as "self". Being a (subclass of a) dict, it has all the usual dict attributes, like methods clear, copy, etc., plus whatever extra attributes you give it. There is no evidence that you have given it any extra attributes. > (PDB)pp dir (self.__dict__) [...] > 'clear', > 'copy', > 'fromkeys', > 'get', > 'has_key', etc. Being an instance, x will usually have an instance dict. (There are exceptions, but this is not one of those cases.) You're looking at the attributes of that dict. Being a dict, it has all the usual dict attributes, like methods clear, copy, etc. > (PDB)pp (self.keys()) > ['mcc'] self is a dict, and dicts have keys:values. This particular dict has a single key, 'mcc'. That's not an attribute. What makes you think it is an attribute? > It was recommended that I use the obj[name] syntax in __getattr__() > but that then invoked __getitem__(), complicating the matter. It was recommended by whom? For what purpose? There's something which either you haven't told us, or I've missed. What are you trying to accomplish? > To be specific, if an attribute is not available, I want to assume > it's a graph node and create it. If the attribute has an index, > I want to create and access an array of those nodes. What's a graph node? Create it where? What do you mean by "attribute has an index"? Where are you creating "an array of those nodes"? What does any of this business got to do with self.__dict__? > It seems to fall perfectly within the definition of __getattr__() > and __getitem__(), but I suspect that slight programming errors > (i.e. mine) are hiding the proper functionality of these methods. I think you have gotten lost in the details and are over-complicating matters greatly. Can you start with a HIGH LEVEL overview of what this class is supposed to represent? It seems to be a subclass of dict. Why? -- Steven From steve at pearwood.info Thu Dec 31 10:03:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 02:03:20 +1100 Subject: using __getitem()__ correctly References: <56846ddf$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <568543b9$0$1590$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 10:30 pm, Charles T. Smith wrote: > On Thu, 31 Dec 2015 11:21:59 +1100, Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> On Thu, 31 Dec 2015 10:13 am, Ben Finney wrote: >>> >>> > You may be familiar with other languages where the distinction >>> > between ?attribute of an object? is not distinct from ?item in a >>> > dictionary?. Python is not one of those languages; the distinction is >>> > real and important. > ... >> >> Tersely: the relationship between an object and its attributes, is not >> the same as the relationship between a dictionary and its items. > > > I understand this to mean that the relationship between a dictionary and > its items is less complex than the relationship between an object and > its attributes. I think that is a fair comment, since attribute access involves MUCH more complexity than dict item access. Attribute access involves one *or more* dict access, *plus* a whole lot of extra complexity, while dict access by definition involves only a single dict access. > I'd like to catalog the different attribute types/implications: > - perhaps a hierarchy of meta-ism - or user-relevance > - those things in the __dict__ > - those things not in the __dict__ but without the "__" > - ??? I don't discourage you from learning for the sake of learning, but how does this get you closer to solving your actual problem? >>> Obviously there is a syntax difference between x.attr and x['key'] >> >> Not merely syntax; the attributes of an object are not generally >> available as items of the container. I've lost track of who you are quoting here. I think Ben? > What are the set of ways that an attribute is accessible? Including > implementation implications? You can write: x.attr which is equivalent to calling the function: getattr(x, "attr") But really, the only limit is what you program x to do. Python gives you the tools to make (say): x.what_is_my_name()[-1] + None return x.attr, although why would you want to? So let's put aside all the infinite number of weird and wacky ways that you could, with sufficient work, access attributes, and consider only the natural ways to do so. There are two: x.attr getattr(x, "attr") >>> Either the instance __dict__, the class __dict__, or a superclass >>> __dict__. >> >> No, I'm not referring to the ?__dict__? attribute of an object; I'm >> referring to the object itself. >> >> To talk about the attributes of an object ?foo? is distinct from talking >> about the items in a dictionary ?foo?. That distinction is real, and >> important. > > > But wanting to deal with the attributes of an object without considering > the way it's implemented - although possible - requires a complete virtual > model that covers all implications. It's easier to simply understand how > the objects work under the covers. You should understand how attributes are implemented, but it is not necessary to understand it in all the gory detail just to use them. Now I'm feeling some sympathy for the people on StackOverflow who told you that you don't need to understand this stuff -- perhaps I was too harsh on them :-) There's a lot of complicated implementation detail involved in attribute access, but for 99% of uses that's all handled for you and all you need do is write x.attr. -- Steven From steve at pearwood.info Thu Dec 31 10:35:36 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 02:35:36 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Dec 2015 11:19 pm, Oscar Benjamin wrote: > On 31 December 2015 at 04:07, Steven D'Aprano wrote: [...] >> As an implementation detail, exposing it to the user (in the form of a >> line in the stacktrace) doesn't help debugging. At best it is neutral >> (the user reads the error message and immediately realises that the >> problem lies with bad arguments passed to other, and _validate has >> nothing to do with it). At worst it actively misleads the user into >> thinking that there is a bug in _validate. > > You're overthinking this. Maybe. As I have suggested a number of times now, I'm aware that this is just a marginal issue. But I think it is a real issue. I believe in beautiful tracebacks that give you just the right amount of information, neither too little nor two much. Debugging is hard enough with being given more information than you need and having to decide what bits to ignore and which are important. (Aside: does anyone else hate the tracebacks given by PyCharm? We've had a number of people posting traceback of errors from PyCharm recently, and in my opinion they drown you in irrelevant detail.) > It's fine for the error to come from > _validate. Conceptually the real error is not in _validate or the > function that calls _validate but in whatever function further up the > stack trace created the wrong type of object to pass in. That may be so, but that could be *anywhere* in the call chain. The ultimate cause of the error may not even appear in the call chain. The principle is that errors should be raised as close to their cause as possible. If I call spam(a, b) and provide bad arguments, the earliest I can possibly detect that is in spam. (Only spam knows what it accepts as arguments.) Any additional levels beyond spam (like _validate) is moving further away: File "spam", line 19, in this File "spam", line 29, in that <--- where the error really lies File "spam", line 39, in other File "spam", line 89, in spam <--- the first place we could detect it File "spam", line 5, in _validate <--- where we actually detect it > If the user > can see the stack trace and work back to the point where they passed > something in to your function then how does the extra level hurt? It hurts precisely because it is one extra level. I acknowledge that it is *only* one extra level. (I told you this was a marginal benefit.) If one extra level is okay, might two extra be okay? How about three? What about thirty? Where would you draw the line? > If it really bothers you then you can use a comment that will show up > in the traceback output > > _validate(a, b) # Verify arguments to myfunc(a, b) No, that can't work. (Aside from the fact that in the most general case, the source code may no longer be available to read.) The whole point of moving the validation code into a function was to share it between a number of functions. > but really I don't think it's a big deal. The traceback gives you > useful information about where to look for an error/bug but it's still > the programmer's job to interpret that, look at the code, and try to > understand what they have done to cause the problem. Sure. And I believe that this technique will make the programmer's job just a little bit easier. -- Steven From rosuav at gmail.com Thu Dec 31 10:53:15 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Jan 2016 02:53:15 +1100 Subject: raise None In-Reply-To: <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Jan 1, 2016 at 2:35 AM, Steven D'Aprano wrote: >> If the user >> can see the stack trace and work back to the point where they passed >> something in to your function then how does the extra level hurt? > > It hurts precisely because it is one extra level. I acknowledge that it is > *only* one extra level. (I told you this was a marginal benefit.) > > If one extra level is okay, might two extra be okay? How about three? What > about thirty? Where would you draw the line? > It becomes something to get used to when you work with a particular library. Several of my students have run into this with matplotlib or sklearn; you make a mistake with a parameter to function X, which just takes that as-is and passes it to function Y, which does some manipulation but doesn't trip the error, and then calls through to function Z, which notices that one parameter doesn't match another, and raises an exception. You get used to scrolling way up to find the actual cause of the error. Whether that supports or contradicts your point, I'm not sure. ChrisA From breamoreboy at yahoo.co.uk Thu Dec 31 10:58:56 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Dec 2015 15:58:56 +0000 Subject: raise None In-Reply-To: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31/12/2015 00:09, Steven D'Aprano wrote: > I have a lot of functions that perform the same argument checking each time: > > def spam(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > def eggs(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > ... > > Since the code is repeated, I naturally pull it out into a function: > > def _validate(a, b): > if condition(a) or condition(b): raise TypeError > if other_condition(a) or something_else(b): raise ValueError > if whatever(a): raise SomethingError > > def spam(a, b): > _validate(a, b) > ... > > def eggs(a, b): > _validate(a, b) > ... > > But when the argument checking fails, the traceback shows the error > occurring in _validate, not eggs or spam. (Naturally, since that is where > the exception is raised.) That makes the traceback more confusing than it > need be. I disagree. > > So I can change the raise to return in the _validate function: > > def _validate(a, b): > if condition(a) or condition(b): return TypeError > if other_condition(a) or something_else(b): return ValueError > if whatever(a): return SomethingError > > and then write spam and eggs like this: > > def spam(a, b): > ex = _validate(a, b) > if ex is not None: raise ex > ... > > It's not much of a gain though. I save an irrelevant level in the traceback, > but only at the cost of an extra line of code everywhere I call the > argument checking function. > > But suppose we allowed "raise None" to do nothing. Then I could rename > _validate to _if_error and write this: > > def spam(a, b): > raise _if_error(a, b) > ... > > > and have the benefits of "Don't Repeat Yourself" without the unnecessary, > and misleading, extra level in the traceback. > > Obviously this doesn't work now, since raise None is an error, but if it did > work, what do you think? > A lot of fuss over nothing. -- 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 Thu Dec 31 11:12:44 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Dec 2015 16:12:44 +0000 Subject: Where are we in the Python 3 transition? Message-ID: "Or, how the K?bler-Ross model aptly applies to Python 3". http://www.snarky.ca/the-stages-of-the-python-3-transition -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From dfnsonfsduifb at gmx.de Thu Dec 31 11:17:56 2015 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 31 Dec 2015 17:17:56 +0100 Subject: raise None In-Reply-To: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31.12.2015 01:09, Steven D'Aprano wrote: > Obviously this doesn't work now, since raise None is an error, but if it did > work, what do you think? I really like the idea. I've approached a similar problem with a similar solution (also experimented with decorators), but the tracebacks really are unintuitive. Unless I missed something, this seems like a nice feature. 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 ebuzman63 at gmail.com Thu Dec 31 11:24:15 2015 From: ebuzman63 at gmail.com (ebuka ogbonnaya) Date: Thu, 31 Dec 2015 08:24:15 -0800 Subject: Complain Message-ID: my name is Ebuka Egbunine, from Nigeria.I studied Geology and mining.Actually i downloaded python3.5(32-bit) successfully on my laptop which operates on 32-bit memory, but the application is not opening, it displays the message " the program can't start because api-ms-crt runtime-l1-1-0.dll is missing from my computer. Try reinstalling the program to fix this problem". I have reinstalled it twice all to no avail. I want to know if there is any other possible solution to the problem. Thanks From steve at pearwood.info Thu Dec 31 11:32:06 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 03:32:06 +1100 Subject: Where are we in the Python 3 transition? References: Message-ID: <56855888$0$1614$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Jan 2016 03:12 am, Mark Lawrence wrote: > "Or, how the K?bler-Ross model aptly applies to Python 3". > > http://www.snarky.ca/the-stages-of-the-python-3-transition Nice link Mark, thanks. -- Steven From invalid at invalid.invalid Thu Dec 31 11:46:28 2015 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 31 Dec 2015 16:46:28 +0000 (UTC) Subject: Need help on a project To :"Create a class called BankAccount with the following parameters " References: <5ec1d759-a2ab-4193-a4aa-869c0bf0506c@googlegroups.com> <1e0feecd-6292-406d-ac27-d32742a4023a@googlegroups.com> <8297515b-834b-4829-abb4-0191a66222bb@googlegroups.com> Message-ID: On 2015-12-25, Gregory Ewing wrote: > Grant Edwards wrote: >> And don't get me started on those people who use those "integrated >> circuits" instead of transistors, relays, and tubes... > > Transistors? You don't know how good you had it. > In my day we had to poke the dopant atoms into > the silicon one at a time with the point of a > needle. You had needles?! -- Grant From oscar.j.benjamin at gmail.com Thu Dec 31 11:46:55 2015 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Dec 2015 16:46:55 +0000 Subject: raise None In-Reply-To: References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31 Dec 2015 15:54, "Chris Angelico" wrote: > > On Fri, Jan 1, 2016 at 2:35 AM, Steven D'Aprano wrote: > >> If the user > >> can see the stack trace and work back to the point where they passed > >> something in to your function then how does the extra level hurt? > > > > It hurts precisely because it is one extra level. I acknowledge that it is > > *only* one extra level. (I told you this was a marginal benefit.) > > > > If one extra level is okay, might two extra be okay? How about three? What > > about thirty? Where would you draw the line? > > > > It becomes something to get used to when you work with a particular > library. Several of my students have run into this with matplotlib or > sklearn; you make a mistake with a parameter to function X, which just > takes that as-is and passes it to function Y, which does some > manipulation but doesn't trip the error, and then calls through to > function Z, which notices that one parameter doesn't match another, > and raises an exception. You get used to scrolling way up to find the > actual cause of the error Exactly. The critical technique is looking at the traceback and splitting it between what's your code and what's someone else's. Hopefully you don't need to look at steves_library.py to figure out what you did wrong. However if you do need to look at Steve's code you're now stumped because he's hidden the actual line that raises. All you know now is that somewhere in _validate the raise happened. Why hide that piece of information and complicate the general interpretation of stack traces? Actually matplotlib is a particularly tricky case as often the arguments you pass or stored and not accessed until later. So the traceback shows an error in the call to show() rather than e.g. legend(). Usually I can glean pretty quickly that e.g. the legend labels are at fault though from the traceback though. -- Oscar From rgaddi at highlandtechnology.invalid Thu Dec 31 12:15:41 2015 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Thu, 31 Dec 2015 17:15:41 -0000 (UTC) Subject: Python Data Analysis Recommendations Message-ID: I'm looking for some advice on handling data collection/analysis in Python. I do a lot of big, time consuming experiments in which I run a long data collection (a day or a weekend) in which I sweep a bunch of variables, then come back offline and try to cut the data into something that makes sense. For example, my last data collection looked (neglecting all the actual equipment control code in each loop) like: for t in temperatures: for r in voltage_ranges: for v in test_voltages[r]: for c in channels: for n in range(100): record_data() I've been using Sqlite (through peewee) as the data backend, setting up a couple tables with a basically hierarchical relationship, and then handling analysis with a rough cut of SQL queries against the original data, Numpy/Scipy for further refinement, and Matplotlib to actually do the visualization. For example, one graph was "How does the slope of straight line fit between measured and applied voltage vary as a function of temperature on each channel?" The whole process feels a bit grindy; like I keep having to do a lot of ad-hoc stitching things together. And I keep hearing about pandas, PyTables, and HDF5. Would that be making my life notably easier? If so, does anyone have any references on it that they've found particularly useful? The tutorials I've seen so far seem to not give much detail on what the point of what they're doing is; it's all "how you write the code" rather than "why you write the code". Paying money for books is acceptable; this is all on the company's time/dime. Thanks, Rob -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From martin at linux-ip.net Thu Dec 31 12:30:14 2015 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 31 Dec 2015 09:30:14 -0800 Subject: raise None In-Reply-To: <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi there, >>> At worst it actively misleads the user into thinking that there >>> is a bug in _validate. Is this "user" a software user or another programmer? If a software user, then some hint about why the _validate found unacceptable data might benefit the user's ability to adjust inputs to the program. If another programmer, then that person should be able to figure it out with the full trace. Probably it's not a bug in _validate, but ....it could be. So, it could be a disservice to the diagnostician to exempt the _validate function from suspicion. Thus, I'd want to see _validate in the stack trace. >Maybe. As I have suggested a number of times now, I'm aware that >this is just a marginal issue. > >But I think it is a real issue. I believe in beautiful tracebacks >that give you just the right amount of information, neither too >little nor two much. Debugging is hard enough with being given more >information than you need and having to decide what bits to ignore >and which are important. I agree about tracebacks that provide the right amount of information. If I were a programmer working with the code you are describingi, I would like to know in any traceback that the failed comparisons (which implement some sort of business logic or sanity checking) occurred in the _validate function. In any software system beyond the simplest, code/data tracing would be required to figure out where the bad data originated. Since Python allows us to provide ancillary text to any exception, you could always provide a fuller explanation of the validation failure. And, while you are at it, you could add the calling function name to the text to point the programmer faster toward the probable issue. Adding one optional parameter to _validate (defaulting to the caller's function name) would allow you to point the way to a diagnostician. Here's a _validate function I made up with two silly comparision tests--where a must be greater than b and both a and b must not be convertible to integers. def _validate(a, b, func=None): if not func: func = sys._getframe(1).f_code.co_name if a >= b: raise ValueError("a cannot be larger than b in " + func) if a == int(a) or b == int(b): raise TypeError("a, b must not be convertible to int in " + func) My main point is less about identifying the calling function or its calling function, but rather to observe that arbitrary text can be used. This should help the poor sap (who is, invariably, diagnosing the problem at 03:00) realize that the function _validate is not the problem. >The principle is that errors should be raised as close to their >cause as possible. If I call spam(a, b) and provide bad arguments, >the earliest I can possibly detect that is in spam. (Only spam >knows what it accepts as arguments.) Any additional levels beyond >spam (like _validate) is moving further away: > > File "spam", line 19, in this > File "spam", line 29, in that <--- where the error really lies > File "spam", line 39, in other > File "spam", line 89, in spam <--- the first place we could detect it > File "spam", line 5, in _validate <--- where we actually detect it Yes, indeed! Our stock in trade. I never liked function 'that'. I much prefer function 'this'. -Martin Q: Who is Snow White's brother? A: Egg white. Get the yolk? -- Martin A. Brown http://linux-ip.net/ From steve at pearwood.info Thu Dec 31 12:50:55 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 04:50:55 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56856b01$0$1597$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Jan 2016 03:46 am, Oscar Benjamin wrote: [...] > Exactly. The critical technique is looking at the traceback and splitting > it between what's your code and what's someone else's. Hopefully you don't > need to look at steves_library.py to figure out what you did wrong. > However if you do need to look at Steve's code you're now stumped because > he's hidden the actual line that raises. All you know now is that > somewhere in _validate the raise happened. Why hide that piece of > information and complicate the general interpretation of stack traces? No. I don't hide anything. Here's a simple example, minus any hypothetical new syntax, showing the traditional way and the non-traditional way. # example.py def _validate(arg): if not isinstance(arg, int): # traditional error handling: raise in the validation function raise TypeError('expected an int') if arg < 0: # non-traditional: return and raise in the caller return ValueError('argument must be non-negative') def func(x): exc = _validate(x) if exc is not None: raise exc print(x+1) def main(): value = None # on the second run, edit this to be -1 func(value) main() And here's the traceback you get in each case. First, the traditional way, raising directly inside _validate: [steve at ando tmp]$ python example.py Traceback (most recent call last): File "example.py", line 17, in main() File "example.py", line 15, in main func(value) File "example.py", line 8, in func exc = _validate(x) File "example.py", line 3, in _validate raise TypeError('expected an int') TypeError: expected an int What do we see? Firstly, the emphasis is on the final call to _validate, where the exception is actually raised. (As it should be, in the general case where the exception is an error.) If you're like me, you're used to skimming the traceback until you get to the last entry, which in this case is: File "example.py", line 3, in _validate and starting to investigate there. But that's a red herring, because although the exception is raised there, that's not where the error lies. _validate is pretty much just boring boilerplate that validates the arguments -- where we really want to start looking is the previous entry, func, and work backwards from there. The second thing we see is that the displayed source code for _validate is entirely redundant: raise TypeError('expected an int') gives us *nothing* we don't see from the exception itself: TypeError: expected an int This is a pretty simple exception. In a more realistic example, with a longer and more detailed message, you might see something like this as the source extract: raise TypeError(msg) where the message is set up in the previous line or lines. This is even less useful to read. So it is my argument that the traditional way of refactoring parameter checks, where exceptions are raised in the _validate function, is sub-optimal. We can do better. Here's the traceback we get from the non-traditional error handling. I edit the file to change the value = None line to value = -1 and re-run it: [steve at ando tmp]$ python example.py Traceback (most recent call last): File "example.py", line 17, in main() File "example.py", line 15, in main func(value) File "example.py", line 10, in func raise exc ValueError: argument must be non-negative Nothing is hidden. We still see the descriptive exception and error message, and the line raise exc is no worse than "raise TypeError(msg)" -- all the detail we need is immediately below it. The emphasis here is on the call to func, since that's the last entry in the call stack. The advantage is that we don't see the irrelevant call to _validate *unless we go looking for it in the source code*. We start our investigate where we need to start, namely in func itself. Of course, none of this is mandatory, nor is it new. Although I haven't tried it, I'm sure that this would work as far back as Python 1.5, since exceptions are first-class values that can be passed around and raised when required. It's entirely up to the developer to choose whether this non-traditional idiom makes sense for their functions or not. Sometimes it will, and sometimes it won't. The only new part here is the idea that we could streamline the code in the caller if "raise None" was a no-op. Instead of writing this: exc = _validate(x) if exc is not None: raise exc we could write: raise _validate(x) which would make this idiom more attractive. -- Steven From otaksoftspamtrap at gmail.com Thu Dec 31 13:18:52 2015 From: otaksoftspamtrap at gmail.com (otaksoftspamtrap at gmail.com) Date: Thu, 31 Dec 2015 10:18:52 -0800 (PST) Subject: Newbie: Check first two non-whitespace characters Message-ID: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> I need to check a string over which I have no control for the first 2 non-white space characters (which should be '[{'). The string would ideally be: '[{...' but could also be something like ' [ { ....'. Best to use re and how? Something else? From python at mrabarnett.plus.com Thu Dec 31 13:38:01 2015 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 31 Dec 2015 18:38:01 +0000 Subject: Newbie: Check first two non-whitespace characters In-Reply-To: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: <56857609.9080603@mrabarnett.plus.com> On 2015-12-31 18:18, otaksoftspamtrap at gmail.com wrote: > I need to check a string over which I have no control for the first 2 non-white space characters (which should be '[{'). > > The string would ideally be: '[{...' but could also be something like > ' [ { ....'. > > Best to use re and how? Something else? > I would use .split and then ''.join: >>> ''.join(' [ { ....'.split()) '[{....' It might be faster if you provide a maximum for the number of splits: >>> ''.join(' [ { ....'.split(None, 1)) '[{ ....' From kliateni at gmail.com Thu Dec 31 13:54:23 2015 From: kliateni at gmail.com (Karim) Date: Thu, 31 Dec 2015 19:54:23 +0100 Subject: Newbie: Check first two non-whitespace characters In-Reply-To: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: <568579DF.50805@gmail.com> On 31/12/2015 19:18, otaksoftspamtrap at gmail.com wrote: > I need to check a string over which I have no control for the first 2 non-white space characters (which should be '[{'). > > The string would ideally be: '[{...' but could also be something like > ' [ { ....'. > > Best to use re and how? Something else? Use pyparsing it is straight forward: >>> from pyparsing import Suppress, restOfLine >>> mystring = Suppress('[') + Suppress('{') + restOfLine >>> result = mystring.parse(' [ { .... I am learning pyparsing' ) >>> print result.asList() ['.... I am learning pyparsing'] You'll get your string inside the list. Hope this help see pyparsing doc for in depth study. Karim From tandrewjohnson at outlook.com Thu Dec 31 13:55:56 2015 From: tandrewjohnson at outlook.com (tjohnson) Date: Thu, 31 Dec 2015 13:55:56 -0500 Subject: Complain In-Reply-To: References: Message-ID: <56857A3C.1080403@outlook.com> On 12/31/2015 11:24 AM, ebuka ogbonnaya wrote: > my name is Ebuka Egbunine, from Nigeria.I studied Geology and > mining.Actually i downloaded python3.5(32-bit) successfully on my laptop > which operates on 32-bit memory, but the application is not opening, it > displays the message " the program can't start because api-ms-crt > runtime-l1-1-0.dll is missing from my computer. Try reinstalling the > program to fix this problem". I have reinstalled it twice all to no avail. > I want to know if there is any other possible solution to the > problem. > > Thanks > Is your operating system Windows XP? If so, you won't be able to use Python 3.5 because it isn't compatible with WinXP, but you can use Python 2.7 or 3.4 instead. From tandrewjohnson at outlook.com Thu Dec 31 13:55:56 2015 From: tandrewjohnson at outlook.com (tjohnson) Date: Thu, 31 Dec 2015 13:55:56 -0500 Subject: Complain In-Reply-To: References: Message-ID: On 12/31/2015 11:24 AM, ebuka ogbonnaya wrote: > my name is Ebuka Egbunine, from Nigeria.I studied Geology and > mining.Actually i downloaded python3.5(32-bit) successfully on my laptop > which operates on 32-bit memory, but the application is not opening, it > displays the message " the program can't start because api-ms-crt > runtime-l1-1-0.dll is missing from my computer. Try reinstalling the > program to fix this problem". I have reinstalled it twice all to no avail. > I want to know if there is any other possible solution to the > problem. > > Thanks > Is your operating system Windows XP? If so, you won't be able to use Python 3.5 because it isn't compatible with WinXP, but you can use Python 2.7 or 3.4 instead. From csmadden at gmail.com Thu Dec 31 13:56:05 2015 From: csmadden at gmail.com (Cory Madden) Date: Thu, 31 Dec 2015 10:56:05 -0800 Subject: Newbie: Check first two non-whitespace characters In-Reply-To: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: I would personally use re here. test_string = ' [{blah blah blah' matches = re.findall(r'[^\s]', t) result = ''.join(matches)[:2] >> '[{' On Thu, Dec 31, 2015 at 10:18 AM, wrote: > I need to check a string over which I have no control for the first 2 non-white space characters (which should be '[{'). > > The string would ideally be: '[{...' but could also be something like > ' [ { ....'. > > Best to use re and how? Something else? > -- > https://mail.python.org/mailman/listinfo/python-list From breamoreboy at yahoo.co.uk Thu Dec 31 13:56:29 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Dec 2015 18:56:29 +0000 Subject: Complain In-Reply-To: References: Message-ID: On 31/12/2015 16:24, ebuka ogbonnaya wrote: > my name is Ebuka Egbunine, from Nigeria.I studied Geology and > mining.Actually i downloaded python3.5(32-bit) successfully on my laptop > which operates on 32-bit memory, but the application is not opening, it > displays the message " the program can't start because api-ms-crt > runtime-l1-1-0.dll is missing from my computer. Try reinstalling the > program to fix this problem". I have reinstalled it twice all to no avail. > I want to know if there is any other possible solution to the > problem. > > Thanks > This has been asked and answered repeatedly so I suggest you search the archives. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From kliateni at gmail.com Thu Dec 31 14:05:02 2015 From: kliateni at gmail.com (Karim) Date: Thu, 31 Dec 2015 20:05:02 +0100 Subject: Newbie: Check first two non-whitespace characters In-Reply-To: <568579DF.50805@gmail.com> References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> <568579DF.50805@gmail.com> Message-ID: <56857C5E.8080106@gmail.com> On 31/12/2015 19:54, Karim wrote: > > > On 31/12/2015 19:18, otaksoftspamtrap at gmail.com wrote: >> I need to check a string over which I have no control for the first 2 >> non-white space characters (which should be '[{'). >> >> The string would ideally be: '[{...' but could also be something like >> ' [ { ....'. >> >> Best to use re and how? Something else? > > Use pyparsing it is straight forward: > > >>> from pyparsing import Suppress, restOfLine > > >>> mystring = Suppress('[') + Suppress('{') + restOfLine > > >>> result = mystring.parse(' [ { .... I am learning pyparsing' ) > > >>> print result.asList() > > ['.... I am learning pyparsing'] > > You'll get your string inside the list. > > Hope this help see pyparsing doc for in depth study. > > Karim Sorry the method to parse a string is parseString not parse, please replace by this line: >>> result = mystring.parseString(' [ { .... I am learning pyparsing' ) Regards From cassius.fechter at gmail.com Thu Dec 31 14:21:18 2015 From: cassius.fechter at gmail.com (cassius.fechter at gmail.com) Date: Thu, 31 Dec 2015 11:21:18 -0800 (PST) Subject: Newbie: Check first two non-whitespace characters In-Reply-To: References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> <568579DF.50805@gmail.com> Message-ID: <3f355b97-3a94-41af-8624-9d244eb555a3@googlegroups.com> Thanks much to both of you! On Thursday, December 31, 2015 at 11:05:26 AM UTC-8, Karim wrote: > On 31/12/2015 19:54, Karim wrote: > > > > > > On 31/12/2015 19:18, snailpail at gmail.com wrote: > >> I need to check a string over which I have no control for the first 2 > >> non-white space characters (which should be '[{'). > >> > >> The string would ideally be: '[{...' but could also be something like > >> ' [ { ....'. > >> > >> Best to use re and how? Something else? > > > > Use pyparsing it is straight forward: > > > > >>> from pyparsing import Suppress, restOfLine > > > > >>> mystring = Suppress('[') + Suppress('{') + restOfLine > > > > >>> result = mystring.parse(' [ { .... I am learning pyparsing' ) > > > > >>> print result.asList() > > > > ['.... I am learning pyparsing'] > > > > You'll get your string inside the list. > > > > Hope this help see pyparsing doc for in depth study. > > > > Karim > > Sorry the method to parse a string is parseString not parse, please > replace by this line: > > >>> result = mystring.parseString(' [ { .... I am learning pyparsing' ) > > Regards From pkpearson at nowhere.invalid Thu Dec 31 14:26:32 2015 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 31 Dec 2015 19:26:32 GMT Subject: Complain References: Message-ID: On Thu, 31 Dec 2015 08:24:15 -0800, ebuka ogbonnaya wrote: > my name is Ebuka Egbunine, from Nigeria.I studied Geology and > mining.Actually i downloaded python3.5(32-bit) successfully on my laptop > which operates on 32-bit memory, but the application is not opening, it > displays the message " the program can't start because api-ms-crt > runtime-l1-1-0.dll is missing from my computer. Try reinstalling the > program to fix this problem". I have reinstalled it twice all to no avail. > I want to know if there is any other possible solution to the > problem. Welcome to the comp.lang.pyton newsgroup. Somebody more capable than me will probably come along soon and answer your question. In the meantime, you might improve your chances of getting a useful answer by telling us what operating system you're using, and maybe something about the hardware. -- To email me, substitute nowhere->runbox, invalid->com. From ebuzman63 at gmail.com Thu Dec 31 15:05:38 2015 From: ebuzman63 at gmail.com (ebuka ogbonnaya) Date: Thu, 31 Dec 2015 12:05:38 -0800 Subject: No subject Message-ID: I use window 7 (32-bit). so i dont know what else to do. please i need a solution to that From ben+python at benfinney.id.au Thu Dec 31 15:18:21 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Jan 2016 07:18:21 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85r3i2s776.fsf@benfinney.id.au> Oscar Benjamin writes: > Exactly. The critical technique is looking at the traceback and > splitting it between what's your code and what's someone else's. > Hopefully you don't need to look at steves_library.py to figure out > what you did wrong. However if you do need to look at Steve's code > you're now stumped because he's hidden the actual line that raises. +1. As best I can tell, Steven is advocating a way to obscure information from the traceback, on the assumption the writer of a library knows that I don't want to see it. Given how very often such decisions make my debugging tasks needlessly difficult, I'm not seeing how that's a desirable feature. -- \ ?Firmness in decision is often merely a form of stupidity. It | `\ indicates an inability to think the same thing out twice.? | _o__) ?Henry L. Mencken | Ben Finney From ben+python at benfinney.id.au Thu Dec 31 15:26:05 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Jan 2016 07:26:05 +1100 Subject: Where are we in the Python 3 transition? References: <56855888$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85mvsqs6ua.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 1 Jan 2016 03:12 am, Mark Lawrence wrote: > > > http://www.snarky.ca/the-stages-of-the-python-3-transition > > Nice link Mark, thanks. People sometimes ask me how much Python 2 code I'll be maintaining by the time official Python 2 support ends. I tell them I can't say, because I don't have 2020 vision. -- \ ?Science shows that belief in God is not only obsolete. It is | `\ also incoherent.? ?Victor J. Stenger, 2001 | _o__) | Ben Finney From denismfmcmahon at gmail.com Thu Dec 31 15:35:11 2015 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 31 Dec 2015 20:35:11 -0000 (UTC) Subject: Newbie: Check first two non-whitespace characters References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: On Thu, 31 Dec 2015 10:18:52 -0800, otaksoftspamtrap wrote: > Best to use re and how? Something else? Split the string on the space character and check the first two non blank elements of the resulting list? Maybe something similar to the following: if [x for x in s.split(' ') if x != ''][0:3] == ['(', '(', '(']: # string starts '(((' -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Thu Dec 31 17:48:33 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Jan 2016 09:48:33 +1100 Subject: raise None In-Reply-To: <85r3i2s776.fsf@benfinney.id.au> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> Message-ID: On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney wrote: > Oscar Benjamin writes: > >> Exactly. The critical technique is looking at the traceback and >> splitting it between what's your code and what's someone else's. >> Hopefully you don't need to look at steves_library.py to figure out >> what you did wrong. However if you do need to look at Steve's code >> you're now stumped because he's hidden the actual line that raises. > > +1. > > As best I can tell, Steven is advocating a way to obscure information > from the traceback, on the assumption the writer of a library knows that > I don't want to see it. > > Given how very often such decisions make my debugging tasks needlessly > difficult, I'm not seeing how that's a desirable feature. What Steven's actually advocating is removing a difference between Python code and native code. Compare: >>> class Integer: ... def __add__(self, other): ... if isinstance(other, list): ... raise TypeError("unsupported operand type(s) for +: 'Integer' and 'list'") ... return 5 ... >>> 7 + [] Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'list' >>> Integer() + [] Traceback (most recent call last): File "", line 1, in File "", line 4, in __add__ TypeError: unsupported operand type(s) for +: 'Integer' and 'list' The default int type is implemented in native code (C in CPython, Java in Jython, etc). If the addition of an int and something else triggers TypeError, the last line in the traceback is the last line of Python, which is the caller. But since Integer is implemented in Python, it adds another line to the traceback. Would you advocate adding lines to the first traceback saying: File "longobject.c", line 3008, in long_add File "longobject.c", line 1425, in CHECK_BINOP etc? It might be useful to someone trying to debug an extension library (or the interpreter itself). Or if it's acceptable to omit the "uninteresting internals" from tracebacks, then why can't we declare that some bits of Python code are uninteresting, too? We already have the means of throwing exceptions into generators, which "pretends" that the exception happened at that point. Why can't we throw an exception out to the caller? I think it's a perfectly reasonable idea, albeit only a small benefit (and thus not worth heaps of new syntax or anything). ChrisA From breamoreboy at yahoo.co.uk Thu Dec 31 18:25:52 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Dec 2015 23:25:52 +0000 Subject: Newbie: Check first two non-whitespace characters In-Reply-To: <568579DF.50805@gmail.com> References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> <568579DF.50805@gmail.com> Message-ID: On 31/12/2015 18:54, Karim wrote: > > > On 31/12/2015 19:18, otaksoftspamtrap at gmail.com wrote: >> I need to check a string over which I have no control for the first 2 >> non-white space characters (which should be '[{'). >> >> The string would ideally be: '[{...' but could also be something like >> ' [ { ....'. >> >> Best to use re and how? Something else? > > Use pyparsing it is straight forward: > > >>> from pyparsing import Suppress, restOfLine > > >>> mystring = Suppress('[') + Suppress('{') + restOfLine > > >>> result = mystring.parse(' [ { .... I am learning pyparsing' ) > > >>> print result.asList() > > ['.... I am learning pyparsing'] > > You'll get your string inside the list. > > Hope this help see pyparsing doc for in depth study. > > Karim Congratulations for writing up one of the most overengineered pile of cobblers I've ever seen. -- 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 Thu Dec 31 18:27:31 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Jan 2016 10:27:31 +1100 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> Message-ID: <85io3eryfw.fsf@benfinney.id.au> Chris Angelico writes: > On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney wrote: > > Given how very often such decisions make my debugging tasks > > needlessly difficult, I'm not seeing how that's a desirable feature. > > What Steven's actually advocating is removing a difference between > Python code and native code. Sure, but his proposal is to move in the direction of *less* debugging information. If I could have the traceback continue into the C code and tell me the line of C code that raised the exception, *that's* what I'd choose. The debugging information barrier of the C?Python boundary is a practical limitation, not a desirable one. I think those barriers should be as few as possible, and don't agree with enabling more of them. -- \ ?Welchen Teil von ?Gestalt? verstehen Sie nicht? [What part of | `\ ?gestalt? don't you understand?]? ?Karsten M. Self | _o__) | Ben Finney From breamoreboy at yahoo.co.uk Thu Dec 31 18:36:18 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Dec 2015 23:36:18 +0000 Subject: raise None In-Reply-To: <85io3eryfw.fsf@benfinney.id.au> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> <85io3eryfw.fsf@benfinney.id.au> Message-ID: On 31/12/2015 23:27, Ben Finney wrote: > Chris Angelico writes: > >> On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney wrote: >>> Given how very often such decisions make my debugging tasks >>> needlessly difficult, I'm not seeing how that's a desirable feature. >> >> What Steven's actually advocating is removing a difference between >> Python code and native code. > > Sure, but his proposal is to move in the direction of *less* debugging > information. > > If I could have the traceback continue into the C code and tell me the > line of C code that raised the exception, *that's* what I'd choose. > > The debugging information barrier of the C?Python boundary is a > practical limitation, not a desirable one. I think those barriers should > be as few as possible, and don't agree with enabling more of them. > Where did C code enter into this? What do the non C implementations do? All I see is a dumb original suggestion that should be shot down in flames as I see no merit in it at all. -- 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 Dec 31 18:39:21 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Jan 2016 10:39:21 +1100 Subject: raise None In-Reply-To: <85io3eryfw.fsf@benfinney.id.au> References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> <85io3eryfw.fsf@benfinney.id.au> Message-ID: On Fri, Jan 1, 2016 at 10:27 AM, Ben Finney wrote: > Chris Angelico writes: > >> On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney wrote: >> > Given how very often such decisions make my debugging tasks >> > needlessly difficult, I'm not seeing how that's a desirable feature. >> >> What Steven's actually advocating is removing a difference between >> Python code and native code. > > Sure, but his proposal is to move in the direction of *less* debugging > information. > > If I could have the traceback continue into the C code and tell me the > line of C code that raised the exception, *that's* what I'd choose. > > The debugging information barrier of the C?Python boundary is a > practical limitation, not a desirable one. I think those barriers should > be as few as possible, and don't agree with enabling more of them. Hmm, maybe. Personally, I wouldn't find exception tracebacks any more helpful for including a bunch of C code lines, but maybe that should be something for tooling. Actually, that's a possibility. If your traceback automatically highlights the last line that isn't imported from sys.path, that might cover the issue. Normally the error will be in your code, not some library you imported. Everything that you got from "someone else" is likely to be installed into sys.path somewhere. Might not be perfect, but it'd be a start. ChrisA From rosuav at gmail.com Thu Dec 31 18:41:42 2015 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Jan 2016 10:41:42 +1100 Subject: raise None In-Reply-To: References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> <85io3eryfw.fsf@benfinney.id.au> Message-ID: On Fri, Jan 1, 2016 at 10:36 AM, Mark Lawrence wrote: > On 31/12/2015 23:27, Ben Finney wrote: >> >> Chris Angelico writes: >> >>> On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney >>> wrote: >>>> >>>> Given how very often such decisions make my debugging tasks >>>> needlessly difficult, I'm not seeing how that's a desirable feature. >>> >>> >>> What Steven's actually advocating is removing a difference between >>> Python code and native code. >> >> >> Sure, but his proposal is to move in the direction of *less* debugging >> information. >> >> If I could have the traceback continue into the C code and tell me the >> line of C code that raised the exception, *that's* what I'd choose. >> >> The debugging information barrier of the C?Python boundary is a >> practical limitation, not a desirable one. I think those barriers should >> be as few as possible, and don't agree with enabling more of them. >> > > Where did C code enter into this? What do the non C implementations do? > All I see is a dumb original suggestion that should be shot down in flames > as I see no merit in it at all. I used the term "native code", because Jython and PyPy do the exact same thing that CPython does. (I haven't checked any others than those, but I wouldn't be surprised if they, too, had this distinction.) Short-handing to "C code" is close enough. ChrisA From marko at pacujo.net Thu Dec 31 19:29:41 2015 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 01 Jan 2016 02:29:41 +0200 Subject: raise None References: <56847239$0$1590$c3e8da3$5496439d@news.astraweb.com> <5684842a$0$1596$c3e8da3$5496439d@news.astraweb.com> <5684aa1a$0$1602$c3e8da3$5496439d@news.astraweb.com> <56854b49$0$1615$c3e8da3$5496439d@news.astraweb.com> <85r3i2s776.fsf@benfinney.id.au> Message-ID: <87mvsq2lca.fsf@elektro.pacujo.net> Ben Finney : > Chris Angelico writes: >> What Steven's actually advocating is removing a difference between >> Python code and native code. > > Sure, but his proposal is to move in the direction of *less* debugging > information. > > If I could have the traceback continue into the C code and tell me the > line of C code that raised the exception, *that's* what I'd choose. > > The debugging information barrier of the C?Python boundary is a > practical limitation, not a desirable one. I think those barriers > should be as few as possible, and don't agree with enabling more of > them. I think I agree with you. Don't check anything; let it crash and burn if the input spec is violated. Marko From ikorot01 at gmail.com Thu Dec 31 20:06:07 2015 From: ikorot01 at gmail.com (Igor Korot) Date: Thu, 31 Dec 2015 17:06:07 -0800 Subject: Happy New Year Message-ID: Happy New Year to everybody on those lists. Let this year brings us a lot of happiness and joy. Lets keep the train rolling and make the upcoming year better. From steve at pearwood.info Thu Dec 31 20:12:39 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 12:12:39 +1100 Subject: Newbie: Check first two non-whitespace characters References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> <568579DF.50805@gmail.com> Message-ID: <5685d289$0$1616$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Jan 2016 10:25 am, Mark Lawrence wrote: > Congratulations for writing up one of the most overengineered pile of > cobblers I've ever seen. You should get out more. -- Steven From steve at pearwood.info Thu Dec 31 20:23:14 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 12:23:14 +1100 Subject: Newbie: Check first two non-whitespace characters References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: <5685d504$0$1607$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Jan 2016 05:18 am, otaksoftspamtrap at gmail.com wrote: > I need to check a string over which I have no control for the first 2 > non-white space characters (which should be '[{'). > > The string would ideally be: '[{...' but could also be something like > ' [ { ....'. > > Best to use re and how? Something else? This should work, and be very fast, for moderately-sized strings: def starts_with_brackets(the_string): the_string = the_string.replace(" ", "") return the_string.startswith("[}") It might be a bit slow for huge strings (tens of millions of characters), but for short strings it will be fine. Alternatively, use a regex: import re regex = re.compile(r' *\[ *\{') if regex.match(the_string): print("string starts with [{ as expected") else: raise ValueError("invalid string") This will probably be slower for small strings, but faster for HUGE strings (tens of millions of characters). But I expect it will be fast enough. It is simple enough to skip tabs as well as spaces. Easiest way is to match on any whitespace: regex = re.compile(r'\w*\[\w*\{') -- Steven From none at mailinator.com Thu Dec 31 20:27:33 2015 From: none at mailinator.com (mm0fmf) Date: Fri, 01 Jan 2016 01:27:33 +0000 Subject: Where are we in the Python 3 transition? In-Reply-To: References: Message-ID: On 31/12/2015 16:12, Mark Lawrence wrote: > "Or, how the K?bler-Ross model aptly applies to Python 3". > > http://www.snarky.ca/the-stages-of-the-python-3-transition > I thought I had a need for asyncio and that means Python3. So I started converting some web facing apps to Python3 for practice and it wasn't that hard. I've not written anything new in Python2 for about 9 months now. I never did need asyncio in the end but the thought I might pushed me to change. YMMV From steve at pearwood.info Thu Dec 31 20:31:00 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Jan 2016 12:31:00 +1100 Subject: Happy New Year References: Message-ID: <5685d6d7$0$1598$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Jan 2016 12:06 pm, Igor Korot wrote: > Happy New Year to everybody on those lists. Let this year brings us a > lot of happiness and joy. > Lets keep the train rolling and make the upcoming year better. Thanks Igor! To lurkers and contributors, newbies and experts, and even the more entertaining of our cranks (not mentioning any names, but we know who they are...), may 2016 be a better year than 2015 for us all. -- Steven From random832 at fastmail.com Thu Dec 31 20:31:16 2015 From: random832 at fastmail.com (Random832) Date: Thu, 31 Dec 2015 20:31:16 -0500 Subject: Newbie: Check first two non-whitespace characters References: <240ab049-68a0-4a00-b911-d58cae9bfbcf@googlegroups.com> Message-ID: otaksoftspamtrap at gmail.com writes: > I need to check a string over which I have no control for the first 2 > non-white space characters (which should be '[{'). > > The string would ideally be: '[{...' but could also be something like > ' [ { ....'. > > Best to use re and how? Something else? Is it an arbitrary string, or is it a JSON object consisting of a list whose first element is a dictionary? Because if you're planning on reading it as a JSON object later you could just validate the types after you've parsed it. From paul.hermeneutic at gmail.com Thu Dec 31 20:56:40 2015 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Thu, 31 Dec 2015 18:56:40 -0700 Subject: No subject In-Reply-To: References: Message-ID: Please provide a few more clues about the problem. What is the problem? On Thu, Dec 31, 2015 at 1:05 PM, ebuka ogbonnaya wrote: > I use window 7 (32-bit). so i dont know what else to do. please i need a > solution to that > -- > https://mail.python.org/mailman/listinfo/python-list >