From alan.gauld at btinternet.com Mon Sep 1 00:39:35 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Aug 2014 23:39:35 +0100 Subject: [Tutor] reading strings and calculating totals In-Reply-To: <14e23969d604dd8362853b4752d831bb@sonic.net> References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> <14e23969d604dd8362853b4752d831bb@sonic.net> Message-ID: On 31/08/14 19:32, Alex Kleider wrote: >> total = 0 >> with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: >> for line in infile: >> total += float(line) >> print(total) > > ..but isn't there a problem if the file contains empty lines? Yes you are right. And my second reply did point out that the OP would need to add some lines to catch any such non-conformities in his data. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Sep 1 01:17:52 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Sep 2014 01:17:52 +0200 Subject: [Tutor] how import a module upon instantiation of a class? References: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > I want to import a module upon instantiation (not definition) of a class. > What is the best way to do this? In my case, I need the "icu" module in > only one place/class of the program. If that class won't be used, I don't > want to have an ImportError. Also, it might be nice to do the imports only > when you actually need that functionality. It's probably not really > PEP-compliant to put the imports somewhere else than at the top of the > module, but I can live with that. > > > import some_nonbuiltin # I don't want it here! > > > class KlassA(object): > import some_nonbuiltin # nope > > def __init__(self): global some_nonbuiltin import some_nonbuiltin From davea at davea.name Mon Sep 1 01:31:13 2014 From: davea at davea.name (Dave Angel) Date: Sun, 31 Aug 2014 19:31:13 -0400 (EDT) Subject: [Tutor] calculate percents of items in a list References: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> Message-ID: LN A-go-go Wrote in message: > Please post in text mode. It's a real pain trying to respond to the memory of your post. sum () is a built-in function that will add all the floats in CL. Of course you can't use it after you've overloaded it with a new meaning. In your loop, you refer to CL [0] when you probably mean i. You also increment some variable in that loop when you're not using it. Next you have a complicated expression that calls float () twice on values that are already floats. As you've already been told, it'd be nice to show us the result you got, and the result you expected. -- DaveA From juan0christian at gmail.com Mon Sep 1 02:12:24 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 31 Aug 2014 21:12:24 -0300 Subject: [Tutor] Good Text Editor/IDE for Python Message-ID: I've been using PyCharm to code in Python but it seems a bit "overpowered" for this task, and there are some annoying bugs. I used Sublime Text 2 in the past, but it seems to be dead now (last update was JUN/2013), so I don't really know any good options. What do you guys use to code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Sep 1 03:13:35 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 11:13:35 +1000 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: <20140901011335.GD9293@ando.pearwood.info> On Sun, Aug 31, 2014 at 09:12:24PM -0300, Juan Christian wrote: > I've been using PyCharm to code in Python but it seems a bit "overpowered" > for this task, and there are some annoying bugs. I used Sublime Text 2 in > the past, but it seems to be dead now (last update was JUN/2013), so I > don't really know any good options. > > What do you guys use to code? I wouldn't be too concerned about the lack of updates to Sublime. Perhaps there are no updates because there are no bugs to fix, code to remove, or requested features to add. If it works, it works. You don't say what operating system you're using. I use Linux, and as far as I am concerned, the best IDE for Linux is Linux itself: http://blog.sanctum.geek.nz/series/unix-as-ide/ http://michaelochurch.wordpress.com/2013/01/09/ide-culture-vs-unix-philosophy/ My IDE is: - A good programmer's editor, ideally one that supports a tabbed interface. I normally use kate (from KDE 3, not KDE 4) or geany, or at a pinch kwrite although it's not tabbed. - A web browser, for looking up documentation and doing web searches. - A good tabbed terminal application. Konsole from KDE is my preferred choice, but just about any one will do. In the terminal, I'll open anything up to half a dozen tabs. One for running source control (git or hg) and other utilities, another for running the application I'm writing and performing tests, and at least one interactive Python session for trying out small snippets and looking up interactive help. Just recently, I've customised my interactive Python with a powerful set of tab completion commands, similar to that provided by IPython. While typing, if I hit tab, it will try to complete the current variable, function, module or file name. I don't know how I programmed without it all these years :-) -- Steven From steve at pearwood.info Mon Sep 1 03:26:44 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 11:26:44 +1000 Subject: [Tutor] calculate percents of items in a list In-Reply-To: References: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> Message-ID: <20140901012643.GE9293@ando.pearwood.info> On Sun, Aug 31, 2014 at 07:31:13PM -0400, Dave Angel wrote: > LN A-go-go Wrote in message: > > > > Please post in text mode. It's a real pain trying to respond to > the memory of your post. LN did post in text mode. Perhaps your email or news client is unable to deal with standard multipart/alternative attachments? If that's the case, I sympathise with your pain, but it's 2014 not 1994 and you ought to stop blaming the poster for your poor tools. Any email client which cannot reply to and quote from the text/plain part of a multipart message is too crappy for words. That's basic functionality. If you absolutely cannot or will not upgrade to a proper client, have you considered copying the original text before replying, pasting it into your reply, and manually adding quote markers? -- Steven From steve at pearwood.info Mon Sep 1 03:46:04 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 11:46:04 +1000 Subject: [Tutor] calculate percents of items in a list In-Reply-To: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> References: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> Message-ID: <20140901014604.GF9293@ando.pearwood.info> Hello, You seem to have deliberately set the Reply-To header for replies to go back to you, instead of allowing them to go to the mailing list for others to take part in the conversation. I don't know if that was you personally, or just another sign of the major suckage that is Yahoo mail, but either way I have honoured that request this time, but normally replies to questions on the tutor mailing list should go to the mailing list so that the others may learn. More comments below, interleaved with your questions. On Sun, Aug 31, 2014 at 10:28:32AM -0700, LN A-go-go wrote: > > > What would be a better way to calculate percentages of items in a list? > please.... > > CountList = [9221382, 10374466, 5192905, 1710238, 3359] > CL = [float(i) for i in CountList] I really don't know why you convert the numbers into floats. There doesn't seem to be any reason for that -- you can sum integer numbers just as easily. If you insist on floats, why not just make them floats in the first place? CountList = [9221382.0, 10374466.0, 5192905.0, 1710238.0, 3359.0] but that's silly. If they are meant to be *counts*, then you cannot have a fraction of a count. Just keep them as ints. > CL > sum = CL[0] + CL[1] + CL[2] + CL[3] + CL[4] Here you accidentally "shadow" the built-in sum() function. You shouldn't do this unless you know what you are doing. Instead: total = sum(CountList) gives you the total you are after. > import math That's not used or needed. > perList = [] > n = 0 > def percentage(CL,sum): > for i in CL: > PER = "return 100 * float (CL[0])/float (sum)" > perList.append(PER) > n = n + 1 You appear to be wanting to calculate cumulative percentages. A simple example: CountList = [5, 2, 8, 5] total = 20 cumulative percentages = [25.0, 35.0, 75.0, 100.0] Is that correct? If so, this will do it: counts = [9221382, 10374466, 5192905, 1710238, 3359] cumulative_totals = [] last = 0 for value in counts: last += value cumulative_totals.append(last) total = sum(counts) # check that the last value matches the total: assert total == cumulative_totals[-1] cumulative_percentages = [] for value in cumulative_totals: perc = value*100.0/total cumulative_percentages.append(perc) print(cumulative_percentages) I think that should do the trick. -- Steven From juan0christian at gmail.com Mon Sep 1 03:51:54 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 31 Aug 2014 22:51:54 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901011335.GD9293@ando.pearwood.info> References: <20140901011335.GD9293@ando.pearwood.info> Message-ID: I'm using Windows, but I do use Linux on a daily basis. On Sunday, August 31, 2014, Steven D'Aprano wrote: > On Sun, Aug 31, 2014 at 09:12:24PM -0300, Juan Christian wrote: > > I've been using PyCharm to code in Python but it seems a bit > "overpowered" > > for this task, and there are some annoying bugs. I used Sublime Text 2 in > > the past, but it seems to be dead now (last update was JUN/2013), so I > > don't really know any good options. > > > > What do you guys use to code? > > I wouldn't be too concerned about the lack of updates to Sublime. > Perhaps there are no updates because there are no bugs to fix, code to > remove, or requested features to add. If it works, it works. > > You don't say what operating system you're using. I use Linux, and as > far as I am concerned, the best IDE for Linux is Linux itself: > > http://blog.sanctum.geek.nz/series/unix-as-ide/ > > http://michaelochurch.wordpress.com/2013/01/09/ide-culture-vs-unix-philosophy/ > > My IDE is: > > - A good programmer's editor, ideally one that supports a tabbed > interface. I normally use kate (from KDE 3, not KDE 4) or geany, or > at a pinch kwrite although it's not tabbed. > > - A web browser, for looking up documentation and doing web searches. > > - A good tabbed terminal application. Konsole from KDE is my > preferred choice, but just about any one will do. > > In the terminal, I'll open anything up to half a dozen tabs. One for > running source control (git or hg) and other utilities, another for > running the application I'm writing and performing tests, and at least > one interactive Python session for trying out small snippets and looking > up interactive help. > > Just recently, I've customised my interactive Python with a powerful set > of tab completion commands, similar to that provided by IPython. While > typing, if I hit tab, it will try to complete the current variable, > function, module or file name. I don't know how I programmed without it > all these years :-) > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Mon Sep 1 03:57:08 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 1 Sep 2014 11:57:08 +1000 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901011335.GD9293@ando.pearwood.info> References: <20140901011335.GD9293@ando.pearwood.info> Message-ID: <20140901015708.GA97686@cskk.homeip.net> On 01Sep2014 11:13, Steven D'Aprano wrote: >On Sun, Aug 31, 2014 at 09:12:24PM -0300, Juan Christian wrote: >> I've been using PyCharm to code in Python but it seems a bit "overpowered" >> for this task, and there are some annoying bugs. I used Sublime Text 2 in >> the past, but it seems to be dead now (last update was JUN/2013), so I >> don't really know any good options. >> >> What do you guys use to code? [...] >You don't say what operating system you're using. I use Linux, and as >far as I am concerned, the best IDE for Linux is Linux itself: [...] > >http://blog.sanctum.geek.nz/series/unix-as-ide/ >http://michaelochurch.wordpress.com/2013/01/09/ide-culture-vs-unix-philosophy/ I'm mostly on OSX, but of course that is a UNIX platform as well:-) So my IDE is somewhat like Steven's. BTW, there are many many discussions in the python-list archives on the various development environments people use. >My IDE is: > >- A good programmer's editor, ideally one that supports a tabbed > interface. I normally use kate (from KDE 3, not KDE 4) or geany, or > at a pinch kwrite although it's not tabbed. I'm a vim user, and use it for everything (email, programming, any other plain text editing). I've been using vi since, um, maybe 1985, and my fingers know it. Of course, I use emacs editing keystrokes (a very limited subset of it, anyway) in interactive shells, including the Python interactive prompt; it is better in that scenario for me because it is modeless - vi is modal, which I find a win for coding. I don't use tabs or subwindows/panes in the editor. I do use tabs in the terminal (and my editor runs in a pane in my terminal). >- A web browser, for looking up documentation and doing web searches. Me too. And I find it very useful to have local copies of the Python doco on my desktop; accessing a local copy is really fast and also works when offline. I keep a local copy of the latest Python 2 and Python 3 doco to hand. This does rely on the doco having a good page size choice; I like a "page" to be a chapter. The Python doco does this well, a "page" per module. By contrast, the PostgreSQL doco is extremely finely sliced and very irritating to browse. I use tabs heavily in the web browser. >- A good tabbed terminal application. Konsole from KDE is my > preferred choice, but just about any one will do. On OSX the winning choice is iTerm2; I use it exclusively. Tabs and also subpanes. It has many good features. >In the terminal, I'll open anything up to half a dozen tabs. One for >running source control (git or hg) and other utilities, another for >running the application I'm writing and performing tests, and at least >one interactive Python session for trying out small snippets and looking >up interactive help. I use a tab per dev environment. (So a tab for my main project, and I use another tab for whichever of its branches I'm working in.) Within each tab I usually split the tab into 3 vertical panes: an editor in the middle )terminal running vim, for me) and a shell on either side. I open python interactive prompts at need as opposed to Steven's always-open instance. On occasions I split the vertical panes horizontally when I need an extra terminal for something short term. >Just recently, I've customised my interactive Python with a powerful set >of tab completion commands, similar to that provided by IPython. While >typing, if I hit tab, it will try to complete the current variable, >function, module or file name. I don't know how I programmed without it >all these years :-) I must try that sometime. Cheers, Cameron Simpson Baldrick: Sir, what shall we do if we stand on a mine? Edmund: Well, Baldrick - I think the common practice is to jump several metres into the air, and scatter yourself in a wide radius on the way down. - _Blackadder_ From ben+python at benfinney.id.au Mon Sep 1 04:29:58 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 01 Sep 2014 12:29:58 +1000 Subject: [Tutor] Good Text Editor/IDE for Python References: Message-ID: <8538ccxec9.fsf@benfinney.id.au> Juan Christian writes: > What [text editor] do you guys use to code? I use GNU Emacs primarily, and sometimes Vim. My recommendations have been posted in a different forum; I'll repeat them here. You can write Python code using any text editor. You will do well to use a text editor which is deliberately designed for programming and other related editing tasks. I would also recommend that a programmer's text editor should: * Be licensed as free software ? the tool should be able to be improved and maintained and distributed to you by any party sufficiently motivated, not locked up by any single party. * Work the same on all major platforms ? you should not need to abandon a tool you like merely because you switch to a different machine for a while. * Be mature with a strong track record ? a text editor which has been around for some decades, and still has a large following, has demonstrated it can survive many different trends in programming tools. * Have good support provided by its own vibrant community ? you don't necessarily need to join such a community, but you will greatly benefit from the fact that a tool has robust community support. That the tool is free software is a significant contributor to this. * Be indefinitely customisable to meet new needs ? this ensures that anyone sufficiently motivated can allow you to use the tool you already know for new tasks that come along. Having a strong community of support will mean that most tasks are already supported in the tool by people who came before you. * Properly support many programming languages and related formats ? this is an outcome of the tool being community-supported, mature, and highly customisable. The tool should, in its standard installation, already support major programming languages and formats, and have a simple way to add supporting plug-ins as you need them. I know of two obvious text editors that meet these criteria: * Vim * Emacs If you're using a *nix style operating system such as GNU+Linux, you will have both of these available for installation from the operating system. On other desktop operating systems you can install them easily too. I hope that helps. Familiarising yourself with a strong, free-software, cross-platform text editor is an essential investment in programming. Good hunting! -- \ ?Faith is generally nothing more than the permission religious | `\ people give to one another to believe things strongly without | _o__) evidence.? ?Sam Harris, _Letter to a Christian Nation_ 2006 | Ben Finney From derektjenkins at gmail.com Mon Sep 1 04:34:04 2014 From: derektjenkins at gmail.com (Derek Jenkins) Date: Sun, 31 Aug 2014 22:34:04 -0400 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901015708.GA97686@cskk.homeip.net> References: <20140901011335.GD9293@ando.pearwood.info> <20140901015708.GA97686@cskk.homeip.net> Message-ID: Juan, Besides Kwrite, I actually use the tools that the others mentioned so far, although I don't use Emacs often at all (perhaps I have just not found an advantageous use for it yet). So no real added info here, but I will say that I've not personally ran into any problems with Sublime. For Windows, if you must continue to use it, I can venture to suggest you give Notepad++ a whirl for a text editor. I have used it on a handful of occasions and it _generally_ seemed okay enough to keep it in mind for a rainy day, such as right now. As for PyCharm, I have 0 experience with that so I can't offer any suggestions. On Sun, Aug 31, 2014 at 9:57 PM, Cameron Simpson wrote: > On 01Sep2014 11:13, Steven D'Aprano wrote: >> >> On Sun, Aug 31, 2014 at 09:12:24PM -0300, Juan Christian wrote: >>> >>> I've been using PyCharm to code in Python but it seems a bit >>> "overpowered" >>> for this task, and there are some annoying bugs. I used Sublime Text 2 in >>> the past, but it seems to be dead now (last update was JUN/2013), so I >>> don't really know any good options. >>> >>> What do you guys use to code? > > [...] >> >> You don't say what operating system you're using. I use Linux, and as >> far as I am concerned, the best IDE for Linux is Linux itself: [...] >> >> http://blog.sanctum.geek.nz/series/unix-as-ide/ >> >> http://michaelochurch.wordpress.com/2013/01/09/ide-culture-vs-unix-philosophy/ > > > I'm mostly on OSX, but of course that is a UNIX platform as well:-) So my > IDE is somewhat like Steven's. BTW, there are many many discussions in the > python-list archives on the various development environments people use. > > >> My IDE is: >> >> - A good programmer's editor, ideally one that supports a tabbed >> interface. I normally use kate (from KDE 3, not KDE 4) or geany, or >> at a pinch kwrite although it's not tabbed. > > > I'm a vim user, and use it for everything (email, programming, any other > plain text editing). I've been using vi since, um, maybe 1985, and my > fingers know it. Of course, I use emacs editing keystrokes (a very limited > subset of it, anyway) in interactive shells, including the Python > interactive prompt; it is better in that scenario for me because it is > modeless - vi is modal, which I find a win for coding. > > I don't use tabs or subwindows/panes in the editor. I do use tabs in the > terminal (and my editor runs in a pane in my terminal). > > >> - A web browser, for looking up documentation and doing web searches. > > > Me too. And I find it very useful to have local copies of the Python doco on > my desktop; accessing a local copy is really fast and also works when > offline. I keep a local copy of the latest Python 2 and Python 3 doco to > hand. This does rely on the doco having a good page size choice; I like a > "page" to be a chapter. The Python doco does this well, a "page" per module. > By contrast, the PostgreSQL doco is extremely finely sliced and very > irritating to browse. > > I use tabs heavily in the web browser. > > >> - A good tabbed terminal application. Konsole from KDE is my >> preferred choice, but just about any one will do. > > > On OSX the winning choice is iTerm2; I use it exclusively. Tabs and also > subpanes. It has many good features. > > >> In the terminal, I'll open anything up to half a dozen tabs. One for >> running source control (git or hg) and other utilities, another for >> running the application I'm writing and performing tests, and at least >> one interactive Python session for trying out small snippets and looking >> up interactive help. > > > I use a tab per dev environment. (So a tab for my main project, and I use > another tab for whichever of its branches I'm working in.) > > Within each tab I usually split the tab into 3 vertical panes: an editor in > the middle )terminal running vim, for me) and a shell on either side. I open > python interactive prompts at need as opposed to Steven's always-open > instance. On occasions I split the vertical panes horizontally when I need > an extra terminal for something short term. > > >> Just recently, I've customised my interactive Python with a powerful set >> of tab completion commands, similar to that provided by IPython. While >> typing, if I hit tab, it will try to complete the current variable, >> function, module or file name. I don't know how I programmed without it >> all these years :-) > > > I must try that sometime. > > Cheers, > Cameron Simpson > > Baldrick: Sir, what shall we do if we stand on a mine? > Edmund: Well, Baldrick - I think the common practice is to jump several > metres > into the air, and scatter yourself in a wide radius on the way down. > - _Blackadder_ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From bouncingcats at gmail.com Mon Sep 1 08:39:11 2014 From: bouncingcats at gmail.com (David) Date: Mon, 1 Sep 2014 16:39:11 +1000 Subject: [Tutor] This is driving my crazy! My file hasn't been corrupted In-Reply-To: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> References: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> Message-ID: On 1 September 2014 02:31, Richard Dillon wrote: > > except IOError: > print('An error occured trying to read the file.') > > except ValueError: > print('Non-numeric data found in the file.') > > except: > print('An error occured.') Your other respondents have already said this, but I am going to emphasise it. The above lines are bad. They do not help you, they only hinder you by replacing useful information with dumb print statements that tell you nothing useful. So delete them all! 'except' blocks should only be used when you know why the error occurred, and they should contain useful extra code to either to recover from the error or to work around it. Those dumb print statements are not useful extra code. So delete them. From robertvstepp at gmail.com Mon Sep 1 03:35:11 2014 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 31 Aug 2014 20:35:11 -0500 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: On Sun, Aug 31, 2014 at 7:12 PM, Juan Christian wrote: > I've been using PyCharm to code in Python but it seems a bit "overpowered" > for this task, and there are some annoying bugs. I used Sublime Text 2 in > the past, but it seems to be dead now (last update was JUN/2013), so I don't > really know any good options. > Sublime Text is still being developed by its creator. He is just being slow (thorough?) about it. A seemingly stable beta version of Sublime Text 3 is available, and the plugin community is actively developing for it. boB From peter.romfeld.hk at gmail.com Mon Sep 1 06:54:30 2014 From: peter.romfeld.hk at gmail.com (Peter Romfeld) Date: Mon, 01 Sep 2014 12:54:30 +0800 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: <5403FC06.2090604@gmail.com> On Monday, September 01, 2014 08:12 AM, Juan Christian wrote: > I've been using PyCharm to code in Python but it seems a bit > "overpowered" for this task, and there are some annoying bugs. I used > Sublime Text 2 in the past, but it seems to be dead now (last update > was JUN/2013), so I don't really know any good options. > > What do you guys use to code? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor my favourite is githubs Atom https://atom.io/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Mon Sep 1 14:14:15 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 1 Sep 2014 09:14:15 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <5403FC06.2090604@gmail.com> References: <5403FC06.2090604@gmail.com> Message-ID: Sorry Peter, but you message is blank here. I (and presumedly the others) can't read a thing. On Monday, September 1, 2014, Peter Romfeld wrote: > On Monday, September 01, 2014 08:12 AM, Juan Christian wrote: > > I've been using PyCharm to code in Python but it seems a bit "overpowered" > for this task, and there are some annoying bugs. I used Sublime Text 2 in > the past, but it seems to be dead now (last update was JUN/2013), so I > don't really know any good options. > > What do you guys use to code? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:https://mail.python.org/mailman/listinfo/tutor > > my favourite is githubs Atom > https://atom.io/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Sep 1 14:41:54 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 22:41:54 +1000 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: <5403FC06.2090604@gmail.com> Message-ID: <20140901124154.GG9293@ando.pearwood.info> On Mon, Sep 01, 2014 at 09:14:15AM -0300, Juan Christian wrote: > Sorry Peter, but you message is blank here. I (and presumedly the others) > can't read a thing. Peter's message is tucked away at the very end of the quoted text, after the footer, with no blank line separating it from the quotes. It took me two goes to notice it too: > > my favourite is githubs Atom > > https://atom.io/ -- Steven From gordon.schulz at gmail.com Mon Sep 1 14:45:13 2014 From: gordon.schulz at gmail.com (gordon.schulz at gmail.com) Date: Mon, 1 Sep 2014 14:45:13 +0200 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: <20140901124513.GA20069@deeperthought.gobagreven.de> On Sunday, 31 Aug 2014 21:12, Juan Christian wrote: > I've been using PyCharm to code in Python but it seems a bit "overpowered" > for this task, and there are some annoying bugs. > What do you guys use to code? While I haven't really noticed any big bugs in PyCharm apart from the dog-slow debugger which really annoys me (anyone got suggestions how to speed it up?), I also regularly jump into (g)vim for most smaller tasks. Pycharm is also setup with the IdeaVim Plugin so my keymaps match and I don't mess up my muscle-memory. In vim I use some plugins for my development work, most notably YouCompleteMe, Unity, Fugitive+gitgutter, Syntastic and Ultisnips. Oh, ctags are also great to have. So it's basically about the task at hand - if it's some bigger project at work and/or home I want to play with, I usually fire up PyCharm and it's well worth it. For me the overhead is negligible - especially so if you put some Javascript/Jinja/etc/etc into the mix. Jetbrain's plugins and integration for almost anything under the sun are just amazing. For everything else it's vim I use. -- Best regards, /Gordon Schulz @azmd From fomcl at yahoo.com Mon Sep 1 15:46:41 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 1 Sep 2014 06:46:41 -0700 Subject: [Tutor] how import a module upon instantiation of a class? In-Reply-To: References: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <1409579201.2264.YahooMailNeo@web163804.mail.gq1.yahoo.com> ----- Original Message ----- > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Cc: > Sent: Monday, September 1, 2014 1:17 AM > Subject: Re: [Tutor] how import a module upon instantiation of a class? > > Albert-Jan Roskam wrote: > >> I want to import a module upon instantiation (not definition) of a class. >> What is the best way to do this? In my case, I need the "icu" > module in >> only one place/class of the program. If that class won't be used, I > don't >> want to have an ImportError. Also, it might be nice to do the imports only >> when you actually need that functionality. It's probably not really >> PEP-compliant to put the imports somewhere else than at the top of the >> module, but I can live with that. >> >> >> import some_nonbuiltin # I don't want it here! >> >> >> class KlassA(object): >> import some_nonbuiltin # nope >> >> def __init__(self): > global some_nonbuiltin > import some_nonbuiltin Ahh with 'global', thank you! It never crossed my mind that this should be used in this case. Within functions, 'global' is only required when the global variable is going to be modified. Given that the module won't be changed, why is global required? Regards, Albert-Jan From fomcl at yahoo.com Mon Sep 1 15:54:47 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 1 Sep 2014 06:54:47 -0700 Subject: [Tutor] abc module question Message-ID: <1409579687.15316.YahooMailNeo@web163805.mail.gq1.yahoo.com> Hi, I was playing with abc for the first time (never ever had any use for it). It works nicely with methods and properties. But is there also a way to enforce that class Concrete has an attribute 'foo' of type 'list'? I could of course write a 'foo' property, but I was hoping there was a direct way, import sys import abc class Abstract(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self): pass @abc.abstractmethod def __getitem__(self, key): raise NotImplementedError("__getitem__ method required!") @abc.abstractproperty def encoding(self): raise NotImplementedError("encoding property required!") @abc.abstractproperty def foo(self): assert isinstance(self.foo, list) class Concrete(Abstract): def __init__(self): self.foo = [] # it could be solved by making foo a property def __getitem__(self, key): pass @property def encoding(self): return "some encoding" c = Concrete() Traceback (most recent call last): File "C:\TEMP\abc_foo.py", line 46, in c = Concrete() TypeError: Can't instantiate abstract class Concrete with abstract methods foo Regards, Albert-Jan PS: Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From steve at pearwood.info Mon Sep 1 15:59:32 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 23:59:32 +1000 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901015708.GA97686@cskk.homeip.net> References: <20140901011335.GD9293@ando.pearwood.info> <20140901015708.GA97686@cskk.homeip.net> Message-ID: <20140901135932.GH9293@ando.pearwood.info> On Mon, Sep 01, 2014 at 11:57:08AM +1000, Cameron Simpson wrote: > On 01Sep2014 11:13, Steven D'Aprano wrote: > >Just recently, I've customised my interactive Python with a powerful set > >of tab completion commands, similar to that provided by IPython. While > >typing, if I hit tab, it will try to complete the current variable, > >function, module or file name. I don't know how I programmed without it > >all these years :-) > > I must try that sometime. Please do :-) You can get the module from here: http://code.google.com/p/tabhistory/ Or directly using Mercurial. Run this command at the shell: hg clone https://code.google.com/p/tabhistory/ For experts: you can work out what to do next :-) It's a single .py file and it has lots of documentation. For beginners: once you have run the hg comand above, copy the file tabhistory/tabhistory.py somewhere where Python will see it. Then, start the Python interactive interpreter, and run: import tabhistory If that succeeds, it is now running! If it does not, please let me know what errors you get. I am especially interested in the experience of Mac and Windows users. (Windows users: you will need the third-party pyreadline module.) Try it out: at the interactive interpreter, type: imp[TAB] where [TAB] means "press the TAB key". Python should complete the command line and give you "import". Continue to type: import co[TAB][TAB] and Python will print the names of all modules beginning with "co" that it can see. On my system, that is: code codeop colorsys compileall contextlib copy codecs collections commands compiler cookielib copy_reg Keep typing: import coll[TAB] and Python will complete the command to: import collections Additional features: - If you press TAB at the beginning of a line, it will insert an actual tab character. That can be configured if you prefer spaces. - Inside quoted strings, it will complete on file names. - After something like "from module import " pressing TAB will complete on the attributes of module, but only if module has already been imported and is in the sys.modules cache. This is a security feature. - As the name hints at, tabhistory also enables command history. Press the up-arrow repeatedly to call up previous commands, and down-arrow to move forward through the history again. tabhistory also creates two objects for customizing the completion and history functions: from tabhistory import history, completer will let you conveniently work with them. Both are extensively documented. One particularly useful feature: calling the history object history() will display the last 10 (by default) lines in the history. (Question: anyone know how to tell readline to jump straight to a particular history line? M-< goes to the oldest line in the history, and M-> goes to the most recent, but how would I go straight to line 87?) Feedback, suggestions and bug reports will be gratefully accepted. -- Steven From steve at pearwood.info Mon Sep 1 16:13:35 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Sep 2014 00:13:35 +1000 Subject: [Tutor] how import a module upon instantiation of a class? In-Reply-To: <1409579201.2264.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1409579201.2264.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <20140901141334.GI9293@ando.pearwood.info> On Mon, Sep 01, 2014 at 06:46:41AM -0700, Albert-Jan Roskam wrote: > >> def __init__(self): > > global some_nonbuiltin > > import some_nonbuiltin > > Ahh with 'global', thank you! It never crossed my mind that this > should be used in this case. Within functions, 'global' is only > required when the global variable is going to be modified. No! Absolutely not! The "global" keyword is needed when the global *name* is going to be re-bound to a different object, it has nothing to do with modifying objects. Let's see how we might "modify a variable": py> mylist = [] py> def spam(): ... mylist.append(42) # modifies the mylist object ... py> spam() py> spam() py> print mylist [42, 42] Calling spam() doesn't change what the name "mylist" refers to, it's still the same list, but the list does get changed. If you re-bind the name, by default Python treats it as a local variable: py> def eggs(): ... mylist = ["something", "else"] ... py> eggs() py> print mylist [42, 42] You need the global keyword to make eggs() consider "mylist" to be global rather than local: py> def eggs(): # take two ... global mylist ... mylist = ["something", "else"] ... py> eggs() py> print mylist ['something', 'else'] The import statement performs a name binding: it creates a variable with the same name as the module (or the name given by "as"). py> math # name doesn't exist yet Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined py> import math py> math # now the name exists, same as if we said "math = ..." So what happens if you put an import inside a function? It creates a variable with the name of the module. Since it is inside a function, it is a *local* variable, which makes it invisible to anything outside of that module: py> def cheese(): ... import string ... py> cheese() py> string Traceback (most recent call last): File "", line 1, in NameError: name 'string' is not defined To make it a global name, you need the global keyword: py> def cheese(): # take two ... global string ... import string ... py> cheese() py> string -- Steven From jarod_v6 at libero.it Mon Sep 1 16:58:48 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Mon, 1 Sep 2014 16:58:48 +0200 (CEST) Subject: [Tutor] python pipeline Message-ID: <19407077.2307881409583528951.JavaMail.httpd@webmail-07.iol.local> Dear all, I'll try to write a pipeline starting from a csv file where I write the name and the path of my files. example.csv Name,FASTQ1,FASTQ2,DIRECTORY sampleA,A_R1_.fastq.gz,A_R2_.fastq.gz,108,~/FASTQ/ sampleB,B_R1_.fastq.gz,B_R2_.fastq.gz,112,~/FASTQ/ On that list I need to send each time 3 different script whic are depend one to the other. So I need to run1 and only whe it finisched start the second and then the 3. One of the problems teach script write the output only in the same directory where I launch the program so I need to create. I set the output directory and the I want to obtain this folder view . ??? sampleA ??? ??? ref.txt ??? ??? second ??? sampleB ??? ref.txt ??? second I have problems on how to move in different folder and how can use subprocess for execute all. Any idea in how can I do this? def Staralign(file,pos): import subprocess global Path global Read1 global Read2 global Nome global label Read1 = [] Read2 = [] Nome = [] Path = [] label = [] with open(file) as p: for i in p: lines = i.rstrip("\n").split(",") if lines[0] != "Name": Path.append(lines[10]) Nome.append(lines[0]) Read1.append(lines[7]) Read2.append(lines[8]) out = open("toRun.sh","w") out.write("#!/bin/bash\n") global pipe pipe =[] dizionario = {} for i in range(len(Nome)): dx =str("".join(Path[i])+ "/"+ "".join(Read1[i])) sn =str("".join(Path[i])+"/"+"".join(Read2[i])) if not os.path.exists(pos+"/"+i): os.makedirs(pos+"/"+i) print >>out, "cd " + pos +"\n" print >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir /home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn "+ dx +" "+ ""+ sn +" --runThreadN 12 --readFilesCommand zcat " +"\n" step_1_out =["~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir /home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn % s %s --runThreadN 12 --readFilesCommand zcat "%(dx,dn)] print >>out,"cd " +" $PWD"+"/"+ "hg19_second/" +"\n" print >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --runMode genomeGenerate --genomeDir"+" $PWD"+"/"+ "hg19_second/ --genomeFastaFiles ~/databases/bowtie2Database/hg19.fa --sjdbFileChrStartEnd " +"$PWD"+"/"+ "SJ. out.tab" +" --sjdbOverhang 49 --runThreadN 12" +"\n" pipe.append("~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir /home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn "+ dx +" "+ ""+ sn +" --runThreadN 12 --readFilesCommand zcat ") print >>out,"cd .." + "\n" print >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir"+ " $PWD"+"/"+ "hg19_second/GenomeDir/ --runMode alignReads --readFilesIn "+ dx +" "+ ""+ sn +" --runThreadN 12 --readFilesCommand zcat " +"\n" dizionario.setdefault() # return Nome,Path,Read1,Read1 This isthe function I wrote but with this way I'm only able to write a bash script.. From ch.de2.2309 at gmail.com Mon Sep 1 17:13:48 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Mon, 1 Sep 2014 22:13:48 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. Message-ID: Hello, I'm trying to counting vehicle, but I can't increasing it, I use python 2.7.6 and opencv 2.4.9 Here the code: import cv2 bgsMOG = cv2.BackgroundSubtractorMOG2(500,30,True) cap = cv2.VideoCapture("d:\MOV_5680.avi") counter =0 if cap: while True: ret, frame = cap.read() if ret: fgmask = bgsMOG.apply(frame, None, 0.01) cv2.line(frame,(20,170),(320,170),(175,175,0),1) contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) ax1=20 #coordinate of line where vehicle will be count if intersect ay1=170 ax2=320 ay2=170 try: hierarchy = hierarchy[0] except: hierarchy = [] for contour, hier in zip(contours, hierarchy): (x,y,w,h) = cv2.boundingRect(contour) if w > 10 and h > 15: cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) x1=w/2 #to find centroid y1=h/2 cx=x+x1 cy=y+y1 centroid=(cx,cy) cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1) dy=cy-170 #my first code to increase counter if dy==0: if (cx<=320)and(cx>=70): counter=counter+1 if cy==170: cv2.putText(frame, str(counter),(10,150), cv2.FONT_HERSHEY_SIMPLEX,2, (255, 0, 0), 1, True) #cv2.namedWindow('Output',cv2.cv.CV_WINDOW_NORMAL) #cv2.resizeWindow('Output',320,180) cv2.imshow('Output', frame) cv2.imshow('FGMASK', fgmask) key = cv2.waitKey(100) if key == ord('q'): break cap.release() cv2.destroyAllWindows() -------------- next part -------------- An HTML attachment was scrubbed... URL: From ch.de2.2309 at gmail.com Mon Sep 1 17:20:02 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Mon, 1 Sep 2014 22:20:02 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. Message-ID: Hello, I'm trying to counting vehicle, but I can't increasing it, I use python 2.7.6 and opencv 2.4.9 Here the code: import cv2 bgsMOG = cv2.BackgroundSubtractorMOG2(500,30,True) cap = cv2.VideoCapture("d:\MOV_5680.avi") counter =0 if cap: while True: ret, frame = cap.read() if ret: fgmask = bgsMOG.apply(frame, None, 0.01) cv2.line(frame,(20,170),(320,170),(175,175,0),1) contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) ax1=20 #coordinate of line where vehicle will be count if intersect ay1=170 ax2=320 ay2=170 try: hierarchy = hierarchy[0] except: hierarchy = [] for contour, hier in zip(contours, hierarchy): (x,y,w,h) = cv2.boundingRect(contour) if w > 10 and h > 15: cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) x1=w/2 #to find centroid y1=h/2 cx=x+x1 cy=y+y1 centroid=(cx,cy) cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1) dy=cy-170 #my first try to increase counter, not work if dy==0: if (cx<=320)and(cx>=70): counter=counter+1 if cy==170: #my second try to increasing, not work too counter=counter+1 cv2.putText(frame, str(counter),(10,150), cv2.FONT_HERSHEY_SIMPLEX,2, (255, 0, 0), 1, True) cv2.imshow('Output', frame) cv2.imshow('FGMASK', fgmask) key = cv2.waitKey(100) if key == ord('q'): break cap.release() cv2.destroyAllWindows() don't have error but I can't increasing the counter, please help me.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 1 17:55:09 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Sep 2014 16:55:09 +0100 Subject: [Tutor] how import a module upon instantiation of a class? In-Reply-To: <20140901141334.GI9293@ando.pearwood.info> References: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1409579201.2264.YahooMailNeo@web163804.mail.gq1.yahoo.com> <20140901141334.GI9293@ando.pearwood.info> Message-ID: On 01/09/14 15:13, Steven D'Aprano wrote: > To make it a global name, you need the global keyword: > > py> def cheese(): # take two > ... global string > ... import string > ... > py> cheese() > py> string > And co ing back to Albert's original request this little insight made me try something and it seems to work... You can assign the name inside the class, thus providing the class level import that Albert wanted: >>> class C: ... def __init__(self): ... import sys ... self.__sys = sys ... def printSys(self): ... print self.__sys.path ... >>> c = C() >>> sys Traceback (most recent call last): File "", line 1, in NameError: name 'sys' is not defined >>> c.__sys Traceback (most recent call last): File "", line 1, in AttributeError: C instance has no attribute '__sys' >>> c.printSys() ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', ... So now you have a module imported inside a class such that it is only visible inside objects of that class. Now why you would want that I'm less sure, but you can do it... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 1 18:04:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Sep 2014 17:04:04 +0100 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901135932.GH9293@ando.pearwood.info> References: <20140901011335.GD9293@ando.pearwood.info> <20140901015708.GA97686@cskk.homeip.net> <20140901135932.GH9293@ando.pearwood.info> Message-ID: On 01/09/14 14:59, Steven D'Aprano wrote: > (Question: anyone know how to tell readline to jump straight to a > particular history line? M-< goes to the oldest line in the history, and > M-> goes to the most recent, but how would I go straight to line 87?) Bash readline allows backwards searches of history with Ctrl-r - does that work? Not quite the same as goto line I know but maybe it would help? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 1 18:13:38 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Sep 2014 17:13:38 +0100 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: On 01/09/14 16:13, Whees Northbee wrote: > Hello, I'm trying to counting vehicle, but I can't increasing it, I use > python 2.7.6 and opencv 2.4.9 I don;t understand what you mean. There is no vehicle in your code? The code is overly complex for me to read through and it uses a module that I don't have so I'm not even attempting to run it... And it looks like it has a syntax error too - an if block missing. Can you provide more details about what is happening? Also try inserting some print statements so that you can see what your code is doing. That way you might see the problem yourself. > import cv2 > > bgsMOG = cv2.BackgroundSubtractorMOG2(500,30,True) > cap = cv2.VideoCapture("d:\MOV_5680.avi") > counter =0 > if cap: > while True: > ret, frame = cap.read() > > if ret: > fgmask = bgsMOG.apply(frame, None, 0.01) > cv2.line(frame,(20,170),(320,170),(175,175,0),1) > contours, hierarchy = cv2.findContours(fgmask, > cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) > > ax1=20 #coordinate of line where vehicle will be count > if intersect > ay1=170 > ax2=320 > ay2=170 > > try: hierarchy = hierarchy[0] > except: hierarchy = [] > for contour, hier in zip(contours, hierarchy): > (x,y,w,h) = cv2.boundingRect(contour) > if w > 10 and h > 15: > cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) > x1=w/2 #to find centroid > y1=h/2 > cx=x+x1 > cy=y+y1 > centroid=(cx,cy) > cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1) > > dy=cy-170 #my first code to increase counter > if dy==0: > if (cx<=320)and(cx>=70): > counter=counter+1 > > if cy==170: > > cv2.putText(frame, str(counter),(10,150), > cv2.FONT_HERSHEY_SIMPLEX,2, (255, 0, 0), 1, True) > #cv2.namedWindow('Output',cv2.cv.CV_WINDOW_NORMAL) > #cv2.resizeWindow('Output',320,180) > cv2.imshow('Output', frame) > cv2.imshow('FGMASK', fgmask) > > > key = cv2.waitKey(100) > if key == ord('q'): > break > cap.release() > cv2.destroyAllWindows() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Sep 1 18:24:17 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Sep 2014 02:24:17 +1000 Subject: [Tutor] how import a module upon instantiation of a class? In-Reply-To: References: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1409579201.2264.YahooMailNeo@web163804.mail.gq1.yahoo.com> <20140901141334.GI9293@ando.pearwood.info> Message-ID: <20140901162417.GJ9293@ando.pearwood.info> On Mon, Sep 01, 2014 at 04:55:09PM +0100, Alan Gauld wrote: > And co ing back to Albert's original request this little insight made me > try something and it seems to work... > > You can assign the name inside the class, thus providing the class level > import that Albert wanted: > > >>> class C: > ... def __init__(self): > ... import sys > ... self.__sys = sys > ... def printSys(self): > ... print self.__sys.path > ... > >>> c = C() > >>> sys > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sys' is not defined > >>> c.__sys > Traceback (most recent call last): > File "", line 1, in > AttributeError: C instance has no attribute '__sys' That's just Python's regular old "name mangling" in progress. If you create a method or attribute with a name starting with two underscores, but not ending with two underscores, the Python compiler mangles references to it. This is quite lame protection from accidental name clashes, but it can easily be over-come. Try this: c._C__sys Python simply stuffs a single underscore and the name of the class in front of the double leading underscore attribute name. It's enough to prevent 99% of accidental name clashes, but anyone who wants to can defeat it. > >>> c.printSys() > ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', ... > > So now you have a module imported inside a class such that it > is only visible inside objects of that class. Not quite invisible. More like standing in the corner covered with a white sheet. So long as nobody peeks under the sheet, nobody can see it. -- Steven From steve at pearwood.info Mon Sep 1 18:38:17 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Sep 2014 02:38:17 +1000 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: <20140901163817.GK9293@ando.pearwood.info> On Mon, Sep 01, 2014 at 10:20:02PM +0700, Whees Northbee wrote: > for contour, hier in zip(contours, hierarchy): > (x,y,w,h) = cv2.boundingRect(contour) What is the value of y here? Insert a line "print(x, y, w, h)" so you can see what values they take. > if w > 10 and h > 15: Is this condition ever true? Perhaps this block of code never gets executed at all. > cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) > x1=w/2 #to find centroid > y1=h/2 > cx=x+x1 > cy=y+y1 What's the value of cy? > centroid=(cx,cy) > cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1) > dy=cy-170 #my first try to increase counter, not work > if dy==0: > if (cx<=320)and(cx>=70): > counter=counter+1 That's better written as: if 70 <= cx <= 320: counter += 1 > if cy==170: #my second try to increasing, not work too > counter=counter+1 What values does cy take? -- Steven From dyoo at hashcollision.org Mon Sep 1 18:40:03 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 1 Sep 2014 09:40:03 -0700 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: On Sun, Aug 31, 2014 at 5:12 PM, Juan Christian wrote: > I've been using PyCharm to code in Python but it seems a bit "overpowered" > for this task, and there are some annoying bugs. I used Sublime Text 2 in > the past, but it seems to be dead now (last update was JUN/2013), so I don't > really know any good options. > > What do you guys use to code? If you're already familiar with Eclipse, then the PyDev plugin may be appropriate. http://pydev.org/ From juan0christian at gmail.com Mon Sep 1 20:34:53 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 1 Sep 2014 15:34:53 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: Thanks everyone. I will try tabhistory, since I'm using Python 3.4.1 it comes built-in in the IDLE, as the site says, "(Python 3.4 comes with these enabled as standard.)", so, I'll definitely try IDLE. I like PyCharm but I prefer a "calm and clear" environment in order to code. I'll keep using Sublime Text 3 (maybe ST3 isn't dead as I thought) + cmd.exe for coding, and maybe IDLE if I like and feel comfortable about it. On Mon, Sep 1, 2014 at 1:40 PM, Danny Yoo wrote: > On Sun, Aug 31, 2014 at 5:12 PM, Juan Christian > wrote: > > I've been using PyCharm to code in Python but it seems a bit > "overpowered" > > for this task, and there are some annoying bugs. I used Sublime Text 2 in > > the past, but it seems to be dead now (last update was JUN/2013), so I > don't > > really know any good options. > > > > What do you guys use to code? > > > If you're already familiar with Eclipse, then the PyDev plugin may be > appropriate. > > http://pydev.org/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ch.de2.2309 at gmail.com Mon Sep 1 19:54:03 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Tue, 2 Sep 2014 00:54:03 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. Message-ID: >What is the value of y here? (x,y,w,h)=cv2.boundingRect(contour), where x,y is the left up position from contour, and w,h is width and height of contour.. >* if w > 10 and h > 15:* *this code I used, because there's a lot small blob from video shaking, or the movement of trees.. And yes, the condition is true* >* cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) *>* x1=w/2 #to find centroid *>* y1=h/2 *>* cx=x+x1 *>* cy=y+y1* >What's the value of cy? cy and cx is the coordinate of center of rectangle.. the value is cartesian coordinate like (136,60) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ch.de2.2309 at gmail.com Mon Sep 1 20:15:59 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Tue, 2 Sep 2014 01:15:59 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. Message-ID: There's no vehicle in my code, my video just contain vehicles so I think I don't need to use haar classifier, so I'm just do background subtraction to get foreground which is vehicle movement because there's no other movement except vehicle and maybe little movement from trees... I just use opencv module, like to do background subtraction.. No, the code don't have any error. The code is working smoothly to detecting vehicle and make rectangle of vehicle, and I find center point of rectangle at (cx,cy).. I draw manually a line in video at coordinate (20,170) to (320,170).. When each of the rectangle vehicle cross or intersect with that line, I want to count it as 1.. I already try: *)I think, since the line is in the same y coordinate, so if the center (cx,cy), cy=line y coordinate, the count increase if cy==170: counter=counter+1 it doesn't work, no error but the counter stuck at 0 Second try: *)I try to find distance between (cx,cy) and that line, if the distance is 0, counter increase dy=cy-170 #170 is y coordinate of line if dy==0: if (cx<=320) and (cx>=70): counter=counter+1 don't have error, but the counter sometime add sometime no.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 1 20:45:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Sep 2014 19:45:36 +0100 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: On 01/09/14 19:34, Juan Christian wrote: > + cmd.exe for coding, If you are not a cmd.exe regular make sure you read the help page and enable all the extra features that are turned off by default... Things like file and command completion for example. It makes cmd.exe a much more usable place. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From juan0christian at gmail.com Mon Sep 1 21:14:18 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 1 Sep 2014 16:14:18 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: Message-ID: I'm going to test a linter for ST3, but there are tons of options for Python and I got confused. https://sublime.wbond.net/packages/SublimeLinter-pyflakes https://sublime.wbond.net/packages/SublimeLinter-pylint https://sublime.wbond.net/packages/SublimeLinter-pep8 https://sublime.wbond.net/packages/SublimeLinter-pep257 https://sublime.wbond.net/packages/SublimeLinter-flake8 If I remember correctly, PEP8 is a "Style Guide for Python Code", good practices for coding and similar. What about pep257, flak8, pylint, and others? Which one is the best to use/follow? On Mon, Sep 1, 2014 at 3:45 PM, Alan Gauld wrote: > On 01/09/14 19:34, Juan Christian wrote: > > + cmd.exe for coding, >> > > If you are not a cmd.exe regular make sure you read the help page > and enable all the extra features that are turned off by default... > Things like file and command completion for example. > > It makes cmd.exe a much more usable place. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Sep 1 21:34:52 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Sep 2014 05:34:52 +1000 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: <20140901193452.GL9293@ando.pearwood.info> On Tue, Sep 02, 2014 at 12:54:03AM +0700, Whees Northbee wrote: > >What is the value of y here? > (x,y,w,h)=cv2.boundingRect(contour), where x,y is the left up position from > contour, and w,h is width and height of contour.. That's not the value of y. You have just repeated the same line of code that provides the values. What are they? y = 1? y = 100000? Who knows? Do you know what values y has? > >* if w > 10 and h > 15:* > > *this code I used, because there's a lot small blob from video > shaking, or the movement of trees.. And yes, the condition is true* How do you know? > >* cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1) > *>* x1=w/2 #to find centroid > *>* y1=h/2 > *>* cx=x+x1 > *>* cy=y+y1* > > >What's the value of cy? > cy and cx is the coordinate of center of rectangle.. the value is cartesian > coordinate like (136,60) You're testing for cy == 170. If the value of cy is 60, that doesn't equal 170. -- Steven From steve at pearwood.info Mon Sep 1 21:47:36 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Sep 2014 05:47:36 +1000 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: <20140901194736.GM9293@ando.pearwood.info> On Tue, Sep 02, 2014 at 01:15:59AM +0700, Whees Northbee wrote: > There's no vehicle in my code, my video just contain vehicles so I think I > don't need to use haar classifier, so I'm just do background subtraction to > get foreground which is vehicle movement because there's no other movement > except vehicle and maybe little movement from trees... Do you realise that this is a list for learning Python? We're not experts on video analysis. Probably nobody here except you has even the faintest idea what a Haar classifier is or whether you need one or not. > I just use opencv module, like to do background subtraction.. > No, the code don't have any error. If the code doesn't have any errors, then it must be working correctly. > The code is working smoothly to detecting vehicle and make rectangle of > vehicle, How do you know? What part of your code shows you that it is correctly detecting vehicles? > and I find center point of rectangle at (cx,cy).. > I draw manually a line in video at coordinate (20,170) to (320,170).. > When each of the rectangle vehicle cross or intersect with that line, I > want to count it as 1.. > I already try: > > *)I think, since the line is in the same y coordinate, so if the center > (cx,cy), cy=line y coordinate, the count increase > > if cy==170: > counter=counter+1 > > it doesn't work, no error but the counter stuck at 0 How fast are the vehicles moving? What is the resolution of the measurements? > Second try: > *)I try to find distance between (cx,cy) and that line, if the distance is > 0, counter increase > > dy=cy-170 #170 is y coordinate of line > if dy==0: > if (cx<=320) and (cx>=70): > counter=counter+1 > > don't have error, but the counter sometime add sometime no.. Earlier, you said that it never worked. Now you say it sometimes works. Which is correct? There is no difference between: cy == 170 and (cy - 170) == 0 So the question is, how do you know that cy ever equals 170? Suppose the vehicle is moving towards the line. In the first frame, cy = 300. In the second frame, 250. In the third frame, 200. Then, 150, 100, 50 and then it's no longer in the picture. There is never a time that cy == 170. The logic of your code is wrong. You need to think of a different way to solve this problem. Or, I could be completely wrong. I don't know, because I don't understand how this video processing works. I am just guessing. -- Steven From fomcl at yahoo.com Mon Sep 1 22:31:12 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 1 Sep 2014 13:31:12 -0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: <20140901194736.GM9293@ando.pearwood.info> References: <20140901194736.GM9293@ando.pearwood.info> Message-ID: <1409603472.92622.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: Steven D'Aprano > To: tutor at python.org > Cc: > Sent: Monday, September 1, 2014 9:47 PM > Subject: Re: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. > > On Tue, Sep 02, 2014 at 01:15:59AM +0700, Whees Northbee wrote: >> There's no vehicle in my code, my video just contain vehicles so I > think I >> don't need to use haar classifier, so I'm just do background > subtraction to >> get foreground which is vehicle movement because there's no other > movement >> except vehicle and maybe little movement from trees... > > Do you realise that this is a list for learning Python? We're not > experts on video analysis. Probably nobody here except you has even the > faintest idea what a Haar classifier is or whether you need one or not. Yep, never heard about it until today :-) http://en.wikipedia.org/wiki/Haar-like_features From cs at zip.com.au Mon Sep 1 23:35:38 2014 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 2 Sep 2014 07:35:38 +1000 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901135932.GH9293@ando.pearwood.info> References: <20140901135932.GH9293@ando.pearwood.info> Message-ID: <20140901213538.GA17277@cskk.homeip.net> On 01Sep2014 23:59, Steven D'Aprano wrote: >On Mon, Sep 01, 2014 at 11:57:08AM +1000, Cameron Simpson wrote: >> On 01Sep2014 11:13, Steven D'Aprano wrote: >> >Just recently, I've customised my interactive Python with a powerful set >> >of tab completion commands, similar to that provided by IPython. While >> >typing, if I hit tab, it will try to complete the current variable, >> >function, module or file name. I don't know how I programmed without it >> >all these years :-) >> >> I must try that sometime. > >Please do :-) > >You can get the module from here: >http://code.google.com/p/tabhistory/ > >Or directly using Mercurial. Run this command at the shell: >hg clone https://code.google.com/p/tabhistory/ [...] Installed. Wow. That's really handy! Thanks! Cameron Simpson Microsoft Mail: as far from RFC-822 as you can get and still pretend to care. - Abby Franquemont-Guillory From jan9447 at me.com Mon Sep 1 20:14:14 2014 From: jan9447 at me.com (Jan Karel Schreuder) Date: Mon, 01 Sep 2014 14:14:14 -0400 Subject: [Tutor] python launcher Message-ID: <06511782-F2EA-45F5-A555-9706920D6BA0@me.com> Until now I have used IDLE to write and run programs. I decided it was time to do it the hard way and use only a Terminal and a plain text editor, TextWrangler. I have Python 3.4.1 and OS 10.8.5. When I run the script by calling for the interpreter in the terminal with the script as the parameter (e.g. python3 shares.py), it runs fine. This is the output: corrupt record.....removed corrupt record.....removed corrupt record.....removed ['description', 'symbol', 'current price', 'number of units'] List shares Buy shares Sell shares Update prices ridfx 21.98 833.592135342 18322.36 dodfx 46.99 390.964829507 18371.44 dfsvx 36.87 499.060771965 18400.37 pplix 15.42 1189.216568817 18337.72 total 73431.89 However, when I run it by using the Python Launcher, this is the result: corrupt record.....removed corrupt record.....removed corrupt record.....removed ['description', 'symbol', 'current price', 'number of units'] ('\t\t\t', 'List shares') ('\t\t\t', 'Buy shares') ('\t\t\t', 'Sell shares') ('\t\t\t', 'Update prices') ('ridfx', '21.98', '833.592135342', 18322.36) ('dodfx', '46.99', '390.964829507', 18371.44) ('pplix', '15.42', '1189.216568817', 18337.72) ('dfsvx', '36.87', '499.060771965', 18400.37) ('total', 73431.89) Exit status: 0 logout [Process completed] Why the difference ? All the output was taken care of by the Print function. Jan Schreuder From juan0christian at gmail.com Tue Sep 2 02:25:33 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 1 Sep 2014 21:25:33 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <20140901213538.GA17277@cskk.homeip.net> References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> Message-ID: So guys, I'll be using this one ( https://sublime.wbond.net/packages/SublimeLinter-flake8), why? Because acording to Python Package Index ( https://pypi.python.org/pypi/flake8), this linter uses: 1. PyFlakes 2. pep8 3. Ned Batchelder's McCabe script I don't have a clue what the n3 does, but the first two are familiar to me. That's enough for code style and error checking, right? On Mon, Sep 1, 2014 at 6:35 PM, Cameron Simpson wrote: > On 01Sep2014 23:59, Steven D'Aprano wrote: > >> On Mon, Sep 01, 2014 at 11:57:08AM +1000, Cameron Simpson wrote: >> >>> On 01Sep2014 11:13, Steven D'Aprano wrote: >>> >Just recently, I've customised my interactive Python with a powerful set >>> >of tab completion commands, similar to that provided by IPython. While >>> >typing, if I hit tab, it will try to complete the current variable, >>> >function, module or file name. I don't know how I programmed without it >>> >all these years :-) >>> >>> I must try that sometime. >>> >> >> Please do :-) >> >> You can get the module from here: >> http://code.google.com/p/tabhistory/ >> >> Or directly using Mercurial. Run this command at the shell: >> hg clone https://code.google.com/p/tabhistory/ >> > [...] > > Installed. Wow. That's really handy! > > Thanks! > Cameron Simpson > > Microsoft Mail: as far from RFC-822 as you can get and still pretend to > care. > - Abby Franquemont-Guillory > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Sep 2 02:37:34 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Sep 2014 02:37:34 +0200 Subject: [Tutor] python launcher References: <06511782-F2EA-45F5-A555-9706920D6BA0@me.com> Message-ID: Jan Karel Schreuder wrote: > Until now I have used IDLE to write and run programs. I decided it was > time to do it the hard way and use only a Terminal and a plain text > editor, TextWrangler. I have Python 3.4.1 and OS 10.8.5. When I run the > script by calling for the interpreter in the terminal with the script as > the parameter (e.g. python3 shares.py), it runs fine. This is the output: > > corrupt record.....removed > corrupt record.....removed > corrupt record.....removed > ['description', 'symbol', 'current price', 'number of units'] > List shares > Buy shares > Sell shares > Update prices > ridfx 21.98 833.592135342 18322.36 > dodfx 46.99 390.964829507 18371.44 > dfsvx 36.87 499.060771965 18400.37 > pplix 15.42 1189.216568817 18337.72 > total 73431.89 > > However, when I run it by using the Python Launcher, this is the result: > > corrupt record.....removed > corrupt record.....removed > corrupt record.....removed > ['description', 'symbol', 'current price', 'number of units'] > ('\t\t\t', 'List shares') > ('\t\t\t', 'Buy shares') > ('\t\t\t', 'Sell shares') > ('\t\t\t', 'Update prices') > ('ridfx', '21.98', '833.592135342', 18322.36) > ('dodfx', '46.99', '390.964829507', 18371.44) > ('pplix', '15.42', '1189.216568817', 18337.72) > ('dfsvx', '36.87', '499.060771965', 18400.37) > ('total', 73431.89) > Exit status: 0 > logout > > [Process completed] > > Why the difference ? All the output was taken care of by the Print > function. In Python 3 print is a function, so print(1, 2) will invoke print with two arguments and display 1 2 In Python 2 print is a statement, to display the two numbers you have to write print 1, 2 while in print(1, 2) (1, 2) is interpreted as a single argument and the tuple (1, 2) is printed. I'm not familiar with the Mac, so I don't know how to convince the "launcher" to use Python 3 instead of Python 2. I'd try adding #!/usr/bin/env python3 as the first line of your script. From juan0christian at gmail.com Tue Sep 2 04:36:19 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 1 Sep 2014 23:36:19 -0300 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> Message-ID: Forget guys, we have the true winner, Anaconda ( https://sublime.wbond.net/packages/Anaconda) Anaconda turns your Sublime Text 3 in a full featured Python development IDE including autocompletion, code linting, IDE features, autopep8 formating, McCabe complexity checker and Vagrant for Sublime Text 3 using Jedi, PyFlakes, pep8, PyLint, pep257 and McCabe that will never freeze your Sublime Text 3. All I want in one place, better than that only if it codes for me. =p On Mon, Sep 1, 2014 at 9:25 PM, Juan Christian wrote: > So guys, I'll be using this one ( > https://sublime.wbond.net/packages/SublimeLinter-flake8), why? > > Because acording to Python Package Index ( > https://pypi.python.org/pypi/flake8), this linter uses: > > 1. PyFlakes > 2. pep8 > 3. Ned Batchelder's McCabe script > > I don't have a clue what the n3 does, but the first two are familiar to > me. That's enough for code style and error checking, right? > > > On Mon, Sep 1, 2014 at 6:35 PM, Cameron Simpson wrote: > >> On 01Sep2014 23:59, Steven D'Aprano wrote: >> >>> On Mon, Sep 01, 2014 at 11:57:08AM +1000, Cameron Simpson wrote: >>> >>>> On 01Sep2014 11:13, Steven D'Aprano wrote: >>>> >Just recently, I've customised my interactive Python with a powerful >>>> set >>>> >of tab completion commands, similar to that provided by IPython. While >>>> >typing, if I hit tab, it will try to complete the current variable, >>>> >function, module or file name. I don't know how I programmed without it >>>> >all these years :-) >>>> >>>> I must try that sometime. >>>> >>> >>> Please do :-) >>> >>> You can get the module from here: >>> http://code.google.com/p/tabhistory/ >>> >>> Or directly using Mercurial. Run this command at the shell: >>> hg clone https://code.google.com/p/tabhistory/ >>> >> [...] >> >> Installed. Wow. That's really handy! >> >> Thanks! >> Cameron Simpson >> >> Microsoft Mail: as far from RFC-822 as you can get and still pretend to >> care. >> - Abby Franquemont-Guillory >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Tue Sep 2 14:38:34 2014 From: crushed26 at gmail.com (Crush) Date: Tue, 2 Sep 2014 08:38:34 -0400 Subject: [Tutor] private help...interacting with stderr/stdout Message-ID: <08C737CF-5084-4714-8A21-6CC79545FC62@gmail.com> It is becoming too difficult to explain the problems I am having with my code via email. Is anyone willing to help via Skype or Teamviewer...I will pay for your time if need be. Thanks, Bo From ch.de2.2309 at gmail.com Tue Sep 2 16:01:31 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Tue, 2 Sep 2014 21:01:31 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. Message-ID: If all of these confusing, I'll simplify the problem, I need to know if a point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. Can someone tell me how?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 2 19:19:20 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Sep 2014 18:19:20 +0100 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: On 02/09/14 15:01, Whees Northbee wrote: > If all of these confusing, I'll simplify the problem, I need to know > if a point (x,y) exactly at a line where line is (ax1,ay) to > (ax2,ay).. > > Can someone tell me how?? Take the equation of the line and see if x,y fits. The hard bit is that if you are sampling x.y periodically you may never get the points exactly on the line so you may need to settle for determining whether the point crossed the line. That will require that you store the previous coordinates and compare to the new ones to see if they cross ay within the given ax boundaries. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Wed Sep 3 00:52:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 2 Sep 2014 15:52:19 -0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: Hi Whees, You may not be asking your question on an appropriate forum. Python-tutor is meant for beginners to Python programming, not beginners to computer vision. That is, if you're doing a computer vision assignment, the expectation is that you should already know how to program Python at a very high level. Otherwise we get into fairly ridiculous situations where we start questioning whether or not you know about basic arithmetic line/slope formulas or floating-point arithmetic. On Tue, Sep 2, 2014 at 7:01 AM, Whees Northbee wrote: > If all of these confusing, I'll simplify the problem, I need to know if a > point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. Case in point: in the question above, you can't possibly be asking us to help you write a predicate that tells whether a point is on a line. So I have to be misunderstanding your question. You must be asking for a library function in OpenCV, and I'm pretty sure none of us are OpenCV experts. Try asking your question on a forum specialized to OpenCV, such as: http://answers.opencv.org/questions/ From dyoo at hashcollision.org Wed Sep 3 01:04:34 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 2 Sep 2014 16:04:34 -0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: > > On Tue, Sep 2, 2014 at 7:01 AM, Whees Northbee wrote: >> If all of these confusing, I'll simplify the problem, I need to know if a >> point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. > > > Case in point: in the question above, you can't possibly be asking us > to help you write a predicate that tells whether a point is on a line. > So I have to be misunderstanding your question. You must be asking > for a library function in OpenCV, and I'm pretty sure none of us are > OpenCV experts. Ok, found an OpenCV-specific answer about this: http://stackoverflow.com/questions/5596805/opencv-detect-if-points-lie-along-line-plane As expected, this is very domain-specific, and probably not suitable for Python-tutor. From memilanuk at gmail.com Wed Sep 3 09:26:25 2014 From: memilanuk at gmail.com (memilanuk) Date: Wed, 03 Sep 2014 00:26:25 -0700 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> Message-ID: <5406C2A1.3010507@gmail.com> On 09/01/2014 07:36 PM, Juan Christian wrote: > Forget guys, we have the true winner, Anaconda > (https://sublime.wbond.net/packages/Anaconda) > > Anaconda turns your Sublime Text 3 in a full featured Python development > IDE including autocompletion, code linting, IDE features, autopep8 > formating, McCabe complexity checker and Vagrant for Sublime Text 3 > using Jedi, PyFlakes, pep8, PyLint, pep257 and McCabe that will never > freeze your Sublime Text 3. > Weird that they would pick that name given the potential for confusion with this: https://store.continuum.io/cshop/anaconda/ ...unless there is some relation there that I'm missing? I'll admit, I haven't downloaded/installed the Anaconda version of python myself as of yet. -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From memilanuk at gmail.com Wed Sep 3 09:26:25 2014 From: memilanuk at gmail.com (memilanuk) Date: Wed, 03 Sep 2014 00:26:25 -0700 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> Message-ID: <5406C2A1.3010507@gmail.com> On 09/01/2014 07:36 PM, Juan Christian wrote: > Forget guys, we have the true winner, Anaconda > (https://sublime.wbond.net/packages/Anaconda) > > Anaconda turns your Sublime Text 3 in a full featured Python development > IDE including autocompletion, code linting, IDE features, autopep8 > formating, McCabe complexity checker and Vagrant for Sublime Text 3 > using Jedi, PyFlakes, pep8, PyLint, pep257 and McCabe that will never > freeze your Sublime Text 3. > Weird that they would pick that name given the potential for confusion with this: https://store.continuum.io/cshop/anaconda/ ...unless there is some relation there that I'm missing? I'll admit, I haven't downloaded/installed the Anaconda version of python myself as of yet. -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From alan.gauld at btinternet.com Wed Sep 3 09:49:11 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Sep 2014 08:49:11 +0100 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: <5406C2A1.3010507@gmail.com> References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> <5406C2A1.3010507@gmail.com> Message-ID: On 03/09/14 08:26, memilanuk wrote: > On 09/01/2014 07:36 PM, Juan Christian wrote: >> Forget guys, we have the true winner, Anaconda >> (https://sublime.wbond.net/packages/Anaconda) >> > > Weird that they would pick that name given the potential for confusion > with this: > > https://store.continuum.io/cshop/anaconda/ > Looks like 2 different projects, which is unfortunate. I admit I assumed initially it was the same anaconda distribution but the focus seems quite different. I can see how it happened, after all anaconda is a snake too so its an "obvious" name for a Python related project... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From memilanuk at gmail.com Wed Sep 3 11:38:49 2014 From: memilanuk at gmail.com (memilanuk) Date: Wed, 03 Sep 2014 02:38:49 -0700 Subject: [Tutor] Good Text Editor/IDE for Python In-Reply-To: References: <20140901135932.GH9293@ando.pearwood.info> <20140901213538.GA17277@cskk.homeip.net> <5406C2A1.3010507@gmail.com> Message-ID: On 09/03/2014 12:49 AM, Alan Gauld wrote: > I can see how it happened, after all anaconda is a snake too > so its an "obvious" name for a Python related project... True... but about 15 seconds of due diligence searching google beforehand for 'python anaconda' is all they had to do to avoid the name conflict. -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From emile at fenx.com Wed Sep 3 16:28:49 2014 From: emile at fenx.com (Emile van Sebille) Date: Wed, 03 Sep 2014 07:28:49 -0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: On 9/2/2014 7:01 AM, Whees Northbee wrote: > If all of these confusing, I'll simplify the problem, I need to know if a point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. > > Can someone tell me how?? if ax1 Hello, I have a question regarding strings in python. I have a directory on my MacBook Bro of about 13 files. I need to alter the file endings in that directory. The files are on the order of 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I need to remove the characters after the 'v' and replace with v20. All of the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these characters to be the same (i.e. v20). I would like to know which modules are best to use, and how to use loops to alter them. Any help you can provide would be great. Thanks, Felisha Lawrence -- Felisha Lawrence Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student NASA URC/BCCSO Graduate Fellow NOAA NCAS Graduate Fellow Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer (240)-535-6665 (cell) felisha.lawrence at gmail.com (email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Sep 4 21:01:50 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 4 Sep 2014 15:01:50 -0400 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: On Thu, Sep 4, 2014 at 8:49 AM, Felisha Lawrence wrote: > Hello, > I have a question regarding strings in python. I have a directory on my > MacBook Bro of about 13 files. I need to alter the file endings in that > directory. The files are on the order of > 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I > need to remove the characters after the 'v' and replace with v20. All of the > endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these > characters to be the same (i.e. v20). I would like to know which modules are > best to use, and how to use loops to alter them. Any help you can provide > would be great. > > Check out the documentation for os.walk and os.rename. The first to collect you filenames, and the second to rename them. > Thanks, > Felisha Lawrence > > -- > Felisha Lawrence > Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student > NASA URC/BCCSO Graduate Fellow > NOAA NCAS Graduate Fellow > Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer > (240)-535-6665 (cell) > felisha.lawrence at gmail.com (email) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From taserian at gmail.com Thu Sep 4 21:05:32 2014 From: taserian at gmail.com (taserian) Date: Thu, 4 Sep 2014 15:05:32 -0400 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: Is there anything different between the filenames aside from that suffix _vXX? If not, then you'll run into problems after the first filename is changed; further attempts won't allow the change, since there's already a file with that same name. AR On Thu, Sep 4, 2014 at 8:49 AM, Felisha Lawrence wrote: > Hello, > I have a question regarding strings in python. I have a directory on my > MacBook Bro of about 13 files. I need to alter the file endings in > that directory. The files are on the order of > 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. > I need to remove the characters after the 'v' and replace with v20. All of > the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of > these characters to be the same (i.e. v20). I would like to know which > modules are best to use, and how to use loops to alter them. Any help you > can provide would be great. > > > Thanks, > Felisha Lawrence > > -- > Felisha Lawrence > Howard University Program for Atmospheric Sciences(HUPAS), Graduate > Student > NASA URC/BCCSO Graduate Fellow > NOAA NCAS Graduate Fellow > Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer > (240)-535-6665 (cell) > felisha.lawrence at gmail.com (email) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 4 21:16:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2014 20:16:04 +0100 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: On 04/09/14 13:49, Felisha Lawrence wrote: > 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. > I need to remove the characters after the 'v' and replace with v20. All of > the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of > these characters to be the same (i.e. v20). How else will you differentiate them if the files are all the same? Do you need to add a sequence number or do you really want to concateate the files into one big file? > I would like to know which > modules are best to use, and how to use loops to alter them. You can use os.listdir to get all the filenames in a single folder You can use glob.glob to get a subset of the files (using * and ? as wildvards) You can use os.walk to get all the files/folders from a directry tree Once you have the list of files you can use a for loop to access each name. You can the use string.replace() to make simple changes re.sub() to replace regular expressions Or you could use string slicing to replace certain characters based on position, wjhich might work well for your case. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Sep 4 22:22:35 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 4 Sep 2014 13:22:35 -0700 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: > I have a question regarding strings in python. I have a directory on my > MacBook Bro of about 13 files. I need to alter the file endings in that > directory. The files are on the order of > 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I > need to remove the characters after the 'v' and replace with v20. All of the > endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these > characters to be the same (i.e. v20). I would like to know which modules are > best to use, and how to use loops to alter them. Any help you can provide > would be great. Hi Felisha, Do you have any prior programming experience? Your subject line suggests that you are new to Python. Are you familiar with any other programming? Give us more details, and we may be able to provide more appropriate advice. In lack of background information, we will assume for the moment that you have some basic programming skills, and will point to documentation where appropriate. We can point to: https://docs.python.org/2/tutorial/ to get a quick-and-dirty introduction to the language. For the operations you'll be doing, you probably want: 1. Some way to collect the set of file names. The glob module might be appropriate: https://docs.python.org/2/library/glob.html 2. Basic string manipulation skills to map the string: "swp.113006004000_KLWX_0.0.5_PPI_v2" to its replacement string: "swp.113006004000_KLWX_0.0.5_PPI_v20" For this particular pattern matching and string replacement, it might be enough to find the rightmost index for the substring "_v" using a string's rfind() method: https://docs.python.org/2/library/stdtypes.html#str.rfind string slicing (https://docs.python.org/2/tutorial/introduction.html#strings) to chop off the tail, and then a string append to put the replacement "_v20" at the end. For anything more sophisticated, you might want to investigate regular expressions. https://docs.python.org/2/howto/regex.html 3. Functions to interact with the operating system, to tell the operating system to rename a file from the old name to its replacement. Possibly os.rename(): https://docs.python.org/2/library/os.html#os.rename Please feel free to ask more questions. Good luck! From dyoo at hashcollision.org Thu Sep 4 22:27:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 4 Sep 2014 13:27:24 -0700 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: On Thu, Sep 4, 2014 at 12:05 PM, taserian wrote: > Is there anything different between the filenames aside from that suffix > _vXX? If not, then you'll run into problems after the first filename is > changed; further attempts won't allow the change, since there's already a > file with that same name. Ah. Nice catch! Yeah, that's a potential problem with the problem statement. Felisha, please clarify this point, because it's a big one. From cs at zip.com.au Thu Sep 4 23:13:50 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 5 Sep 2014 07:13:50 +1000 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: <20140904211350.GA51278@cskk.homeip.net> On 04Sep2014 15:01, Joel Goldstick wrote: >On Thu, Sep 4, 2014 at 8:49 AM, Felisha Lawrence > wrote: >> I have a question regarding strings in python. I have a directory on my >> MacBook Bro of about 13 files. I need to alter the file endings in that >> directory. The files are on the order of >> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I >> need to remove the characters after the 'v' and replace with v20. All of the >> endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these >> characters to be the same (i.e. v20). I would like to know which modules are >> best to use, and how to use loops to alter them. Any help you can provide >> would be great. >> >> >Check out the documentation for os.walk and os.rename. The first to >collect you filenames, and the second to rename them. os.listdir will be far easier than os.walk if it is a single flat directory. Cheers, Cameron Simpson Knox's box is a 286. Fox in Socks does hacks and tricks Knox's box is hard to fix. To fix poor Knox's box for kicks. - David Mar , as quoted by John Mackin From felisha.lawrence at gmail.com Thu Sep 4 22:32:18 2014 From: felisha.lawrence at gmail.com (Felisha Lawrence) Date: Thu, 4 Sep 2014 16:32:18 -0400 Subject: [Tutor] New to Python..Need help In-Reply-To: References: Message-ID: These are all the files. No two filenames are the same swp.1120630020111.KLWX.0.0.5_PPI_v2 swp.1120630020143.KLWX.0.0.9_PPI_v3 swp.1120630020215.KLWX.0.1.3_PPI_v4 swp.1120630020247.KLWX.0.1.8_PPI_v5 swp.1120630020302.KLWX.0.2.4_PPI_v6 swp.1120630020316.KLWX.0.3.1_PPI_v7 swp.1120630020330.KLWX.0.4.0_PPI_v8 swp.1120630020344.KLWX.0.5.1_PPI_v9 swp.1120630020358.KLWX.0.6.4_PPI_v10 swp.1120630020411.KLWX.0.8.0_PPI_v11 swp.1120630020424.KLWX.0.10.0_PPI_v12 swp.1120630020437.KLWX.0.12.5_PPI_v13 swp.1120630020451.KLWX.0.15.6_PPI_v14 swp.1120630020504.KLWX.0.19.5_PPI_v15 On Thu, Sep 4, 2014 at 4:27 PM, Danny Yoo wrote: > On Thu, Sep 4, 2014 at 12:05 PM, taserian wrote: > > Is there anything different between the filenames aside from that suffix > > _vXX? If not, then you'll run into problems after the first filename is > > changed; further attempts won't allow the change, since there's already a > > file with that same name. > > > Ah. Nice catch! Yeah, that's a potential problem with the problem > statement. Felisha, please clarify this point, because it's a big > one. > -- Felisha Lawrence Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student NASA URC/BCCSO Graduate Fellow NOAA NCAS Graduate Fellow Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer (240)-535-6665 (cell) felisha.lawrence at gmail.com (email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From najam.qasim at yahoo.com Thu Sep 4 22:37:57 2014 From: najam.qasim at yahoo.com (Najam Qasim) Date: Thu, 4 Sep 2014 16:37:57 -0400 Subject: [Tutor] Tutor Digest, Vol 127, Issue 12 In-Reply-To: References: Message-ID: <60D3ED5E-948F-4313-A9C0-C975ABD1330B@yahoo.com> I downloaded notepad++. Can you please help me how to run python script in notepad++? Thanks. Najam > On Sep 4, 2014, at 4:23 PM, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. New to Python..Need help (Felisha Lawrence) > 2. Re: New to Python..Need help (Joel Goldstick) > 3. Re: New to Python..Need help (taserian) > 4. Re: New to Python..Need help (Alan Gauld) > 5. Re: New to Python..Need help (Danny Yoo) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 4 Sep 2014 08:49:04 -0400 > From: Felisha Lawrence > To: tutor at python.org > Subject: [Tutor] New to Python..Need help > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > Hello, > I have a question regarding strings in python. I have a directory on my > MacBook Bro of about 13 files. I need to alter the file endings in > that directory. The files are on the order of > 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. > I need to remove the characters after the 'v' and replace with v20. All of > the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of > these characters to be the same (i.e. v20). I would like to know which > modules are best to use, and how to use loops to alter them. Any help you > can provide would be great. > > > Thanks, > Felisha Lawrence > > -- > Felisha Lawrence > Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student > > NASA URC/BCCSO Graduate Fellow > NOAA NCAS Graduate Fellow > Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer > (240)-535-6665 (cell) > felisha.lawrence at gmail.com (email) > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Thu, 4 Sep 2014 15:01:50 -0400 > From: Joel Goldstick > Cc: "tutor at python.org" > Subject: Re: [Tutor] New to Python..Need help > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Thu, Sep 4, 2014 at 8:49 AM, Felisha Lawrence > wrote: >> Hello, >> I have a question regarding strings in python. I have a directory on my >> MacBook Bro of about 13 files. I need to alter the file endings in that >> directory. The files are on the order of >> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I >> need to remove the characters after the 'v' and replace with v20. All of the >> endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these >> characters to be the same (i.e. v20). I would like to know which modules are >> best to use, and how to use loops to alter them. Any help you can provide >> would be great. > Check out the documentation for os.walk and os.rename. The first to > collect you filenames, and the second to rename them. > >> Thanks, >> Felisha Lawrence >> >> -- >> Felisha Lawrence >> Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student >> NASA URC/BCCSO Graduate Fellow >> NOAA NCAS Graduate Fellow >> Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer >> (240)-535-6665 (cell) >> felisha.lawrence at gmail.com (email) >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > > > -- > Joel Goldstick > http://joelgoldstick.com > > > ------------------------------ > > Message: 3 > Date: Thu, 4 Sep 2014 15:05:32 -0400 > From: taserian > To: Felisha Lawrence > Cc: Tutor > Subject: Re: [Tutor] New to Python..Need help > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > Is there anything different between the filenames aside from that suffix > _vXX? If not, then you'll run into problems after the first filename is > changed; further attempts won't allow the change, since there's already a > file with that same name. > > AR > > > On Thu, Sep 4, 2014 at 8:49 AM, Felisha Lawrence > wrote: > >> Hello, >> I have a question regarding strings in python. I have a directory on my >> MacBook Bro of about 13 files. I need to alter the file endings in >> that directory. The files are on the order of >> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. >> I need to remove the characters after the 'v' and replace with v20. All of >> the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of >> these characters to be the same (i.e. v20). I would like to know which >> modules are best to use, and how to use loops to alter them. Any help you >> can provide would be great. >> >> >> Thanks, >> Felisha Lawrence >> >> -- >> Felisha Lawrence >> Howard University Program for Atmospheric Sciences(HUPAS), Graduate >> Student >> NASA URC/BCCSO Graduate Fellow >> NOAA NCAS Graduate Fellow >> Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer >> (240)-535-6665 (cell) >> felisha.lawrence at gmail.com (email) >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 4 > Date: Thu, 04 Sep 2014 20:16:04 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] New to Python..Need help > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 04/09/14 13:49, Felisha Lawrence wrote: >> >> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. >> I need to remove the characters after the 'v' and replace with v20. All of >> the endings of the files are sequential _v2, _v3,_v4, _v5. I need all of >> these characters to be the same (i.e. v20). > > How else will you differentiate them if the files are all the same? Do > you need to add a sequence number or do you really want to concateate > the files into one big file? > >> I would like to know which >> modules are best to use, and how to use loops to alter them. > > You can use os.listdir to get all the filenames in a single folder > > You can use glob.glob to get a subset of the files > (using * and ? as wildvards) > > You can use os.walk to get all the files/folders from a directry tree > > > Once you have the list of files you can use a for loop to access each name. > > You can the use > > string.replace() to make simple changes > re.sub() to replace regular expressions > > Or you could use string slicing to replace certain characters > based on position, wjhich might work well for your case. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 5 > Date: Thu, 4 Sep 2014 13:22:35 -0700 > From: Danny Yoo > To: Felisha Lawrence > Cc: Python Tutor Mailing List > Subject: Re: [Tutor] New to Python..Need help > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > >> I have a question regarding strings in python. I have a directory on my >> MacBook Bro of about 13 files. I need to alter the file endings in that >> directory. The files are on the order of >> 'swp.113006004000_KLWX_0.0.5_PPI_v2','swp.113006004000_KLWX_0.0.5_PPI_v3'. I >> need to remove the characters after the 'v' and replace with v20. All of the >> endings of the files are sequential _v2, _v3,_v4, _v5. I need all of these >> characters to be the same (i.e. v20). I would like to know which modules are >> best to use, and how to use loops to alter them. Any help you can provide >> would be great. > > Hi Felisha, > > > Do you have any prior programming experience? > > Your subject line suggests that you are new to Python. Are you > familiar with any other programming? Give us more details, and we may > be able to provide more appropriate advice. In lack of background > information, we will assume for the moment that you have some basic > programming skills, and will point to documentation where appropriate. > > > We can point to: > > https://docs.python.org/2/tutorial/ > > to get a quick-and-dirty introduction to the language. > > > > For the operations you'll be doing, you probably want: > > 1. Some way to collect the set of file names. The glob module might > be appropriate: > > https://docs.python.org/2/library/glob.html > > > 2. Basic string manipulation skills to map the string: > > "swp.113006004000_KLWX_0.0.5_PPI_v2" > > to its replacement string: > > "swp.113006004000_KLWX_0.0.5_PPI_v20" > > > For this particular pattern matching and string replacement, it might > be enough to find the rightmost index for the substring "_v" using a > string's rfind() method: > > https://docs.python.org/2/library/stdtypes.html#str.rfind > > string slicing (https://docs.python.org/2/tutorial/introduction.html#strings) > to chop off the tail, and then a string append to put the replacement > "_v20" at the end. > > > For anything more sophisticated, you might want to investigate regular > expressions. > > https://docs.python.org/2/howto/regex.html > > > 3. Functions to interact with the operating system, to tell the > operating system to rename a file from the old name to its > replacement. Possibly os.rename(): > > https://docs.python.org/2/library/os.html#os.rename > > > > Please feel free to ask more questions. Good luck! > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 127, Issue 12 > ************************************** From alan.gauld at btinternet.com Fri Sep 5 00:26:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2014 23:26:54 +0100 Subject: [Tutor] Tutor Digest, Vol 127, Issue 12 In-Reply-To: <60D3ED5E-948F-4313-A9C0-C975ABD1330B@yahoo.com> References: <60D3ED5E-948F-4313-A9C0-C975ABD1330B@yahoo.com> Message-ID: On 04/09/14 21:37, Najam Qasim wrote: Please do not include the entire digest in your mail, especially since none of it seems relevant to your post. Some members pay by the byte. > I downloaded notepad++. Can you please help me how to run python script in notepad++? I only played with notepad++ briefly but I seem to recall it had a menu with commands to 'make' and 'run' a file. You could configure the commands associated with those menus in the settings somewhere. Hopefully somebody who currently uses the editor can provide clearer help. Meantime just save the file and run it from the Windows Explorer or (better) an OS command prompt HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Fri Sep 5 00:45:28 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 4 Sep 2014 15:45:28 -0700 Subject: [Tutor] Tutor Digest, Vol 127, Issue 12 In-Reply-To: References: <60D3ED5E-948F-4313-A9C0-C975ABD1330B@yahoo.com> Message-ID: On Thu, Sep 4, 2014 at 3:26 PM, Alan Gauld wrote: > On 04/09/14 21:37, Najam Qasim wrote: >> I downloaded notepad++. Can you please help me how to run python script in >> notepad++? > > I only played with notepad++ briefly but I seem to recall it had a menu with > commands to 'make' and 'run' a file. You could configure the commands > associated with those menus in the settings somewhere. I use Notepad++ all the time as my go-to text editor - but I don't use it as an IDE precisely, because it doesn't have an integrated interpreter/debugger/etc. There _is_ a Run menu, but it's just a generic program launcher; I think your memory is playing tricks on you as far as a Make command is concerned. Notepad++ does have a large plugin ecosystem, and there may be some IDE-ish plugins out there, but that's not really what the program is meant for. > Hopefully somebody who currently uses the editor can provide clearer help. > Meantime just save the file and run it from the Windows Explorer or (better) > an OS command prompt This would be my advice also. From dyoo at hashcollision.org Fri Sep 5 01:21:27 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 4 Sep 2014 16:21:27 -0700 Subject: [Tutor] Tutor Digest, Vol 127, Issue 12 In-Reply-To: References: <60D3ED5E-948F-4313-A9C0-C975ABD1330B@yahoo.com> Message-ID: >> I downloaded notepad++. Can you please help me how to run python script in >> notepad++? > > > I only played with notepad++ briefly but I seem to recall it had a menu with > commands to 'make' and 'run' a file. You could configure the commands > associated with those menus in the settings somewhere. Potentially relevant: http://stackoverflow.com/questions/1702586/how-to-execute-a-python-file-in-notepad I too have no experience with Notepad++, so hopefully there are others on the list that can chime in. From ch.de2.2309 at gmail.com Fri Sep 5 13:09:45 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Fri, 5 Sep 2014 18:09:45 +0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: I'm really sorry if my post doesn't appropriate to the forum rule.. I already asked in other forums 2 months ago, but no answer or had voted down and closed.. If you ask me about the basic slope formula or basic theory of intersection of point with a line I know, that's why I try with "if" code since the line is have the same y coordinate there's no slope, so I think if the y coordinate point same with y coordinate line no matter the value of x coordinate as long as the y coordinate same, the counter increasing.. but if you're think I'm expert with python because I'm work with computer vision I'm not I'm newbie to both.. I'm sorry.. On Wed, Sep 3, 2014 at 6:04 AM, Danny Yoo wrote: > > > > On Tue, Sep 2, 2014 at 7:01 AM, Whees Northbee > wrote: > >> If all of these confusing, I'll simplify the problem, I need to know if > a > >> point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. > > > > > > Case in point: in the question above, you can't possibly be asking us > > to help you write a predicate that tells whether a point is on a line. > > So I have to be misunderstanding your question. You must be asking > > for a library function in OpenCV, and I'm pretty sure none of us are > > OpenCV experts. > > > Ok, found an OpenCV-specific answer about this: > > > http://stackoverflow.com/questions/5596805/opencv-detect-if-points-lie-along-line-plane > > As expected, this is very domain-specific, and probably not suitable > for Python-tutor. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Sep 5 19:40:43 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 6 Sep 2014 03:40:43 +1000 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: <20140905174043.GQ9293@ando.pearwood.info> On Fri, Sep 05, 2014 at 06:09:45PM +0700, Whees Northbee wrote: > I'm really sorry if my post doesn't appropriate to the forum rule.. I > already asked in other forums 2 months ago, but no answer or had voted down > and closed.. It's not a matter about breaking some rule, but about you getting an answer. Your question is very narrowly specific to a particular software library. Of all the people here, YOU probably know more about it than all the rest of us together. Even though OpenCV *uses* Python, your question is not about Python. It is about computer vision, and we know less than you about computer vision. -- Steven From marc.tompkins at gmail.com Fri Sep 5 19:41:03 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 5 Sep 2014 10:41:03 -0700 Subject: [Tutor] How to count vehicle? I'm trying but my code don't increasing.. In-Reply-To: References: Message-ID: On Fri, Sep 5, 2014 at 4:09 AM, Whees Northbee wrote: > I'm really sorry if my post doesn't appropriate to the forum rule.. I > already asked in other forums 2 months ago, but no answer or had voted down > and closed.. It's not that you've broken a rule. It's just that you're asking on a forum where you're not likely to get an answer, because nobody here (that I am aware of) is an expert in computer vision. The way you phrased the question at first made it sound like you were asking about the basic math - we can help you with that, and with turning that math into Python. But for questions about OpenCV, you're going to have to ask in a place where people actually use OpenCV. It's not a matter of etiquette or forum rules - it's a matter of asking in a place where people can actually answer your question. If you asked in OpenCV forums, and got no answer/voted down... we're sorry, but we can't really help you with that. From dyoo at hashcollision.org Fri Sep 5 21:35:17 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 5 Sep 2014 12:35:17 -0700 Subject: [Tutor] How to detect colinearity? Message-ID: > But if you're think I'm expert with python because I'm work with computer vision > I'm not I'm newbie to both.. Ok. Since you've stated that you are a beginner, we now have to recalibrate how we're answering your questions. In that case, I would strongly suggest going through a basic programming tutorial first, before tackling anything with computer vision. Otherwise, you'll keep getting tripped up on issues that people will assume you already know about. There are several tutorials you can take a look at: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Personally, I like: http://openbookproject.net/thinkcs/python/english2e/ but the other tutorials from the link above should be fine. > If you ask me about the basic slope formula or basic theory of > intersection of point with a line I know, that's why I try with "if" code > since the line is have the same y coordinate there's no slope, so I think if > the y coordinate point same with y coordinate line no matter the value of x > coordinate as long as the y coordinate same, the counter increasing. So you've tried to use the idea of slope, but have discovered that when the line is vertical, using a slope approach does not work on such lines. Yes. That's one of the problems with using the slope approach. There are more general approaches that avoid the whole slope problem, such as: http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment which talks about an alternative approach. The proposed function they use there is: ############################################################# def isBetween(a, b, c): crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y) if abs(crossproduct) > epsilon : return False dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y) * (b.y - a.y) if dotproduct < 0 : return False squaredlengthba = (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y) if dotproduct > squaredlengthba: return False return True ############################################################# where a, b, and c are objects with x and y components. It's more general because it doesn't use division: rather, they use cross products and dot products. Vector arithmetic to the rescue, basically. But note the "epsilon" free variable there: that's an indication that we have to be careful about floating point arithmetic. I used the term "floating point arithmetic" earlier in one of my first replies because I hoped that would trigger concepts that I had assumed that you had learned about already. I saw that you were using exact equality on numbers, and for folks who have done some beginner-style computer arithmetic, the term "floating point arithmetic" should be a big warning sign to be careful about equality. But now that you've said more of your background, I can't assume you know what "floating point" arithmetic means. Please read: https://docs.python.org/2/tutorial/floatingpoint.html for a brief introduction. After reading that, you should have a better understanding as to why your programs not use exact equality when floating point numbers are concerned. From crushed26 at gmail.com Fri Sep 5 22:32:17 2014 From: crushed26 at gmail.com (Bo Morris) Date: Fri, 5 Sep 2014 16:32:17 -0400 Subject: [Tutor] command counter Message-ID: how would I keep track of count for each time a command exectuted? for example... subprocess.Popen("command") && add 1 to count. If count equals n number, do something. I have tried count = 0 count += 1, but count does not seem to be incrementing. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Fri Sep 5 22:40:08 2014 From: crushed26 at gmail.com (Bo Morris) Date: Fri, 5 Sep 2014 16:40:08 -0400 Subject: [Tutor] command counter Message-ID: I think I figured it out... each time I run subprocess.Popen("command"), I also have to count += 1, which adds 1 to count each time the command is run. Is this correct, or is there a better way? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Sep 5 22:51:39 2014 From: davea at davea.name (Dave Angel) Date: Fri, 5 Sep 2014 16:51:39 -0400 (EDT) Subject: [Tutor] command counter References: Message-ID: Bo Morris Wrote in message: > > subprocess.Popen("command") && add 1 to count. If count equals n number, do something. > I have tried count = 0 count += 1, but count does not seem to be incrementing. It would be much better to post the code that "does not seem..." There are many possible reasons that count might not seem to change. For example, are you incrementing inside a function and checking it elsewhere? If so, look up the keyword global, or make count part of the return value. Please show your code. -- DaveA From crushed26 at gmail.com Fri Sep 5 23:32:34 2014 From: crushed26 at gmail.com (Crush) Date: Fri, 5 Sep 2014 17:32:34 -0400 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: References: Message-ID: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Ok nevermind, I did not figure it out. My code... count = 0 while count < 3: count += 1 Subprocess.Popen('command') if count == 3: sys.exit() This does not work as I want it to; it consecutively executes the command three times in a row. I only want it to execute once. However, if there is an error, I want it to try again, but only if count does not equal 3. If count equals 3, i want it to give up and exit or do something else. Bo > On Sep 5, 2014, at 4:40 PM, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: How to count vehicle? I'm trying but my code don't > increasing.. (Whees Northbee) > 2. Re: How to count vehicle? I'm trying but my code don't > increasing.. (Steven D'Aprano) > 3. Re: How to count vehicle? I'm trying but my code don't > increasing.. (Marc Tompkins) > 4. How to detect colinearity? (Danny Yoo) > 5. command counter (Bo Morris) > 6. command counter (Bo Morris) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 5 Sep 2014 18:09:45 +0700 > From: Whees Northbee > To: Danny Yoo > Cc: "tutor at python.org" > Subject: Re: [Tutor] How to count vehicle? I'm trying but my code > don't increasing.. > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > I'm really sorry if my post doesn't appropriate to the forum rule.. I > already asked in other forums 2 months ago, but no answer or had voted down > and closed.. If you ask me about the basic slope formula or basic theory of > intersection of point with a line I know, that's why I try with "if" code > since the line is have the same y coordinate there's no slope, so I think > if the y coordinate point same with y coordinate line no matter the value > of x coordinate as long as the y coordinate same, the counter increasing.. > but if you're think I'm expert with python because I'm work with computer > vision I'm not I'm newbie to both.. I'm sorry.. > > > On Wed, Sep 3, 2014 at 6:04 AM, Danny Yoo wrote: > >>> >>> On Tue, Sep 2, 2014 at 7:01 AM, Whees Northbee >> wrote: >>>> If all of these confusing, I'll simplify the problem, I need to know if >> a >>>> point (x,y) exactly at a line where line is (ax1,ay) to (ax2,ay).. >>> >>> >>> Case in point: in the question above, you can't possibly be asking us >>> to help you write a predicate that tells whether a point is on a line. >>> So I have to be misunderstanding your question. You must be asking >>> for a library function in OpenCV, and I'm pretty sure none of us are >>> OpenCV experts. >> >> >> Ok, found an OpenCV-specific answer about this: >> >> >> http://stackoverflow.com/questions/5596805/opencv-detect-if-points-lie-along-line-plane >> >> As expected, this is very domain-specific, and probably not suitable >> for Python-tutor. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Sat, 6 Sep 2014 03:40:43 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] How to count vehicle? I'm trying but my code > don't increasing.. > Message-ID: <20140905174043.GQ9293 at ando.pearwood.info> > Content-Type: text/plain; charset=us-ascii > >> On Fri, Sep 05, 2014 at 06:09:45PM +0700, Whees Northbee wrote: >> I'm really sorry if my post doesn't appropriate to the forum rule.. I >> already asked in other forums 2 months ago, but no answer or had voted down >> and closed.. > > It's not a matter about breaking some rule, but about you getting an > answer. Your question is very narrowly specific to a particular software > library. Of all the people here, YOU probably know more about it than > all the rest of us together. > > Even though OpenCV *uses* Python, your question is not about Python. It > is about computer vision, and we know less than you about computer > vision. > > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Fri, 5 Sep 2014 10:41:03 -0700 > From: Marc Tompkins > To: Whees Northbee > Cc: "tutor at python.org" > Subject: Re: [Tutor] How to count vehicle? I'm trying but my code > don't increasing.. > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > >> On Fri, Sep 5, 2014 at 4:09 AM, Whees Northbee wrote: >> I'm really sorry if my post doesn't appropriate to the forum rule.. I >> already asked in other forums 2 months ago, but no answer or had voted down >> and closed.. > > It's not that you've broken a rule. It's just that you're asking on a > forum where you're not likely to get an answer, because nobody here > (that I am aware of) is an expert in computer vision. The way you > phrased the question at first made it sound like you were asking about > the basic math - we can help you with that, and with turning that math > into Python. But for questions about OpenCV, you're going to have to > ask in a place where people actually use OpenCV. It's not a matter of > etiquette or forum rules - it's a matter of asking in a place where > people can actually answer your question. If you asked in OpenCV > forums, and got no answer/voted down... we're sorry, but we can't > really help you with that. > > > ------------------------------ > > Message: 4 > Date: Fri, 5 Sep 2014 12:35:17 -0700 > From: Danny Yoo > To: Whees Northbee > Cc: "tutor at python.org" > Subject: [Tutor] How to detect colinearity? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > >> But if you're think I'm expert with python because I'm work with computer vision >> I'm not I'm newbie to both.. > > Ok. Since you've stated that you are a beginner, we now have to > recalibrate how we're answering your questions. > > In that case, I would strongly suggest going through a basic > programming tutorial first, before tackling anything with computer > vision. Otherwise, you'll keep getting tripped up on issues that > people will assume you already know about. > > There are several tutorials you can take a look at: > > https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Personally, I like: > > http://openbookproject.net/thinkcs/python/english2e/ > > but the other tutorials from the link above should be fine. > > > >> If you ask me about the basic slope formula or basic theory of >> intersection of point with a line I know, that's why I try with "if" code >> since the line is have the same y coordinate there's no slope, so I think if >> the y coordinate point same with y coordinate line no matter the value of x >> coordinate as long as the y coordinate same, the counter increasing. > > So you've tried to use the idea of slope, but have discovered that > when the line is vertical, using a slope approach does not work on > such lines. Yes. That's one of the problems with using the slope > approach. > > There are more general approaches that avoid the whole slope problem, such as: > > http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment > > which talks about an alternative approach. The proposed function they > use there is: > > ############################################################# > def isBetween(a, b, c): > crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y) > if abs(crossproduct) > epsilon : return False > > dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y) * (b.y - a.y) > if dotproduct < 0 : return False > > squaredlengthba = (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y) > if dotproduct > squaredlengthba: return False > > return True > ############################################################# > > where a, b, and c are objects with x and y components. It's more > general because it doesn't use division: rather, they use cross > products and dot products. Vector arithmetic to the rescue, > basically. > > > But note the "epsilon" free variable there: that's an indication that > we have to be careful about floating point arithmetic. > > I used the term "floating point arithmetic" earlier in one of my first > replies because I hoped that would trigger concepts that I had assumed > that you had learned about already. > > I saw that you were using exact equality on numbers, and for folks who > have done some beginner-style computer arithmetic, the term "floating > point arithmetic" should be a big warning sign to be careful about > equality. > > But now that you've said more of your background, I can't assume you > know what "floating point" arithmetic means. > > Please read: > > https://docs.python.org/2/tutorial/floatingpoint.html > > for a brief introduction. > > After reading that, you should have a better understanding as to why > your programs not use exact equality when floating point numbers are > concerned. > > > ------------------------------ > > Message: 5 > Date: Fri, 5 Sep 2014 16:32:17 -0400 > From: Bo Morris > To: "tutor at python.org" > Subject: [Tutor] command counter > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > how would I keep track of count for each time a command exectuted? for > example... > > subprocess.Popen("command") && add 1 to count. If count equals n number, do > something. > > I have tried count = 0 count += 1, but count does not seem to be > incrementing. > > Thanks > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 6 > Date: Fri, 5 Sep 2014 16:40:08 -0400 > From: Bo Morris > To: "tutor at python.org" > Subject: [Tutor] command counter > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > I think I figured it out... > > each time I run subprocess.Popen("command"), I also have to count += 1, > which adds 1 to count each time the command is run. Is this correct, or is > there a better way? > > Thanks > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 127, Issue 15 > ************************************** From cs at zip.com.au Sat Sep 6 00:09:58 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 6 Sep 2014 08:09:58 +1000 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> References: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Message-ID: <20140905220958.GA17389@cskk.homeip.net> On 05Sep2014 17:32, Crush wrote: >Ok nevermind, I did not figure it out. My code... > >count = 0 >while count < 3: > count += 1 > Subprocess.Popen('command') >if count == 3: > sys.exit() > >This does not work as I want it to; it consecutively executes the command three times in a row. I only want it to execute once. However, if there is an error, I want it to try again, but only if count does not equal 3. If count equals 3, i want it to give up and exit or do something else. 1: PLease consider getting the list as individual messages instead of a digest. Quoting the whole digest does not provide useful context, and the subject line is terrible. 2: Look at the indentation above: you start 3 processes inside the loop, but never wait for any of them, or examine their exit status (which is the usual criterion for trying again, if you really believe a second attempt will help). 3: Please cut/paste your code instead of retyping it. You spell "Subprocess" above with a capital "S", which it does not have. This leads me to think the above it not your exact running code. Cheers, Cameron Simpson Nonsense. Space is blue, and birds fly through it. - Heisenberg From marc.tompkins at gmail.com Sat Sep 6 00:10:15 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 5 Sep 2014 15:10:15 -0700 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> References: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Message-ID: On Fri, Sep 5, 2014 at 2:32 PM, Crush wrote: > Ok nevermind, I did not figure it out. My code... > > count = 0 > while count < 3: > count += 1 > Subprocess.Popen('command') > if count == 3: > sys.exit() > > This does not work as I want it to; it consecutively executes the command three times in a row. I only want it to execute once. However, if there is an error, I want it to try again, but only if count does not equal 3. If count equals 3, i want it to give up and exit or do something else. I don't know what "command" does, or what an "error" would mean for your purposes - if you want an exact answer, you'll need to provide more detail. However, I'm going to assume that if an "error" occurs, a Python exception of some sort gets raised. If so, here's how I would handle this: count = 0 success = False while (count < 3) and not success: try: Subprocess.Popen('command') success = True except: # (you shouldn't use a bare except, but I don't know what to expect) count +=1 sys.exit() From alan.gauld at btinternet.com Sat Sep 6 00:11:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Sep 2014 23:11:48 +0100 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> References: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Message-ID: On 05/09/14 22:32, Crush wrote: > count = 0 > while count < 3: > count += 1 > Subprocess.Popen('command') This is not real code since 'command' is presumably not the real command and subprocess is not spelled with an 'S'... Its usually better to post real code. > if count == 3: > sys.exit() > > This does not work as I want it to; No, it does what you asked it to. Computers cannot guess your intentions, they only do what you tell them. > I only want it to execute once. However, if there is an error, I want it to try again, > but only if count does not equal 3. Let's translate that to Python count = 1 error = subprocess.Popen('command') # execute once while error and count < 3: # if error and less than 3 error = subprocess.call('command') # on success call() returns zero count += 1 > If count equals 3, i want it to give up and exit or do something else. else: raise SystemExit # or something else Is that the sort of thing? PS If you really must use Popen then detecting the error condition is slightly more work: You need to explicitly assign the Popen object's returncode value to error. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From crushed26 at gmail.com Sat Sep 6 00:42:38 2014 From: crushed26 at gmail.com (Crush) Date: Fri, 5 Sep 2014 18:42:38 -0400 Subject: [Tutor] command counter Message-ID: <6854DF25-A376-45AA-90D7-9B6145CB1291@gmail.com> My code is as follows... count = 0 while count < 3: count += 1 subprocess.Popen('command') if count == 3: sys.exit() 'command' is any command. For testing, I have been using the command 'xterm' just so I can see it opening. As far as error and pertaining to the above code, if I close the xterm window, have it open back up until the counter reaches the specified number. I am basically trying to recreate in python a shell script I use. The current shell script runs a real long avconv/ bmdplay command and if the command stops running, the script will try and rerun it until count equals n number. Again, I am only using xterm temporarily while I try to get the logic correct. Once correct, I can change the command and still have the same outcome...I think. I am not using a function. From crushed26 at gmail.com Sat Sep 6 00:55:54 2014 From: crushed26 at gmail.com (Bo Morris) Date: Fri, 5 Sep 2014 18:55:54 -0400 Subject: [Tutor] command counter Message-ID: Here is the shell script I am trying to recreate in python. Sorry for not posting this with my other emails...I am a bit off today. restart_count=10 count=10 restart=5 while ((count--)); do avconv -v verbose -re -analyzeduration 0 | ./bmdplay -m 2 -f pipe:0 echo "----Retry----" if [[ $count = 1 ]] && [[ $restart != 1 ]]; then sleep 10 ((restart--)) count=$restart_count fi done echo "Gave up" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 6 01:34:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 06 Sep 2014 00:34:54 +0100 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: References: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Message-ID: On 05/09/14 23:11, Alan Gauld wrote: > Let's translate that to Python > > count = 1 > error = subprocess.Popen('command') # execute once oops, that should be subprocess.call() sorry. > while error and count < 3: # if error and less than 3 > error = subprocess.call('command') # on success call() returns zero > count += 1 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sat Sep 6 03:26:47 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 6 Sep 2014 11:26:47 +1000 Subject: [Tutor] Vol 127, Issue 15 In-Reply-To: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> References: <0690BE3D-64FB-4EC6-9EBF-F2899D02F5A4@gmail.com> Message-ID: <20140906012640.GR9293@ando.pearwood.info> On Fri, Sep 05, 2014 at 05:32:34PM -0400, Crush wrote: > Ok nevermind, I did not figure it out. My code... You say "Never mind", which normally means the problem is solved, but then you say it doesn't do what you want. So do you want help or not? :-) > count = 0 > while count < 3: > count += 1 > Subprocess.Popen('command') > if count == 3: > sys.exit() > > This does not work as I want it to; it consecutively executes the > command three times in a row. I only want it to execute once. However, > if there is an error, I want it to try again, but only if count does > not equal 3. If count equals 3, i want it to give up and exit or do > something else. Here is a sketch of what you can do (untested): for count in range(3): result = subprocess.popen("command") if result == 0: # Success! We're done. break # break out of the loop. # Be careful of the indentation here. The next line needs to be # lined up with the "for". else: # We never escaped from the for loop, so the command # never ran successfully. print("Exiting with failure") sys.exit(1) sys.exit(0) # Zero, or blank, means success. Strictly speaking, you don't even need that sys.exit, since Python will exit when it reaches the end of the program. Please don't reply to digests without changing the subject line to something meaningful, and without trimming the unnecessary quoting. I've had to delete about nine pages of quoted text which is irrelevant to your post, all of which I've seen before. The best way is to NOT use digests. They are more trouble than they are worth. -- Steven From davea at davea.name Sat Sep 6 04:46:12 2014 From: davea at davea.name (Dave Angel) Date: Fri, 5 Sep 2014 22:46:12 -0400 (EDT) Subject: [Tutor] command counter References: <6854DF25-A376-45AA-90D7-9B6145CB1291@gmail.com> Message-ID: Crush Wrote in message: > My code is as follows... > > count = 0 > while count < 3: > count += 1 > subprocess.Popen('command') > if count == 3: > sys.exit() > > The line beginning "subp" is indented further than the one before it, so this script would terminate with an indentation error. Once you've fixed that we should look at the if statement. If the count is 3 it calls sys.exit. But of course count is 3, or we wouldn't have finished the while loop. And you terminate anyway when you fall off the end of the script. So why call sys.exit () Finally, if you just want to something 3 times, why not use a for loop? for count in range (3): subproc... -- DaveA From gvdonald at gmail.com Sat Sep 6 01:29:24 2014 From: gvdonald at gmail.com (Gregory Donaldson) Date: Fri, 5 Sep 2014 19:29:24 -0400 Subject: [Tutor] If statement The Python Tutorial 3.4.1 Message-ID: I've tried to copy this example from the Tutorial into the Python Idle, but it doesn't seem to recognize it. 4.1. if Statements? Perhaps the most well-known statement type is the if statement. For example: >>> >>> x = int(input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x = 0... print('Negative changed to zero')... elif x == 0:... print('Zero')... elif x == 1:... print('Single')... else:... print('More')...More This is what it looks like when I try to get it to work. >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: x = 0 print('Negative changed to zero') elif x == 0: SyntaxError: invalid syntax >>> if x < 0: x = 0 print('Negative changed to zero') elif x == 0: -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Sep 6 20:52:57 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 6 Sep 2014 14:52:57 -0400 Subject: [Tutor] If statement The Python Tutorial 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 5, 2014 at 7:29 PM, Gregory Donaldson wrote: > I've tried to copy this example from the Tutorial into the Python Idle, but > it doesn't seem to recognize it. > > 4.1. if Statements? > > Perhaps the most well-known statement type is the if statement. For example: > >>>> > >>>> x = int(input("Please enter an integer: ")) > Please enter an integer: 42 >>>> if x < 0: > ... x = 0 > ... print('Negative changed to zero') > ... elif x == 0: > ... print('Zero') > ... elif x == 1: > ... print('Single') > ... else: > ... print('More') > ... > More > > This is what it looks like when I try to get it to work. > >>>> x = int(input("Please enter an integer: ")) > > Please enter an integer: 42 > >>>> if x < 0: > > x = 0 > > print('Negative changed to zero') > you need to indent the above two statements. Use 4 spaces > elif x == 0: > > SyntaxError: invalid syntax > >>>> if x < 0: > > x = 0 > > print('Negative changed to zero') > > elif x == 0: > > > also, please set your mail to send text In python, indentation matters > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Sun Sep 7 01:49:39 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Sep 2014 00:49:39 +0100 Subject: [Tutor] If statement The Python Tutorial 3.4.1 In-Reply-To: References: Message-ID: On 06/09/14 00:29, Gregory Donaldson wrote: > This is what it looks like when I try to get it to work. > >>>> x = int(input("Please enter an integer: ")) > > Please enter an integer: 42 > >>>> if x < 0: > > x = 0 > > print('Negative changed to zero') I'm guessing that you actually indented the two lines above but not the one below - otherwise you'd get an indentation error by now, not a syntax error below. > elif x == 0: > > SyntaxError: invalid syntax Are you sure this is where you get the syntax error? Or did you maybe hit enter too many times thus ending the if block? It needs to follow this pattern: if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('you typed zero') else: print('alls well') So the if/elif and else lines are all lined up with each other and the indented lines are likewise lined up. And if working in the interactive prompt you must not have blank lines (Note: You can have blanks when creating a program file) Indentation is always important in programming for readability, but in Python its vital for Python to understand your code correctly. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From juan0christian at gmail.com Sun Sep 7 05:00:15 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 7 Sep 2014 00:00:15 -0300 Subject: [Tutor] Good approach regarding classes attributes Message-ID: I'm writing a program that have a 'User' class. This class will have the following attributes: 1. id 2. personaname 3. lastlogoff 4. profileurl 5. avatar 6. realname 7. timecreated 8. loccountrycode I'm thinking about writing something like that: http://pastebin.com/7KHB2qQ8 Is it a good approach, is this phytonic? -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Sep 7 05:01:40 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 7 Sep 2014 00:01:40 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: Ops, sorry. Pastebin @ line 9: It's [JSON response lastlogoff] On Sun, Sep 7, 2014 at 12:00 AM, Juan Christian wrote: > I'm writing a program that have a 'User' class. This class will have the > following attributes: > > 1. id > 2. personaname > 3. lastlogoff > 4. profileurl > 5. avatar > 6. realname > 7. timecreated > 8. loccountrycode > > I'm thinking about writing something like that: > http://pastebin.com/7KHB2qQ8 > > Is it a good approach, is this phytonic? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mariopy at gmx.com Sun Sep 7 05:10:30 2014 From: mariopy at gmx.com (Mario Py) Date: Sat, 06 Sep 2014 21:10:30 -0600 Subject: [Tutor] Programming for Everybody (Python) - Oct 6, University of Michigan Message-ID: <540BCCA6.2070202@gmx.com> Here is another Python course that starts October 6 2014: https://www.coursera.org/course/pythonlearn From alan.gauld at btinternet.com Sun Sep 7 09:52:25 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Sep 2014 08:52:25 +0100 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On 07/09/14 04:00, Juan Christian wrote: > I'm writing a program that have a 'User' class. This class will have the > following attributes: > > 1. id > 2. personaname > 3. lastlogoff > 4. profileurl > 5. avatar > 6. realname > 7. timecreated > 8. loccountrycode > > I'm thinking about writing something like that: http://pastebin.com/7KHB2qQ8 > When its a short bit of code (<100 lines) just put it in the email body... class User(): def __init__(id): self.__id = id [URL Request to call API and get everything using the ID (JSON)] self.__personaname = [JSON response personaname] self.__lastlogoff = [JSON response personaname] [...] This is fine although the question of whether you need the attributes to be private needs to be considered carefully on a per attribute basis. def get_id(): return __id def get_personaname(): return __personaname But this style is not Pythonic. If you have a method that just returns the attribute its better to just make the attribute non-private and allow users to access it directly. In fact even if you wanted to do some processing around the access, rather than have lots of getXXX methods it would be more Pythonic to write get/set methods but then declare the attribute as a property and hide the get/set methods so that, to the user, it looks like direct access. get/set methods are a very Java-ish kind of style but not really Pythonic. For most cases direct access is preferred. Also, as a matter of style/convention, the class name is usually CamelCased so it would be class User: Similarly attribute names are usually spaced using underscores so personaname becomes persona_name etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sun Sep 7 10:04:25 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Sep 2014 10:04:25 +0200 Subject: [Tutor] Good approach regarding classes attributes References: Message-ID: Juan Christian wrote: > I'm writing a program that have a 'User' class. This class will have the > following attributes: > > 1. id > 2. personaname > 3. lastlogoff > 4. profileurl > 5. avatar > 6. realname > 7. timecreated > 8. loccountrycode > > I'm thinking about writing something like that: > class User(): > > def __init__(id): > self.__id = id > > [URL Request to call API and get everything using the ID (JSON)] > > self.__personaname = [JSON response personaname] > [...] > > def get_id(): > return __id > > def get_personaname(): > return __personaname > > [...] > Is it a good approach, is this phytonic? It's not a good approach and it's not pythonic. In Python you should avoid accessor functions and (pseudo-)private __attributes ("Python is not Java"). So class User: def __init__(self, id): self.id = id # load attributes self.personname = [personname from JSON] ... user = User(42) is certainly better. You might also consider making the class less dependent of the way you acquire the corresponding data: class User: # in Python 2: class User(object): ... def __init__(self, id, personname, ...) self.id = id self.personname = personname ... @classmethod def from_id(class_, id): # load attributes return User(id, personname, ...) jeff = User(42, "Jeff", ...) jack = User.from_id(43) From juan0christian at gmail.com Sun Sep 7 15:08:09 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 7 Sep 2014 10:08:09 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On Sun, Sep 7, 2014 at 5:04 AM, Peter Otten <__peter__ at web.de> wrote: > > It's not a good approach and it's not pythonic. > > In Python you should avoid accessor functions and (pseudo-)private > __attributes ("Python is not Java"). So > > class User: > def __init__(self, id): > self.id = id > # load attributes > self.personname = [personname from JSON] > ... > > user = User(42) > > is certainly better. You might also consider making the class less > dependent > of the way you acquire the corresponding data: > > class User: # in Python 2: class User(object): ... > def __init__(self, id, personname, ...) > self.id = id > self.personname = personname > ... > @classmethod > def from_id(class_, id): > # load attributes > return User(id, personname, ...) > > jeff = User(42, "Jeff", ...) > jack = User.from_id(43) Ok, no pseudo-private attributes. I read it in tutorials from 2013 and in the course that I'm taking that this would be a good pythonic way to deal with class attributes. They wouldn't be truly private, but someone using the program would see the " __ " in the beginning of the attribute and wouldn't call it directly, "because we are all adults and such", you saying that this approach doesn't exist in real life? I can't give all the 8 attributes to '__init__' because I don't even have them. I would call it with ID only and them the API server would return me all the info, and then I would set them. I didn't learn '@classmethod' decoration yet, but I presume it would work as a 'get()', right? The thing is, where 'user with id 43' is stored? You get it using 'from_id' but we don't have any list in there the store users, I got confused in that part. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Sep 7 16:06:01 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Sep 2014 16:06:01 +0200 Subject: [Tutor] Good approach regarding classes attributes References: Message-ID: Juan Christian wrote: > On Sun, Sep 7, 2014 at 5:04 AM, Peter Otten <__peter__ at web.de> wrote: >> >> It's not a good approach and it's not pythonic. >> >> In Python you should avoid accessor functions and (pseudo-)private >> __attributes ("Python is not Java"). So >> >> class User: >> def __init__(self, id): >> self.id = id >> # load attributes >> self.personname = [personname from JSON] >> ... >> >> user = User(42) >> >> is certainly better. You might also consider making the class less >> dependent >> of the way you acquire the corresponding data: >> >> class User: # in Python 2: class User(object): ... >> def __init__(self, id, personname, ...) >> self.id = id >> self.personname = personname >> ... >> @classmethod >> def from_id(class_, id): >> # load attributes >> return User(id, personname, ...) >> >> jeff = User(42, "Jeff", ...) >> jack = User.from_id(43) > > > > Ok, no pseudo-private attributes. I read it in tutorials from 2013 and in > the course that I'm taking that this would be a good pythonic way to deal > with class attributes. They wouldn't be truly private, but someone using > the program would see the " __ " in the beginning of the attribute and > wouldn't call it directly, "because we are all adults and such", you > saying that this approach doesn't exist in real life? The double underscore plus name mangling is mainly to avoid name collisions in subclasses; to signal "this is private" a single underscore would suffice. But you then go on to make the attribute public via a a getter. In that case my first choice are normal attributes so that you can write print(user.personname) # pythonic instead of print(user.get_personname()) # Javaism If you want to prohibit the user from doing user.personname = "Frankenstein" because the new name is not propagated to the database and the assignment puts your application into an inconsistent state which you want to avoid by some "bondage and discipline" you can change personname into a property: class User: def __init__(self, id): ... self._personname = [as extracted from the JSON] @property def personname(self): return self._personname user = User(42) print(user.personname) # implicitly calls the personname(self) method > I can't give all the 8 attributes to '__init__' because I don't even have > them. At least not now ;) My suggestion would decouple creation of the User instance and fetching of user-related data from a server. > I would call it with ID only and them the API server would return me > all the info, and then I would set them. I didn't learn '@classmethod' > decoration yet, but I presume it would work as a 'get()', right? The thing > is, where 'user with id 43' is stored? You get it using 'from_id' but we > don't have any list in there the store users, I got confused in that part. Maybe it becomes clearer with a small change. Instead of the classmethod you could use a normal function: class User: def __init__(self, id, personname, ...): self.id = id self.personname = personname ... def fetch_user_from_server(id): json_user = fetch data_from_server(id) return User(id, json_user["personname"], ...) jim = fetch_user_from_server(42) If you should later decide that you want to provide a way to allow entering new users you could use the User class for that, too: def create_new_user(): personname = input("Name: ") # in real code this would rather be a # gui dialog or web page ... return User(None, personname, ...) new_guy = create_new_user() save_user_to_server(new_guy) You don't have to worry that the __init__() method tries to load data for an inexistent user. But even if you are sure you'll never do that it is still a good idea to keep concerns separate, if only to write independent unit tests for the User class and the server access. From juan0christian at gmail.com Sun Sep 7 19:07:48 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 7 Sep 2014 14:07:48 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: > > > On Sun, Sep 7, 2014 at 5:04 AM, Peter Otten <__peter__ at web.de> wrote: > > > I would call it with ID only and them the API server would return me > > all the info, and then I would set them. I didn't learn '@classmethod' > > decoration yet, but I presume it would work as a 'get()', right? The > thing > > is, where 'user with id 43' is stored? You get it using 'from_id' but we > > don't have any list in there the store users, I got confused in that > part. > > Maybe it becomes clearer with a small change. Instead of the classmethod > you > could use a normal function: > > class User: > def __init__(self, id, personname, ...): > self.id = id > self.personname = personname > ... > > def fetch_user_from_server(id): > json_user = fetch data_from_server(id) > return User(id, json_user["personname"], ...) > > jim = fetch_user_from_server(42) > I'll definitely use the '@property' decoration. Thanks for the tip, so, a different module to accommodate all the API requests and one for the logic/code itself is a better approach, right? > If you should later decide that you want to provide a way to allow entering > new users you could use the User class for that, too: > > def create_new_user(): > personname = input("Name: ") # in real code this would rather be a > # gui dialog or web page > ... > return User(None, personname, ...) > > new_guy = create_new_user() > save_user_to_server(new_guy) > > You don't have to worry that the __init__() method tries to load data for > an > inexistent user. > > But even if you are sure you'll never do that it is still a good idea to > keep concerns separate, if only to write independent unit tests for the > User > class and the server access. Creating new users won't exist, my program is like a Home Broker using the Steam API. This 'User' class will be mainly used to properly store the users data, I'll automatically and recursively go trough my (or any person) friend-list and fetch users info and inventory and properly use it in my favor. Here is an example of JSON response from the Steam API: { "response": { "players": [ { "steamid": "76561198067618735", "communityvisibilitystate": 3, "profilestate": 1, "personaname": "wildee14", "lastlogoff": 1410065399, "commentpermission": 1, "profileurl": "http://steamcommunity.com/id/wildee14/", "avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/da/da259bfaef7fe7c2521de78433977a6c006217c5.jpg", "avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/da/da259bfaef7fe7c2521de78433977a6c006217c5_medium.jpg", "avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/da/da259bfaef7fe7c2521de78433977a6c006217c5_full.jpg", "personastate": 0, "realname": "wildee", "primaryclanid": "103582791429571843", "timecreated": 1342807007, "personastateflags": 0, "loccountrycode": "US" } ] } } -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Sep 7 20:01:01 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 8 Sep 2014 04:01:01 +1000 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: <20140907180051.GU9293@ando.pearwood.info> On Sun, Sep 07, 2014 at 12:00:15AM -0300, Juan Christian wrote: > I'm writing a program that have a 'User' class. This class will have the > following attributes: > > 1. id > 2. personaname > 3. lastlogoff > 4. profileurl > 5. avatar > 6. realname > 7. timecreated > 8. loccountrycode > > I'm thinking about writing something like that: http://pastebin.com/7KHB2qQ8 For small code snippets, just include it in the body of your email. This is a small code snippet :-) class User(): def __init__(id): self.__id = id [URL Request to call API and get everything using the ID (JSON)] self.__personaname = [JSON response personaname] self.__lastlogoff = [JSON response personaname] [...] def get_id(): return __id def get_personaname(): return __personaname > Is it a good approach, is this phytonic? Nope, it's more like Java than Python. And it's buggy. Here are some questions you should ask yourself: - Are you likely to subclass User? If you do subclass, is it reasonable to treat the fields as part of the public API? - Why are coupling the User class to the database? That makes it hard to separate the construction of a User (say, for testing) from database lookups. This is my suggestion for a Pythonic approach, with some of the bugs fixed, and using more Pythonic naming conventions. class User(object): # Class attribute is shared by all instances. _database = XXX # reference to a database def __init__(self, id, persona_name, last_logoff, profile_url, avatar, real_name, time_created, loc_country_code): # Data validation is left as an exercise. self.id = id self.persona_name = persona_name self.last_logoff = last_logoff # [etc. ...] @classmethod def fromid(cls, id): args = cls._database.lookup_by_id(id) # or some method return cls(*args) And that's pretty much it for the initial version. Some features: - There is a class attribute (and therefore shared by all instances) called _database. In the Java world, I think that would be called a "static variable". The leading underscore makes it a private attribute by convention. By making this an attribute rather than hard-coding it inside methods, it makes it easy to override during testing: saved_database = User._database User._database = Mock() # continue as usual, with no further changes needed # when you are done: User._database = saved_database - The initialiser method __init__ takes eight explicit arguments, plus "self". This enables you to create instances without reading them from the database, e.g. creating them on the fly, reading from an INI file, or any other source. This is especially useful during testing. However, the downside of this is that you need to add argument validation, since you can no longer assume the database has validated all the values. Or, you can just trust the caller knows what they are doing. - There's an alternative constuctor offered, to support the case where you do want to read the arguments from the database. So you can create Users two ways: instance = User(1234, 'fred', ...) # provide all the arguments instance = User.fromid(1234) # or via database lookup We can extend this minimal version. Suppose you want writing to the attributes to update the database. We do this by making all the attributes computed properties, with an extra private method. class User(object): # Class attribute is shared by all instances. _database = XXX # reference to a database # The init method stays the same. def __init__(self, id, persona_name, last_logoff, profile_url, avatar, real_name, time_created, loc_country_code): # Data validation is left as an exercise. self.id = id self.persona_name = persona_name self.last_logoff = last_logoff # [etc. ...] # But now we add a bunch of properties. def _get_id(self): [URL Request to call API and get everything using the ID (JSON)] self.__personaname = [JSON response personaname] self.__lastlogoff = [JSON response personaname] [...] def get_id(): return __id def get_personaname(): return __personaname > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Sep 7 20:12:14 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 8 Sep 2014 04:12:14 +1000 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: <20140907180051.GU9293@ando.pearwood.info> References: <20140907180051.GU9293@ando.pearwood.info> Message-ID: <20140907181214.GV9293@ando.pearwood.info> On Mon, Sep 08, 2014 at 04:01:01AM +1000, Steven D'Aprano wrote a bunch of stuff about the User class... Ah, sorry guys, I did *not* intend to send that post. It's probably a bit incoherent, and certainly unfinished. I hit the wrong key and my mail program sent it. If I get time to finish it tomorrow, I'll resend it. (But, alas, I probably won't. Sorry.) -- Steven From juan0christian at gmail.com Mon Sep 8 04:31:52 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 7 Sep 2014 23:31:52 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: <20140907181214.GV9293@ando.pearwood.info> References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: So... I tried to follow all what you guys said: user.py module: import urllib.request import json class User(): def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar, timecreated, loccountrycode): self._steamid = steamid self._personaname = personaname self._lastlogoff = lastlogoff self._profileurl = profileurl self._avatar = avatar self._timecreated = timecreated self._loccountrycode = loccountrycode @property def steamid(self): return self._steamid @property def personaname(self): return self._personaname @property def lastlogoff(self): return self._lastlogoff @property def profileurl(self): return self._profileurl @property def _avatar(self): return self._avatar @property def _timecreated(self): return self._timecreated @property def _loccountrycode(self): return self._loccountrycode def fetch_user(steamid): req = urllib.request.urlopen(' http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9F55D955257F1EDC9B6D217B94FCD20&steamids=' + steamid) content = json.loads(req.read().decode('utf-8'))["response"]["players"][0] print("DEBUG ONLY: " + content["avatar"] + "\n") return User(content["steamid"], content["personaname"], content["lastlogoff"], content["profileurl"], content["avatar"], content["timecreated"], content["loccountrycode"]) main module: from user import User u = User.fetch_user("76561198067618735") print(u) console output: DEBUG ONLY: http://media.steampowered.com/steamcommunity/public/images/avatars/da/da259bfaef7fe7c2521de78433977a6c006217 c5.jpg Traceback (most recent call last): File ".\main.py", line 3, in u = User.fetch_user("76561198067618735") File "D:\Documents\HomeBroker\user.py", line 50, in fetch_user return User(content["steamid"], content["personaname"], content["lastlogoff"], content["profileurl"], content["avata r"], content["timecreated"], content["loccountrycode"]) File "D:\Documents\HomeBroker\user.py", line 11, in __init__ self._avatar = avatar AttributeError: can't set attribute Why am I getting this "AttributeError: can't set attribute" specifically when trying to set 'self._avatar = avatar'? Does my code in user.py module follows the pythonic way now? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Sep 8 04:49:38 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 7 Sep 2014 22:49:38 -0400 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: On Sun, Sep 7, 2014 at 10:31 PM, Juan Christian wrote: > So... I tried to follow all what you guys said: > > user.py module: > > import urllib.request > import json > > class User(): > > def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar, > timecreated, loccountrycode): > self._steamid = steamid > self._personaname = personaname > self._lastlogoff = lastlogoff > self._profileurl = profileurl > self._avatar = avatar > self._timecreated = timecreated > self._loccountrycode = loccountrycode > > > @property > def steamid(self): > return self._steamid I don't understand the purpose of the decorator and the _business why not self.timecreated = timecreated etc? > > @property > def personaname(self): > return self._personaname > Unless the formatting got screwed up in the email, all or these return statements need to be indented > @property > def lastlogoff(self): > return self._lastlogoff > > @property > def profileurl(self): > return self._profileurl > > @property > def _avatar(self): > return self._avatar > > @property > def _timecreated(self): > return self._timecreated > > @property > def _loccountrycode(self): > return self._loccountrycode > > > def fetch_user(steamid): > req = > urllib.request.urlopen('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9F55D955257F1EDC9B6D217B94FCD20&steamids=' > + steamid) > content = json.loads(req.read().decode('utf-8'))["response"]["players"][0] > print("DEBUG ONLY: " + content["avatar"] + "\n") try this: print content > > return User(content["steamid"], content["personaname"], > content["lastlogoff"], content["profileurl"], content["avatar"], > content["timecreated"], content["loccountrycode"]) > > > main module: > > from user import User > > u = User.fetch_user("76561198067618735") > print(u) > > > console output: > > DEBUG ONLY: > http://media.steampowered.com/steamcommunity/public/images/avatars/da/da259bfaef7fe7c2521de78433977a6c006217 > c5.jpg > > Traceback (most recent call last): > File ".\main.py", line 3, in > u = User.fetch_user("76561198067618735") > File "D:\Documents\HomeBroker\user.py", line 50, in fetch_user > return User(content["steamid"], content["personaname"], > content["lastlogoff"], content["profileurl"], content["avata > r"], content["timecreated"], content["loccountrycode"]) > File "D:\Documents\HomeBroker\user.py", line 11, in __init__ > self._avatar = avatar > AttributeError: can't set attribute > > > Why am I getting this "AttributeError: can't set attribute" specifically > when trying to set 'self._avatar = avatar'? Why not print out all of the content data. Something around avatar might look strange. > > Does my code in user.py module follows the pythonic way now? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Mon Sep 8 05:01:36 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 7 Sep 2014 20:01:36 -0700 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: >> @property >> def _avatar(self): >> return self._avatar Hi Joel, The above code looks strange to me. The method and the field name should not use the same name. From joel.goldstick at gmail.com Mon Sep 8 05:08:50 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 7 Sep 2014 23:08:50 -0400 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: On Sun, Sep 7, 2014 at 11:01 PM, Danny Yoo wrote: >>> @property >>> def _avatar(self): >>> return self._avatar > > Hi Joel, > > The above code looks strange to me. The method and the field name > should not use the same name. ah! good catch Danny. I didn't write it, I was commenting on the OP code. But (and maybe this was discussed earlier in the thread), what value is using the property decorator instead of just saving the data to attributes? -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Mon Sep 8 06:01:51 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 7 Sep 2014 21:01:51 -0700 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: >>>> @property >>>> def _avatar(self): >>>> return self._avatar >> >> Hi Joel, >> >> The above code looks strange to me. The method and the field name >> should not use the same name. > > ah! good catch Danny. I didn't write it, I was commenting on the OP code. > > But (and maybe this was discussed earlier in the thread), what value > is using the property decorator instead of just saving the data to > attributes? Let's first point to documentation that says what "property" is: https://docs.python.org/2/library/functions.html#property If you read it a bit, one of the key terms that should come up is "managed attribute". What do they mean by this? A managed attribute is an attribute that the class's definition actively controls. Let's use a concrete example: say that we'd like to make sure a Person's name is always capitalized. We might try to enforce this capitalization property in the constructor. ############################### class Person(object): def __init__(self, name): self.name = name.title() def greet(self): print("Hi, I'm %s" % self.name) p = Person("joel goldstick") p.greet() ############################### However, this does not stop clients from assigning directly to the name, ##################### p.name = "joel goldstick" ##################### and therefore breaking a desire to keep the name capitalized. So this might be a problem. So what we'd like is the following: to make sure that there's some kind of program logic that kicks in whenever we assign to Person.name. In some programming languages, we do this by marking the attribute name in some way that makes it clear not to access it directly, and we provide "setter" and "getter" methods, the code that can "manage" this attribute. ############################# class Person(object): def __init__(self, name): self._name = name.title() def getName(self): return self._name def setName(self, name): self._name = name.title() def greet(self): print("Hi, I'm %s" % self._name) ## client code: p = Person("joel goldstick") print(p.getName()) p.greet() p.setName("juan christian") print(p.getName()) p.greet() ############################# Python allows us to get "setter" and "getter"-like behavior while still allowing client code to use the attribute with what looks like direct attribute access: ################################# class Person(object): def __init__(self, name): self._name = name.title() @property def name(self): return self._name @name.setter def name(self, newName): self._name = newName.title() def greet(self): print("Hi, I'm %s" % self._name) ## client code: p = Person("joel goldstick") print(p.name) p.greet() p.name= "juan christian" print(p.name) p.greet() ################################# where now the client code looks simpler, but the class definition still gets to manage the attribute's value. Hopefully that helps to make the suggestions in this thread a little more understandable in context. Python's properties allow us to make the client code look direct but still allow for attribute management. From alan.gauld at btinternet.com Mon Sep 8 07:36:23 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Sep 2014 06:36:23 +0100 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: On 08/09/14 03:31, Juan Christian wrote: > @property > def steamid(self): > return self._steamid Unless you specifically *need* these fields to be read-only you don't need the property declarations. Just use the _XXX convention to signal that they are *intended* to be private and allow clients to access them as myuser._persona_name Also note the underscore. It improves readability to break multi-words like that. For example several others have quoted this as 'person name' rather than 'persona name' - quite a different concept but hard to spot when all one word... > File "D:\Documents\HomeBroker\user.py", line 11, in __init__ > self._avatar = avatar > AttributeError: can't set attribute Thats because you set the property name to the field name. Notice the difference: @property def profileurl(self): return self._profileurl @property def _avatar(self): return self._avatar The first sets the property to the non-underscore version The second uses underscore for both property and field name, thus making the field read-only. Be careful what you wish for... Another reason to only use properties when you *need* to make them read only (or to do some processing on reads or writes) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Sep 8 10:58:34 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Sep 2014 10:58:34 +0200 Subject: [Tutor] Good approach regarding classes attributes References: Message-ID: Juan Christian wrote: > I'll definitely use the '@property' decoration. Thanks for the tip, Personally I'd use normal attributes, though. > so, a > different module to accommodate all the API requests and one for the > logic/code itself is a better approach, right? A separate function or method should be sufficient. > Creating new users won't exist, my program is like a Home Broker using the > Steam API. This 'User' class will be mainly used to properly store the > users data, I'll automatically and recursively go trough my (or any > person) friend-list and fetch users info and inventory and properly use it > in my favor. It is always a good idea to give such background right from the start. There are existing wrappers of that API. You might adopt one or at least have a look at the code to see how they are solving the issues you encounter. From s.shall at virginmedia.com Mon Sep 8 13:14:24 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Mon, 08 Sep 2014 13:14:24 +0200 Subject: [Tutor] Use of "getter" and "setter" attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: <540D8F90.8020409@virginmedia.com> On 08/09/2014 06:01, Danny Yoo wrote: >>>>> @property >>>>> def _avatar(self): >>>>> return self._avatar >>> Hi Joel, >>> >>> The above code looks strange to me. The method and the field name >>> should not use the same name. >> ah! good catch Danny. I didn't write it, I was commenting on the OP code. >> >> But (and maybe this was discussed earlier in the thread), what value >> is using the property decorator instead of just saving the data to >> attributes? > > Let's first point to documentation that says what "property" is: > > https://docs.python.org/2/library/functions.html#property > > If you read it a bit, one of the key terms that should come up is > "managed attribute". > > What do they mean by this? > > A managed attribute is an attribute that the class's definition > actively controls. > > Let's use a concrete example: say that we'd like to make sure a > Person's name is always capitalized. We might try to enforce this > capitalization property in the constructor. > > ############################### > class Person(object): > def __init__(self, name): > self.name = name.title() > def greet(self): > print("Hi, I'm %s" % self.name) > > p = Person("joel goldstick") > p.greet() > ############################### > > However, this does not stop clients from assigning directly to the name, > > ##################### > p.name = "joel goldstick" > ##################### > > and therefore breaking a desire to keep the name capitalized. So this > might be a problem. > > So what we'd like is the following: to make sure that there's some > kind of program logic that kicks in whenever we assign to Person.name. > > In some programming languages, we do this by marking the attribute > name in some way that makes it clear not to access it directly, and we > provide "setter" and "getter" methods, the code that can "manage" this > attribute. > > ############################# > class Person(object): > def __init__(self, name): > self._name = name.title() > > def getName(self): > return self._name > > def setName(self, name): > self._name = name.title() > > def greet(self): > print("Hi, I'm %s" % self._name) > > ## client code: > p = Person("joel goldstick") > print(p.getName()) > p.greet() > > p.setName("juan christian") > print(p.getName()) > p.greet() > ############################# > > > Python allows us to get "setter" and "getter"-like behavior while > still allowing client code to use the attribute with what looks like > direct attribute access: > > ################################# > class Person(object): > def __init__(self, name): > self._name = name.title() > > @property > def name(self): > return self._name > > @name.setter > def name(self, newName): > self._name = newName.title() > > def greet(self): > print("Hi, I'm %s" % self._name) > > ## client code: > p = Person("joel goldstick") > print(p.name) > p.greet() > > p.name= "juan christian" > print(p.name) > p.greet() > ################################# > > where now the client code looks simpler, but the class definition > still gets to manage the attribute's value. > > > Hopefully that helps to make the suggestions in this thread a little > more understandable in context. Python's properties allow us to make > the client code look direct but still allow for attribute management. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > I was taught to [generally] always use getter and setter, and I have found this clear and useful. But I am a beginner, so my question is whether there there are any other reasons to use the methods outlined above by the always helpful Danny Yoo, in addition to the simplification to which he draws attention? -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Mon Sep 8 16:17:33 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 8 Sep 2014 11:17:33 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de> wrote: > > > Personally I'd use normal attributes, though. > Why normal attributes? Isn't it better to make these read-only as I won't ever need to modify them? And even if I modify them, it won't change in the Steam servers, only in my program, and I don't see any use for that, I need the 'real' values always, the 'real' thing only. On Mon, Sep 8, 2014 at 2:36 AM, Alan Gauld wrote: > > Also note the underscore. It improves readability to break multi-words > like that. > For example several others have quoted this as 'person name' rather than > 'persona name' - quite a different concept but hard to spot when all one > word... I tried to follow the variables from the Steam API, there they use 'personaname', 'lastlogoff', 'profileurl', 'loccountrycode' and so on, everything without ' _ ', but now I'm doing the way you said, thanks! File "D:\Documents\HomeBroker\user.py", line 11, in __init__ >> self._avatar = avatar >> AttributeError: can't set attribute >> > > Thats because you set the property name to the field name. > Notice the difference: > > @property > def profileurl(self): > return self._profileurl > > @property > def _avatar(self): > return self._avatar > > > The first sets the property to the non-underscore version > The second uses underscore for both property and field name, > thus making the field read-only. Be careful what you wish for... > > Another reason to only use properties when you *need* to > make them read only (or to do some processing on reads > or writes) Yes, my fault there, I didn't see the ' _ ' in the beginning of the function, but I do need them to be read-only, the user will never need to modify them, and if he tries to modify let's say the name, ' persona_name = "New Name Here" ', it would only change inside the program, the Steam Servers would still use the old name, the 'real' name. The new and now working code is the following: import urllib.request import json class User(): def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar, timecreated, loccountrycode): self._steam_id = steamid self._persona_name = personaname self._last_logoff = lastlogoff self._profile_url = profileurl self._avatar = avatar self._time_created = timecreated self._country_code = loccountrycode @property def steam_id(self): return self._steam_id @property def persona_name(self): return self._persona_name @property def last_logoff(self): return self._last_logoff @property def profile_url(self): return self._profile_url @property def avatar(self): return self._avatar @property def time_created(self): return self._time_created @property def country_code(self): return self._country_code def fetch_users(*id_collection): steamid = [] users = [] for user_id in id_collection: steamid.append(user_id) req = urllib.request.urlopen(' http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9FXXXXXD20&steamids=' + ','.join(steamid)) user_list = json.loads(req.read().decode('utf-8'))["response"]["players"] for user in user_list: if user["communityvisibilitystate"] == 3: # Only people with open profile and inventory are wanted users.append(User(user["steamid"], user["personaname"], user["lastlogoff"], user["profileurl"], user["avatar"], user["timecreated"], user["loccountrycode"])) return users Remember that I do need these attributes to be read-only, so I need to use the '@property' decoration. I modified the 'fetch_users' function in order to accept any number of IDs, this way I can fetch various profiles in one call. Any problems, suggestions now? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Sep 8 18:04:41 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Sep 2014 18:04:41 +0200 Subject: [Tutor] Good approach regarding classes attributes References: Message-ID: Juan Christian wrote: > On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de> wrote: >> Personally I'd use normal attributes, though. >> > > Why normal attributes? Isn't it better to make these read-only as I won't > ever need to modify them? And even if I modify them, it won't change in > the Steam servers, only in my program, and I don't see any use for that, I > need the 'real' values always, the 'real' thing only. Yes, but you know that those attributes should not be reassigned, and for everyone else a hint in the docstring will do. Basically I tend to write as little code as needed, or to put it another way: I'm a lazy bastard ;) In that spirit here's an alternative implementation of the User class: from collections import namedtuple User = namedtuple( "User", "steamid personaname lastlogoff profileurl " "avatar timecreated countrycode") You may note that I refrained from making little improvements to the attribute names -- another odd preference of mine ;) -- which also helps simplify the fetch_users() implementation: ... for user in user_list: if user["communityvisibilitystate"] == 3: users.append(User._make(user[field] for field in User._fields)) ... From alan.gauld at btinternet.com Mon Sep 8 18:39:11 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Sep 2014 17:39:11 +0100 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On 08/09/14 15:17, Juan Christian wrote: One tiny tweak... > class User(): You don't need the parens after User. You don;t have any superclasses so they do nothing. Python convention for an empty parent list is just to leave the parens off: class User: -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 8 19:00:06 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Sep 2014 18:00:06 +0100 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On 08/09/14 15:17, Juan Christian wrote: > Why normal attributes? Isn't it better to make these read-only as I won't > ever need to modify them? And even if I modify them, it won't change in the > Steam servers, only in my program, and I don't see any use for that, I need > the 'real' values always, the 'real' thing only. Read only is not a good term for properties, they are not really read-only. You can still change the unmderlying attribute directly: >>> class C: ... def __init__(self,x): ... self._x = x ... @property ... def x(self): ... return self._x ... >>> c = C(66) >>> c.x 66 >>> c._x 66 >>> c.x = 22 Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute >>> c._x = 22 >>> c.x 22 Notice that although I can't set x, I can set _x! And it 'changes' x. The only thing that stops me is seeing the _x which tells me I shouldn't be messing with it. So in this scenario the property only buys you a tiny bit of protection, you are really still relying on the "We are all consenting adults" philosophy of Python... That's why we would normally only use normal attributes unless the property needed some munging inside the getter/setter method. If you really really don't trust your clients not to mess with _x then that's where you probably do need the __x version, combined with properties. which is where we came in! :-) (And its still not 100% foolproof) >>> class C: ... def __init__(self,x): ... self.__x = x ... @property ... def x(self): ... return self.__x ... >>> c = C(66) >>> c.x 66 >>> c.__x Traceback (most recent call last): File "", line 1, in AttributeError: 'C' object has no attribute '__x' >>> c.x = 22 Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute >>> c.__x = 22 >>> c.x 66 >>> c.__x 22 Notice I can still set/read __x from the client, but at least this time it does not change the x property value... >>> dir(c) ['_C__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '__x', 'x'] >>> Notice dir() shows that you now have two __x attributes, the original name-mangled version and the new local 'c' instance version. The only way to get total read-only working would be to write your own get attribute function - I think that is as near foolproof as you can get in Python. Python doesn't really make this kind of data hiding easy, its just not the Pythonic way. Python is not Java (or Smalltalk for that matter). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From juan0christian at gmail.com Mon Sep 8 19:26:52 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 8 Sep 2014 14:26:52 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: > > > On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de> wrote: > > In that spirit here's an alternative implementation of the User class: > > from collections import namedtuple > User = namedtuple( > "User", > "steamid personaname lastlogoff profileurl " > "avatar timecreated countrycode") > > You may note that I refrained from making little improvements to the > attribute names -- another odd preference of mine ;) -- which also helps > simplify the fetch_users() implementation: > > ... > for user in user_list: > if user["communityvisibilitystate"] == 3: > users.append(User._make(user[field] for field in User._fields)) > ... I didn't get the idea behind 'namedtuple' and your 'User._make(user[field] for field in User._fields)', I'm still using the other way: import urllib.request import json class User: def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar, timecreated, loccountrycode): self.steam_id = steamid self.persona_name = personaname self.last_logoff = lastlogoff self.profile_url = profileurl self.avatar = avatar self.time_created = timecreated self.country_code = loccountrycode def fetch_users(*steamids): users = [] req = urllib.request.urlopen(' http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9XXXXX20&steamids=' + ','.join(steamids)) user_list = json.loads(req.read().decode('utf-8'))["response"]["players"] for user in user_list: if user["communityvisibilitystate"] == 3: users.append(User(user["steamid"], user["personaname"], user["lastlogoff"], user["profileurl"], user["avatar"], user["timecreated"], user["loccountrycode"])) return users As you guys said, I'd better use the "all open" pythonic way and not try to hide things, so here it's. Is this piece of code pythonic enough? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Sep 9 00:09:23 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Sep 2014 00:09:23 +0200 Subject: [Tutor] Good approach regarding classes attributes References: Message-ID: Juan Christian wrote: >> >> > On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de> wrote: >> >> In that spirit here's an alternative implementation of the User class: >> >> from collections import namedtuple >> User = namedtuple( >> "User", >> "steamid personaname lastlogoff profileurl " >> "avatar timecreated countrycode") >> >> You may note that I refrained from making little improvements to the >> attribute names -- another odd preference of mine ;) -- which also helps >> simplify the fetch_users() implementation: >> >> ... >> for user in user_list: >> if user["communityvisibilitystate"] == 3: >> users.append(User._make(user[field] for field in User._fields)) >> ... > > > I didn't get the idea behind 'namedtuple' and your 'User._make(user[field] > for field in User._fields)', I'm still using the other way: > > import urllib.request > import json > > class User: > > def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar, > timecreated, loccountrycode): > self.steam_id = steamid > self.persona_name = personaname > self.last_logoff = lastlogoff > self.profile_url = profileurl > self.avatar = avatar > self.time_created = timecreated > self.country_code = loccountrycode > > def fetch_users(*steamids): > users = [] > > req = urllib.request.urlopen(' > http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9XXXXX20&steamids=' > + ','.join(steamids)) > user_list = json.loads(req.read().decode('utf-8'))["response"]["players"] > > for user in user_list: > if user["communityvisibilitystate"] == 3: > users.append(User(user["steamid"], user["personaname"], > user["lastlogoff"], user["profileurl"], user["avatar"], > user["timecreated"], user["loccountrycode"])) > > return users > > As you guys said, I'd better use the "all open" pythonic way and not try > to hide things, so here it's. Is this piece of code pythonic enough? Yes, I think this is simple enough that you can easily understand it when you look at it again in a year. There are no constructs that strike me as unidiomatic. It's time to stop pondering over the innards of this component and use it to build something useful. Good luck with that! PS: This is not about being pythonic, but it might be more convenient for client code if you use datetime objects instead of timestamps: >>> import datetime >>> last_logoff = datetime.datetime.utcfromtimestamp(1410065399) >>> print(last_logoff) 2014-09-07 04:49:59 From felisha.lawrence at gmail.com Mon Sep 8 21:17:46 2014 From: felisha.lawrence at gmail.com (Felisha Lawrence) Date: Mon, 8 Sep 2014 15:17:46 -0400 Subject: [Tutor] Output 'Strings' to directory Message-ID: Is it possible to output strings created from a print statement into a directory locally? If so, would you use sysstdout module? Thanks, Felisha -- Felisha Lawrence Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student NASA URC/BCCSO Graduate Fellow NOAA NCAS Graduate Fellow Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer (240)-535-6665 (cell) felisha.lawrence at gmail.com (email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Sep 9 03:15:25 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 8 Sep 2014 18:15:25 -0700 Subject: [Tutor] Output 'Strings' to directory In-Reply-To: References: Message-ID: On Mon, Sep 8, 2014 at 12:17 PM, Felisha Lawrence wrote: > Is it possible to output strings created from a print statement into a > directory locally? Hi Felisha, Yes. This can be done from the level of your operating system shell, rather than Python, through "output redirection". http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html Output redirection would be an extra-lingual approach to what you're asking. It's also fairly straightforward, and works well on Unix-like systems. It should also work on Windows, though I have to admit that I don't have direct experience there. As an intra-lingual feature, yes as well to your question. You can write to a file-like object instead of the systemwide "standard output". This requires you to be more specific whenever you're writing output, to write it to that file. For example, see the "file" argument to print: https://docs.python.org/2/library/functions.html#print where every place where we'd use a simpler print where it implicitly prints to the "standard output", we tell it to print to a file. From jarod_v6 at libero.it Tue Sep 9 09:00:43 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Tue, 9 Sep 2014 09:00:43 +0200 (CEST) Subject: [Tutor] how to be sure the process are ended Message-ID: <23185698.4214661410246043483.JavaMail.httpd@webmail-07.iol.local> >----Messaggio originale---- >Da: jarod_v6 at libero.it >Data: 08/09/2014 18.15 >A: >Ogg: how to be sure the process are ended > >Dear all!! >I want to use subprocess for run some programs But I need to be sure the >program end before continue with the other: > >subprocess.call("ls") > cmd1 = i > p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) > > while True: > if p1.poll() is None: > time.sleep(3) > > pass > if p1.poll()==0: > print '#' > break > if p1.poll() is not None and p1.poll() != 0: > raise Exception('Error building Alignment using star with hg19 >database') > > > >This are not working. How can I do? >thanks in advance for the precious help >bw, > From mimiouyang at hotmail.com Tue Sep 9 02:48:18 2014 From: mimiouyang at hotmail.com (Mimi Ou Yang) Date: Tue, 9 Sep 2014 00:48:18 +0000 Subject: [Tutor] =?utf-8?q?Else_and_If?= Message-ID: print ("Quiz TIME!!!") ready = input("Are you ready?") if (ready in ("yes","YES","Yes")): print ("Alrighty") if (ready in ("no","NO","No")): print ("Too bad so sad. You're obligated to do it.") else: print ("OK (sarcasm)") q1 = input("1. When was Quebec City founded? a. 1608 b. 1690 c. 1900: ") if (q1 == "a"): print ("Good answer.On to the next question.") q2 = input("2. What is 1+1? a. 5 b.8 c.2: ") if (q2 == "c"): print ("Hooray Good answer") else: print ("Wrong Answer") q3 = input("What color was Napoleon's white horse? a. black b. white c.brown: ") if (q3 in ("b","B")): print ("Good.Next question.") else: print ("Wrong.Next question.") When I write yes or YES or Yes or no or No or NO in the ready input it always print out Alrighty and OK (sarcasm) can you tell me what is the mistake in my code? Thanks? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Sep 9 10:52:34 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Sep 2014 10:52:34 +0200 Subject: [Tutor] Else and If References: Message-ID: Mimi Ou Yang wrote: > print ("Quiz TIME!!!") > ready = input("Are you ready?") > if (ready in ("yes","YES","Yes")): > print ("Alrighty") > if (ready in ("no","NO","No")): > print ("Too bad so sad. You're obligated to do it.") > else: > print ("OK (sarcasm)") > When I write yes or YES or Yes or no or No or NO in the ready input it > always print out Alrighty and OK (sarcasm) can you tell me what is the > mistake in my code? Assuming ready is "Yes" the following expression evaluates to True, the if- suite is executed and "Alrighty" is printed > if (ready in ("yes","YES","Yes")): > print ("Alrighty") Then the following expression evaluates to False, thus the if-suite is not executed, but the else-suite is executed and thus prints "OK (sarcasm)" > if (ready in ("no","NO","No")): The first if condition1: suite1 and the second if condition2: suite2 else: suite3 are completely separate. You can change by nesting them: if condition1: suite1 else: if condition2: suite2 else: suite3 That way the second condition is only evaluated when the first condition is False. While this works there is a better option: put all conditions into a single if ... elif... else: if condition1: suite1 elif condition2: suite2 else: # neither cond1 nor cond2 are met suite3 Taking your example: if (ready in ("yes","YES","Yes")): print("Alrighty") elif (ready in ("no","NO","No")): print("Too bad so sad. You're obligated to do it.") else: print("OK (sarcasm)") By the way, the parens around the condition are superfluous, and you may want to allow all spellings of "yes" (like "YEs" and "yEs") and "no", so ready = ready.lower() # or ready.casefold() if ready == "yes": print("Alrighty") elif ready == "no": print("Too bad so sad. You're obligated to do it.") else: print("OK (sarcasm)") The number of `elif`s is not limited -- if you like you can insert a elif ready == "maybe tomorrow": ... From jarod_v6 at libero.it Tue Sep 9 11:33:33 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Tue, 9 Sep 2014 11:33:33 +0200 (CEST) Subject: [Tutor] Understand subprocess poll Message-ID: <6340899.4279811410255213136.JavaMail.httpd@webmail-07.iol.local> Dear all!! I want to use subprocess for run some programs But I need to be sure the program end before continue with the other: subprocess.call("ls") cmd1 = i p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) while True: if p1.poll() is None: time.sleep(3) pass if p1.poll()==0: print '#' break if p1.poll() is not None and p1.poll() != 0: raise Exception('Error building Alignment using star with hg19 database') This are not working. How can I do? thanks in advance for the precious help bw, From __peter__ at web.de Tue Sep 9 11:45:36 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Sep 2014 11:45:36 +0200 Subject: [Tutor] Understand subprocess poll References: <6340899.4279811410255213136.JavaMail.httpd@webmail-07.iol.local> Message-ID: jarod_v6 at libero.it wrote: > I want to use subprocess for run some programs But I need to be sure the > program end before continue with the other: > > subprocess.call("ls") > cmd1 = i > p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) > > while True: > if p1.poll() is None: > time.sleep(3) > > pass > if p1.poll()==0: > print '#' > break > if p1.poll() is not None and p1.poll() != 0: > raise Exception('Error building Alignment using star with hg19 > database') > This are not working. How can I do? > thanks in advance for the precious help > bw, I don't understand why you would need this loop. Why don't you use subprocess.call() and be done? From s.shall at virginmedia.com Tue Sep 9 15:09:32 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 09 Sep 2014 15:09:32 +0200 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: <540EFC0C.3000202@virginmedia.com> On 08/09/2014 18:39, Alan Gauld wrote: > On 08/09/14 15:17, Juan Christian wrote: > > One tiny tweak... > >> class User(): > > You don't need the parens after User. You don;t have any superclasses > so they do nothing. Python convention for an empty parent list is just > to leave the parens off: > > class User: > A simple question from a newbie, in response to this surprise. Is it not helpful to always put (object) as the parent, if the class is not itself a sub-class? And while I am writing, what does OP stand for in this list? -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Tue Sep 9 15:14:39 2014 From: leamhall at gmail.com (leam hall) Date: Tue, 9 Sep 2014 09:14:39 -0400 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: <540EFC0C.3000202@virginmedia.com> References: <540EFC0C.3000202@virginmedia.com> Message-ID: On Tue, Sep 9, 2014 at 9:09 AM, Sydney Shall wrote: > And while I am writing, what does OP stand for in this list? "Original Poster". So I understand. Won't answer the Python question since I'm a newbie here myself. -- Mind on a Mission From wolfgang.maier at biologie.uni-freiburg.de Tue Sep 9 15:05:11 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 09 Sep 2014 15:05:11 +0200 Subject: [Tutor] Understand subprocess poll In-Reply-To: References: <6340899.4279811410255213136.JavaMail.httpd@webmail-07.iol.local> Message-ID: <540EFB07.5050901@biologie.uni-freiburg.de> On 09/09/2014 11:45 AM, Peter Otten wrote: > jarod_v6 at libero.it wrote: > >> I want to use subprocess for run some programs But I need to be sure the >> program end before continue with the other: >> >> subprocess.call("ls") >> cmd1 = i >> p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) >> >> while True: >> if p1.poll() is None: >> time.sleep(3) >> >> pass >> if p1.poll()==0: >> print '#' >> break >> if p1.poll() is not None and p1.poll() != 0: >> raise Exception('Error building Alignment using star with hg19 >> database') > >> This are not working. How can I do? >> thanks in advance for the precious help >> bw, > > I don't understand why you would need this loop. Why don't you use > subprocess.call() and be done? > The OP is piping the process stdout so I assume he is going to read from it in place of the pass in his example. Since the subprocess is doing genome-wide sequence alignment (at least I guess so from the exception string) there will be lots of output, which would cause subprocess.call() to block. Assuming that the posted code was indented correctly and was otherwise run as posted this could also be the answer to the original question: you have to keep on consuming data from the pipe or its buffer is going to fill up and block everyhing. With a simple pass statement you do not achieve anything that you can't do with call. Wolfgang From __peter__ at web.de Tue Sep 9 15:44:22 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Sep 2014 15:44:22 +0200 Subject: [Tutor] Good approach regarding classes attributes References: <540EFC0C.3000202@virginmedia.com> Message-ID: Sydney Shall wrote: > On 08/09/2014 18:39, Alan Gauld wrote: >> On 08/09/14 15:17, Juan Christian wrote: >> >> One tiny tweak... >> >>> class User(): >> >> You don't need the parens after User. You don;t have any superclasses >> so they do nothing. Python convention for an empty parent list is just >> to leave the parens off: >> >> class User: >> > A simple question from a newbie, in response to this surprise. > Is it not helpful to always put (object) as the parent, if the class is > not itself a sub-class? The answer differs between Python 2 and 3. In Python 3 class C: # preferred in Python 3 pass and class C(object): pass are the same, so there is no point adding the explicit object inheritance. In Python 2 however class C: pass will create a "classic class" whereas class C(object): # preferred in Python 2 pass is a "newstyle class". The most notable difference between these is that properties work correctly only with newstyle classes. Therefore making all your classes "newstyle" is a good idea. > And while I am writing, what does OP stand for in this list? Original Poster, as Leam says. From juan0christian at gmail.com Tue Sep 9 15:54:22 2014 From: juan0christian at gmail.com (Juan Christian) Date: Tue, 9 Sep 2014 10:54:22 -0300 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: Message-ID: On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de > wrote: > > PS: This is not about being pythonic, but it might be more convenient for > client code if you use datetime objects instead of timestamps: > > >>> import datetime > >>> last_logoff = datetime.datetime.utcfromtimestamp(1410065399) > >>> print(last_logoff) > 2014-09-07 04:49:59 > Yes, I'll do it for sure, the API response is indeed returned that way to make things easier. -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.shall at virginmedia.com Tue Sep 9 16:02:01 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 09 Sep 2014 16:02:01 +0200 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <540EFC0C.3000202@virginmedia.com> Message-ID: <540F0859.5070802@virginmedia.com> On 09/09/2014 15:44, Peter Otten wrote: > Sydney Shall wrote: > >> On 08/09/2014 18:39, Alan Gauld wrote: >>> On 08/09/14 15:17, Juan Christian wrote: >>> >>> One tiny tweak... >>> >>>> class User(): >>> You don't need the parens after User. You don;t have any superclasses >>> so they do nothing. Python convention for an empty parent list is just >>> to leave the parens off: >>> >>> class User: >>> >> A simple question from a newbie, in response to this surprise. >> Is it not helpful to always put (object) as the parent, if the class is >> not itself a sub-class? > The answer differs between Python 2 and 3. In Python 3 > > class C: # preferred in Python 3 > pass > > and > > class C(object): > pass > > are the same, so there is no point adding the explicit object inheritance. > > In Python 2 however > > class C: > pass > > will create a "classic class" whereas > > class C(object): # preferred in Python 2 > pass > > is a "newstyle class". The most notable difference between these is that > properties work correctly only with newstyle classes. Therefore making all > your classes "newstyle" is a good idea. > >> And while I am writing, what does OP stand for in this list? > Original Poster, as Leam says. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Thanks Peter, most helpful. I was taught with Python 2.7, so now I understand the advice. -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Sep 9 16:05:09 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 9 Sep 2014 10:05:09 -0400 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: <540F0859.5070802@virginmedia.com> References: <540EFC0C.3000202@virginmedia.com> <540F0859.5070802@virginmedia.com> Message-ID: On Tue, Sep 9, 2014 at 10:02 AM, Sydney Shall wrote: > On 09/09/2014 15:44, Peter Otten wrote: > > Sydney Shall wrote: > > On 08/09/2014 18:39, Alan Gauld wrote: > > On 08/09/14 15:17, Juan Christian wrote: > > One tiny tweak... > > class User(): > > You don't need the parens after User. You don;t have any superclasses > so they do nothing. Python convention for an empty parent list is just > to leave the parens off: > > class User: > > A simple question from a newbie, in response to this surprise. > Is it not helpful to always put (object) as the parent, if the class is > not itself a sub-class? > > The answer differs between Python 2 and 3. In Python 3 > > class C: # preferred in Python 3 > pass > > and > > class C(object): > pass > > are the same, so there is no point adding the explicit object inheritance. > > In Python 2 however > > class C: > pass > > will create a "classic class" whereas > > class C(object): # preferred in Python 2 > pass > > is a "newstyle class". The most notable difference between these is that > properties work correctly only with newstyle classes. Therefore making all > your classes "newstyle" is a good idea. > > And while I am writing, what does OP stand for in this list? > > Original Poster, as Leam says. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > Thanks Peter, most helpful. > I was taught with Python 2.7, so now I understand the advice. > > > -- > Sydney Shall > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Please post in plain text -- Joel Goldstick http://joelgoldstick.com From __peter__ at web.de Tue Sep 9 16:18:40 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Sep 2014 16:18:40 +0200 Subject: [Tutor] Understand subprocess poll References: <6340899.4279811410255213136.JavaMail.httpd@webmail-07.iol.local> <540EFB07.5050901@biologie.uni-freiburg.de> Message-ID: Wolfgang Maier wrote: > On 09/09/2014 11:45 AM, Peter Otten wrote: >> jarod_v6 at libero.it wrote: >> >>> I want to use subprocess for run some programs But I need to be sure the >>> program end before continue with the other: >>> >>> subprocess.call("ls") >>> cmd1 = i >>> p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) >>> >>> while True: >>> if p1.poll() is None: >>> time.sleep(3) >>> >>> pass >>> if p1.poll()==0: >>> print '#' >>> break >>> if p1.poll() is not None and p1.poll() != 0: >>> raise Exception('Error building Alignment using star with hg19 >>> database') >> >>> This are not working. How can I do? >>> thanks in advance for the precious help >>> bw, >> >> I don't understand why you would need this loop. Why don't you use >> subprocess.call() and be done? >> > > The OP is piping the process stdout so I assume he is going to read from > it in place of the pass in his example. > Since the subprocess is doing genome-wide sequence alignment (at least I > guess so from the exception string) there will be lots of output, which > would cause subprocess.call() to block. > > Assuming that the posted code was indented correctly and was otherwise > run as posted this could also be the answer to the original question: > you have to keep on consuming data from the pipe or its buffer is going > to fill up and block everyhing. With a simple pass statement you do not > achieve anything that you can't do with call. Ah, you're right. I still don't see where the need to poll arises, I'd expect something like p = subprocess.Popen(cmd, ..., stdout=PIPE) for line in p.stdout: process(line) p.stdout.close() if p.wait() != 0: raise Exception to work. From jarod_v6 at libero.it Tue Sep 9 16:36:47 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Tue, 9 Sep 2014 16:36:47 +0200 (CEST) Subject: [Tutor] Understand subprocess poll Message-ID: <28501232.4398921410273407217.JavaMail.httpd@webmail-07.iol.local> Thanks for yhe help! The comand run is this the class created are this: def run(cmd,pi): import subprocess import time import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % (levelname)s - %(messag e)s") #logging.debug(" Running pipelines: %s" % (cmd)) # setup logging log_file = "None" tou = "file"+"_.log.txt" if log_file is not None: logfh = open(tou, "w") else: logfh = None print "####################################################" p1 = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=logfh, cwd=pi) #logging.info(" Running pipelines: %s" % (cmd)) while True: if p1.poll() is None: time.sleep(3) pass if p1.poll()==0: print 'Finish this step.' logging.info("###################: %s %s" % (cmd,time.ctime())) break if p1.poll() is not None and p1.poll() != 0: raise Exception('Not working please check the error') # end logging if logfh is not None: logfh.close() return 0 step_2_out =["~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir /home/sbsuser/d atabases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn %s %s -- runThreadN 12 --readFilesCommand zcat "%(dx,sn)] The problems is the script end the process but not allign all the data. If I use the comand line the same code the process work. How can resolve this issue? >----Messaggio originale---- >Da: tutor-request at python.org >Data: 09/09/2014 16.02 >A: >Ogg: Tutor Digest, Vol 127, Issue 26 > >Send Tutor mailing list submissions to > tutor at python.org > >To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor >or, via email, send a message with subject or body 'help' to > tutor-request at python.org > >You can reach the person managing the list at > tutor-owner at python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. Re: Good approach regarding classes attributes (Sydney Shall) > 2. Re: Good approach regarding classes attributes (leam hall) > 3. Re: Understand subprocess poll (Wolfgang Maier) > 4. Re: Good approach regarding classes attributes (Peter Otten) > 5. Re: Good approach regarding classes attributes (Juan Christian) > 6. Re: Good approach regarding classes attributes (Sydney Shall) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Tue, 09 Sep 2014 15:09:32 +0200 >From: Sydney Shall >To: tutor at python.org >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: <540EFC0C.3000202 at virginmedia.com> >Content-Type: text/plain; charset="windows-1252"; Format="flowed" > >On 08/09/2014 18:39, Alan Gauld wrote: >> On 08/09/14 15:17, Juan Christian wrote: >> >> One tiny tweak... >> >>> class User(): >> >> You don't need the parens after User. You don;t have any superclasses >> so they do nothing. Python convention for an empty parent list is just >> to leave the parens off: >> >> class User: >> >A simple question from a newbie, in response to this surprise. >Is it not helpful to always put (object) as the parent, if the class is >not itself a sub-class? >And while I am writing, what does OP stand for in this list? > > >-- >Sydney Shall >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 2 >Date: Tue, 9 Sep 2014 09:14:39 -0400 >From: leam hall >To: tutor >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: > >Content-Type: text/plain; charset=UTF-8 > >On Tue, Sep 9, 2014 at 9:09 AM, Sydney Shall wrote: > >> And while I am writing, what does OP stand for in this list? > >"Original Poster". So I understand. Won't answer the Python question >since I'm a newbie here myself. > >-- >Mind on a Mission > > >------------------------------ > >Message: 3 >Date: Tue, 09 Sep 2014 15:05:11 +0200 >From: Wolfgang Maier >To: tutor at python.org >Subject: Re: [Tutor] Understand subprocess poll >Message-ID: <540EFB07.5050901 at biologie.uni-freiburg.de> >Content-Type: text/plain; charset=utf-8; format=flowed > >On 09/09/2014 11:45 AM, Peter Otten wrote: >> jarod_v6 at libero.it wrote: >> >>> I want to use subprocess for run some programs But I need to be sure the >>> program end before continue with the other: >>> >>> subprocess.call("ls") >>> cmd1 = i >>> p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) >>> >>> while True: >>> if p1.poll() is None: >>> time.sleep(3) >>> >>> pass >>> if p1.poll()==0: >>> print '#' >>> break >>> if p1.poll() is not None and p1.poll() != 0: >>> raise Exception('Error building Alignment using star with hg19 >>> database') >> >>> This are not working. How can I do? >>> thanks in advance for the precious help >>> bw, >> >> I don't understand why you would need this loop. Why don't you use >> subprocess.call() and be done? >> > >The OP is piping the process stdout so I assume he is going to read from >it in place of the pass in his example. >Since the subprocess is doing genome-wide sequence alignment (at least I >guess so from the exception string) there will be lots of output, which >would cause subprocess.call() to block. > >Assuming that the posted code was indented correctly and was otherwise >run as posted this could also be the answer to the original question: >you have to keep on consuming data from the pipe or its buffer is going >to fill up and block everyhing. With a simple pass statement you do not >achieve anything that you can't do with call. > >Wolfgang > > > >------------------------------ > >Message: 4 >Date: Tue, 09 Sep 2014 15:44:22 +0200 >From: Peter Otten <__peter__ at web.de> >To: tutor at python.org >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: >Content-Type: text/plain; charset="ISO-8859-1" > >Sydney Shall wrote: > >> On 08/09/2014 18:39, Alan Gauld wrote: >>> On 08/09/14 15:17, Juan Christian wrote: >>> >>> One tiny tweak... >>> >>>> class User(): >>> >>> You don't need the parens after User. You don;t have any superclasses >>> so they do nothing. Python convention for an empty parent list is just >>> to leave the parens off: >>> >>> class User: >>> >> A simple question from a newbie, in response to this surprise. >> Is it not helpful to always put (object) as the parent, if the class is >> not itself a sub-class? > >The answer differs between Python 2 and 3. In Python 3 > >class C: # preferred in Python 3 > pass > >and > >class C(object): > pass > >are the same, so there is no point adding the explicit object inheritance. > >In Python 2 however > >class C: > pass > >will create a "classic class" whereas > >class C(object): # preferred in Python 2 > pass > >is a "newstyle class". The most notable difference between these is that >properties work correctly only with newstyle classes. Therefore making all >your classes "newstyle" is a good idea. > >> And while I am writing, what does OP stand for in this list? > >Original Poster, as Leam says. > > > > >------------------------------ > >Message: 5 >Date: Tue, 9 Sep 2014 10:54:22 -0300 >From: Juan Christian >Cc: "tutor at python.org" >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: > >Content-Type: text/plain; charset="utf-8" > >On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de > >wrote: > >> >> PS: This is not about being pythonic, but it might be more convenient for >> client code if you use datetime objects instead of timestamps: >> >> >>> import datetime >> >>> last_logoff = datetime.datetime.utcfromtimestamp(1410065399) >> >>> print(last_logoff) >> 2014-09-07 04:49:59 >> > >Yes, I'll do it for sure, the API response is indeed returned that way to >make things easier. >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 6 >Date: Tue, 09 Sep 2014 16:02:01 +0200 >From: Sydney Shall >To: tutor at python.org >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: <540F0859.5070802 at virginmedia.com> >Content-Type: text/plain; charset="windows-1252"; Format="flowed" > >On 09/09/2014 15:44, Peter Otten wrote: >> Sydney Shall wrote: >> >>> On 08/09/2014 18:39, Alan Gauld wrote: >>>> On 08/09/14 15:17, Juan Christian wrote: >>>> >>>> One tiny tweak... >>>> >>>>> class User(): >>>> You don't need the parens after User. You don;t have any superclasses >>>> so they do nothing. Python convention for an empty parent list is just >>>> to leave the parens off: >>>> >>>> class User: >>>> >>> A simple question from a newbie, in response to this surprise. >>> Is it not helpful to always put (object) as the parent, if the class is >>> not itself a sub-class? >> The answer differs between Python 2 and 3. In Python 3 >> >> class C: # preferred in Python 3 >> pass >> >> and >> >> class C(object): >> pass >> >> are the same, so there is no point adding the explicit object inheritance. >> >> In Python 2 however >> >> class C: >> pass >> >> will create a "classic class" whereas >> >> class C(object): # preferred in Python 2 >> pass >> >> is a "newstyle class". The most notable difference between these is that >> properties work correctly only with newstyle classes. Therefore making all >> your classes "newstyle" is a good idea. >> >>> And while I am writing, what does OP stand for in this list? >> Original Poster, as Leam says. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >Thanks Peter, most helpful. >I was taught with Python 2.7, so now I understand the advice. > > >-- >Sydney Shall >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Subject: Digest Footer > >_______________________________________________ >Tutor maillist - Tutor at python.org >https://mail.python.org/mailman/listinfo/tutor > > >------------------------------ > >End of Tutor Digest, Vol 127, Issue 26 >************************************** > From s.shall at virginmedia.com Tue Sep 9 17:05:46 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 09 Sep 2014 17:05:46 +0200 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <540EFC0C.3000202@virginmedia.com> <540F0859.5070802@virginmedia.com> Message-ID: <540F174A.1000709@virginmedia.com> On 09/09/2014 16:05, Joel Goldstick wrote: > On Tue, Sep 9, 2014 at 10:02 AM, Sydney Shall wrote: >> On 09/09/2014 15:44, Peter Otten wrote: >> >> Sydney Shall wrote: >> >> On 08/09/2014 18:39, Alan Gauld wrote: >> >> On 08/09/14 15:17, Juan Christian wrote: >> >> One tiny tweak... >> >> class User(): >> >> You don't need the parens after User. You don;t have any superclasses >> so they do nothing. Python convention for an empty parent list is just >> to leave the parens off: >> >> class User: >> >> A simple question from a newbie, in response to this surprise. >> Is it not helpful to always put (object) as the parent, if the class is >> not itself a sub-class? >> >> The answer differs between Python 2 and 3. In Python 3 >> >> class C: # preferred in Python 3 >> pass >> >> and >> >> class C(object): >> pass >> >> are the same, so there is no point adding the explicit object inheritance. >> >> In Python 2 however >> >> class C: >> pass >> >> will create a "classic class" whereas >> >> class C(object): # preferred in Python 2 >> pass >> >> is a "newstyle class". The most notable difference between these is that >> properties work correctly only with newstyle classes. Therefore making all >> your classes "newstyle" is a good idea. >> >> And while I am writing, what does OP stand for in this list? >> >> Original Poster, as Leam says. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> Thanks Peter, most helpful. >> I was taught with Python 2.7, so now I understand the advice. >> >> >> -- >> Sydney Shall >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > Please post in plain text > My apologies. I thought I was. I will immediately change it. -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Sep 9 17:44:39 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Sep 2014 08:44:39 -0700 Subject: [Tutor] Fwd: Re: Output 'Strings' to directory In-Reply-To: References: Message-ID: Forwarding to tutor. ---------- Forwarded message ---------- From: "Felisha Lawrence" Date: Sep 9, 2014 6:56 AM Subject: Re: [Tutor] Output 'Strings' to directory To: "Danny Yoo" Cc: > So, I ran the following code > > > import os > > path = '/Users/felishalawrence/testswps/vol1' > for file in os.listdir(path): > newFile = file[:file.rindex("v")]+"v20" > sys.stdout = '/Users/felishalawrence/testswps/vol1' > print newFile > > and got nothing. No errors and it did not print out my results in ipython notebook when I removed line 5 and ran it again. The output was also not in the folder specified. What did I do wrong? > > Thanks, > > > > On Mon, Sep 8, 2014 at 9:15 PM, Danny Yoo wrote: >> >> On Mon, Sep 8, 2014 at 12:17 PM, Felisha Lawrence >> wrote: >> > Is it possible to output strings created from a print statement into a >> > directory locally? >> >> >> Hi Felisha, >> >> Yes. This can be done from the level of your operating system shell, >> rather than Python, through "output redirection". >> >> http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html >> >> Output redirection would be an extra-lingual approach to what you're >> asking. It's also fairly straightforward, and works well on Unix-like >> systems. It should also work on Windows, though I have to admit that >> I don't have direct experience there. >> >> >> As an intra-lingual feature, yes as well to your question. You can >> write to a file-like object instead of the systemwide "standard >> output". This requires you to be more specific whenever you're >> writing output, to write it to that file. >> >> For example, see the "file" argument to print: >> >> https://docs.python.org/2/library/functions.html#print >> >> where every place where we'd use a simpler print where it implicitly >> prints to the "standard output", we tell it to print to a file. > > > > > -- > Felisha Lawrence > Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student > NASA URC/BCCSO Graduate Fellow > NOAA NCAS Graduate Fellow > Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer > (240)-535-6665 (cell) > felisha.lawrence at gmail.com (email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Sep 9 18:26:34 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Sep 2014 09:26:34 -0700 Subject: [Tutor] Fwd: Fwd: Re: Output 'Strings' to directory In-Reply-To: References: Message-ID: Felisha, please use reply to all. I'm at work at the moment; can't look at your question. Thanks! Forwarding to tutor. ---------- Forwarded message ---------- From: Felisha Lawrence Date: Tue, Sep 9, 2014 at 8:53 AM Subject: Re: [Tutor] Fwd: Re: Output 'Strings' to directory To: Danny Yoo Also, I had this code working import os path = '/Users/felishalawrence/testswps/vol1' for file in os.listdir(path): newFile = file[:file.index("v")]+"v20" print newFile and now I am getting this error ValueError: substring not found I did not change anything On Tue, Sep 9, 2014 at 11:44 AM, Danny Yoo wrote: > > Forwarding to tutor. > > > ---------- Forwarded message ---------- > From: "Felisha Lawrence" > Date: Sep 9, 2014 6:56 AM > Subject: Re: [Tutor] Output 'Strings' to directory > To: "Danny Yoo" > Cc: > > > So, I ran the following code > > > > > > import os > > > > path = '/Users/felishalawrence/testswps/vol1' > > for file in os.listdir(path): > > newFile = file[:file.rindex("v")]+"v20" > > sys.stdout = '/Users/felishalawrence/testswps/vol1' > > print newFile > > > > and got nothing. No errors and it did not print out my results in ipython notebook when I removed line 5 and ran it again. The output was also not in the folder specified. What did I do wrong? > > > > Thanks, > > > > > > > > On Mon, Sep 8, 2014 at 9:15 PM, Danny Yoo wrote: > >> > >> On Mon, Sep 8, 2014 at 12:17 PM, Felisha Lawrence > >> wrote: > >> > Is it possible to output strings created from a print statement into a > >> > directory locally? > >> > >> > >> Hi Felisha, > >> > >> Yes. This can be done from the level of your operating system shell, > >> rather than Python, through "output redirection". > >> > >> http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html > >> > >> Output redirection would be an extra-lingual approach to what you're > >> asking. It's also fairly straightforward, and works well on Unix-like > >> systems. It should also work on Windows, though I have to admit that > >> I don't have direct experience there. > >> > >> > >> As an intra-lingual feature, yes as well to your question. You can > >> write to a file-like object instead of the systemwide "standard > >> output". This requires you to be more specific whenever you're > >> writing output, to write it to that file. > >> > >> For example, see the "file" argument to print: > >> > >> https://docs.python.org/2/library/functions.html#print > >> > >> where every place where we'd use a simpler print where it implicitly > >> prints to the "standard output", we tell it to print to a file. > > > > > > > > > > -- > > Felisha Lawrence > > Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student > > NASA URC/BCCSO Graduate Fellow > > NOAA NCAS Graduate Fellow > > Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer > > (240)-535-6665 (cell) > > felisha.lawrence at gmail.com (email) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Felisha Lawrence Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student NASA URC/BCCSO Graduate Fellow NOAA NCAS Graduate Fellow Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer (240)-535-6665 (cell) felisha.lawrence at gmail.com (email) From alan.gauld at btinternet.com Tue Sep 9 18:53:05 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Sep 2014 17:53:05 +0100 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <540EFC0C.3000202@virginmedia.com> Message-ID: On 09/09/14 14:44, Peter Otten wrote: >> Is it not helpful to always put (object) as the parent, if the class is >> not itself a sub-class? > > The answer differs between Python 2 and 3. In Python 3 > > class C: # preferred in Python 3 > pass Apologies, I should have mentioned that. I've been using Python3 almost exclusively since January this year and I'm starting to forget my Python 2 idioms... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Sep 9 18:57:11 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Sep 2014 17:57:11 +0100 Subject: [Tutor] Fwd: Fwd: Re: Output 'Strings' to directory In-Reply-To: References: Message-ID: > From: Felisha Lawrence > Date: Tue, Sep 9, 2014 at 8:53 AM > Subject: Re: [Tutor] Fwd: Re: Output 'Strings' to directory > To: Danny Yoo > > > Also, > I had this code working > > import os > > path = '/Users/felishalawrence/testswps/vol1' > for file in os.listdir(path): > newFile = file[:file.index("v")]+"v20" > > print newFile > and now I am getting this error > > ValueError: substring not found > > I did not change anything Have you checked that no new files have been created - possibly by your code, that don't conform to your expected naming style? Try putting a 'print file' before the name modification to see what the name that causes the error looks like. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From admin at c12.in Tue Sep 9 14:27:51 2014 From: admin at c12.in (Mirage Web Studio) Date: Tue, 09 Sep 2014 17:57:51 +0530 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540BC08A.4000308@c12.in> References: <540BC08A.4000308@c12.in> Message-ID: <540EF247.30900@c12.in> Hello, I am not an advanced programmer, but am very good with keyboard and find using tabs for syntax and formatting very helpful. But in this list and other python documentation i have repeatedly seen people recommending use of spaces. I know that i can use any of them and use tabs as my preference. But i would like to understand why hitting the poor keyboard 4/8/12 times is preferred than just hitting it 1/2/3 times. Thank you George --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From felisha.lawrence at gmail.com Tue Sep 9 19:26:24 2014 From: felisha.lawrence at gmail.com (Felisha Lawrence) Date: Tue, 9 Sep 2014 13:26:24 -0400 Subject: [Tutor] Fwd: Fwd: Re: Output 'Strings' to directory In-Reply-To: References: Message-ID: Thanks! Thats exactly what my problem was. I fixed it On Tue, Sep 9, 2014 at 12:57 PM, Alan Gauld wrote: > From: Felisha Lawrence >> Date: Tue, Sep 9, 2014 at 8:53 AM >> Subject: Re: [Tutor] Fwd: Re: Output 'Strings' to directory >> To: Danny Yoo >> >> >> Also, >> I had this code working >> >> import os >> >> path = '/Users/felishalawrence/testswps/vol1' >> for file in os.listdir(path): >> newFile = file[:file.index("v")]+"v20" >> >> print newFile >> and now I am getting this error >> >> ValueError: substring not found >> >> I did not change anything >> > > Have you checked that no new files have been created - possibly by your > code, that don't conform to your expected naming style? > > Try putting a 'print file' before the name modification to see what the > name that causes the error looks like. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Felisha Lawrence Howard University Program for Atmospheric Sciences(HUPAS), Graduate Student NASA URC/BCCSO Graduate Fellow NOAA NCAS Graduate Fellow Graduate Student Association for Atmospheric Sciences(GSAAS), Treasurer (240)-535-6665 (cell) felisha.lawrence at gmail.com (email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Sep 9 22:26:14 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 9 Sep 2014 16:26:14 -0400 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540EF247.30900@c12.in> References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: On Tue, Sep 9, 2014 at 8:27 AM, Mirage Web Studio wrote: > > Hello, > > I am not an advanced programmer, but am very good with keyboard and find > using tabs for syntax and formatting very helpful. But in this list and > other python documentation i have repeatedly seen people recommending > use of spaces. > > I know that i can use any of them and use tabs as my preference. But i > would like to understand why hitting the poor keyboard 4/8/12 times is > preferred than just hitting it 1/2/3 times. Most text editors let you set the tab key to actually produce spaces, and the ctl-tab key to jump back. If you say what editor you are using, someone will be able to tell you how to set that up > > Thank you > > George > > > > --- > This email is free from viruses and malware because avast! Antivirus > protection is active. > http://www.avast.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From wrw at mac.com Tue Sep 9 21:58:15 2014 From: wrw at mac.com (William Ray Wing) Date: Tue, 09 Sep 2014 15:58:15 -0400 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540EF247.30900@c12.in> References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: <48E36072-FF52-49CA-A863-616A6D219B3D@mac.com> On Sep 9, 2014, at 8:27 AM, Mirage Web Studio wrote: > > Hello, > > I am not an advanced programmer, but am very good with keyboard and find > using tabs for syntax and formatting very helpful. But in this list and > other python documentation i have repeatedly seen people recommending > use of spaces. > > I know that i can use any of them and use tabs as my preference. But i > would like to understand why hitting the poor keyboard 4/8/12 times is > preferred than just hitting it 1/2/3 times. > > Thank you > > George Most of us use editors that expand tabs to a programmable number of spaces. -Bill From dyoo at hashcollision.org Tue Sep 9 23:02:09 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Sep 2014 14:02:09 -0700 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540EF247.30900@c12.in> References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: > I am not an advanced programmer, but am very good with keyboard and find > using tabs for syntax and formatting very helpful. But in this list and > other python documentation i have repeatedly seen people recommending > use of spaces. Usually, you want to match the style used by the majority of the community. According to the community PEP-8: http://legacy.python.org/dev/peps/pep-0008/#tabs-or-spaces it's spaces, and in particular, four spaces: http://legacy.python.org/dev/peps/pep-0008/#indentation The overriding reason, as I understand it, is not technical, but rather social: influential folks used that indentation level, the style spread, and the community generally followed that style. Now it's the majority. There is value in coming to terms with this: there are bigger, more important issues out there. Like big-endian vs little-endian. :P > I know that i can use any of them and use tabs as my preference. But i > would like to understand why hitting the poor keyboard 4/8/12 times is > preferred than just hitting it 1/2/3 times. You can use an editor that will do the right thing, but still let you use your tab key the way you want. What editor are you using now? Best of wishes! From alan.gauld at btinternet.com Wed Sep 10 01:30:52 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Sep 2014 00:30:52 +0100 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540EF247.30900@c12.in> References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: On 09/09/14 13:27, Mirage Web Studio wrote: > would like to understand why hitting the poor keyboard 4/8/12 times is > preferred than just hitting it 1/2/3 times. Its not, as others have already said, you set the tab key to insert spaces. Of course you usually have to delete those spaces manually - but hopefully that's a relatively rare event - and there are usually short cuts to delete to start of line.! But spaces are preferred because they are a fixed size whereas different editors/browsers display tabs differently. And a common size is 8 space equivalent - which looks bad if there are 3 or 4 levels of indentation, and usually requires more line wrapping. OTOH 4 spaces is 4 spaces regardless of the viewer used. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From codemonkey at inbox.com Wed Sep 10 04:56:55 2014 From: codemonkey at inbox.com (Deb Wyatt) Date: Tue, 9 Sep 2014 18:56:55 -0800 Subject: [Tutor] Real world use of recursion Message-ID: Sorry to bother you all with what you might consider trivia, but someone in my course forum posted this statement: "I have never seen or heard of real uses of recursion except for proving cleverness," so I thought I would ask you all if that is true. Is it really not used in real world applications? Thanks in advance, Deb in WA, USA ____________________________________________________________ Can't remember your password? Do you need a strong and secure password? Use Password manager! It stores your passwords & protects your account. Check it out at http://mysecurelogon.com/password-manager From robertvstepp at gmail.com Tue Sep 9 22:21:14 2014 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 9 Sep 2014 15:21:14 -0500 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: <540EF247.30900@c12.in> References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: On Tue, Sep 9, 2014 at 7:27 AM, Mirage Web Studio wrote: > > Hello, > > I am not an advanced programmer, but am very good with keyboard and find > using tabs for syntax and formatting very helpful. But in this list and > other python documentation i have repeatedly seen people recommending > use of spaces. > > I know that i can use any of them and use tabs as my preference. But i > would like to understand why hitting the poor keyboard 4/8/12 times is > preferred than just hitting it 1/2/3 times. I will allow the experts to answer your root question. I just want to point out that most editors have a setting where hitting tab results in spaces being inserted (of the appropriate number) instead of tab characters. Thus you can use your preferred tab key and follow recommended technique! -- boB From admin at c12.in Wed Sep 10 00:29:59 2014 From: admin at c12.in (Mirage Web Studio) Date: Wed, 10 Sep 2014 03:59:59 +0530 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: <540F7F67.2040104@c12.in> Thank you and everybody else for the reply. I am using pycharm and i have found the way to produce four spaces for single tab key press. George On 10-Sep-14 2:32 AM, Danny Yoo wrote: >> I am not an advanced programmer, but am very good with keyboard and find >> using tabs for syntax and formatting very helpful. But in this list and >> other python documentation i have repeatedly seen people recommending >> use of spaces. > > > Usually, you want to match the style used by the majority of the > community. According to the community PEP-8: > > http://legacy.python.org/dev/peps/pep-0008/#tabs-or-spaces > > it's spaces, and in particular, four spaces: > > http://legacy.python.org/dev/peps/pep-0008/#indentation > > The overriding reason, as I understand it, is not technical, but > rather social: influential folks used that indentation level, the > style spread, and the community generally followed that style. Now > it's the majority. > > > There is value in coming to terms with this: there are bigger, more > important issues out there. > > Like big-endian vs little-endian. :P > > >> I know that i can use any of them and use tabs as my preference. But i >> would like to understand why hitting the poor keyboard 4/8/12 times is >> preferred than just hitting it 1/2/3 times. > > You can use an editor that will do the right thing, but still let you > use your tab key the way you want. What editor are you using now? > > > Best of wishes! > --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From dyoo at hashcollision.org Wed Sep 10 07:11:40 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Sep 2014 22:11:40 -0700 Subject: [Tutor] Fwd: Re: Real world use of recursion In-Reply-To: References: Message-ID: Sorry, forgot to reply to all. ---------- Forwarded message ---------- From: "Danny Yoo" Date: Sep 9, 2014 10:10 PM Subject: Re: [Tutor] Real world use of recursion To: "Deb Wyatt" Cc: > > On Sep 9, 2014 8:07 PM, "Deb Wyatt" wrote: > > > > Sorry to bother you all with what you might consider trivia, but someone in my course forum posted this statement: > > > > "I have never seen or heard of real uses of recursion except for proving cleverness," > > Then they haven't seen much yet. > > Particularly, they may not realize it, but processing HTML is all about dealing with recursive data structures. > > Or they haven't written a compiler, in which case is all about recursive walks over tree structures. > > Or they haven't done any data processing involving parsing with recursive descent. > > Or they haven't done any optimization problems where knowing recursion completely opens up dynamic programming techniques. > > In short, heck yes I use it! Recursion is a tool, a standard technique that a professional programmer should have in their tool belt. Maybe not every program uses it, but it comes up enough that the comment from the forum is laughably wrong. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Wed Sep 10 07:18:37 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Sep 2014 22:18:37 -0700 Subject: [Tutor] Real world use of recursion In-Reply-To: References: Message-ID: Hi Deb, For good training on recursion, I can't think of better material than: http://www.ccs.neu.edu/home/matthias/HtDP2e/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Sep 10 07:48:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Sep 2014 06:48:54 +0100 Subject: [Tutor] Real world use of recursion In-Reply-To: References: Message-ID: On 10/09/14 03:56, Deb Wyatt wrote: > "I have never seen or heard of real uses of recursion except for proving cleverness," > > so I thought I would ask you all if that is true. Is it really not used in real world applications? Its often used in prototyping and then converted to non-recursive solutions for scalability. But that's not because recursion is bad its because many programming languages have limited implementations of recursion (like Python's limit on how many levels you can go). In languages like Lisp, Scheme, and Haskell, recursion is fundamental to the language and not limited so it is used much more heavily. But even with its limitations I use recursion in real world programs at least once or twice a year. Its not a regular technique but it is a powerful one that has its place along with the other functional programming techniques like map(), reduce() and lambdas(which are also limited in Python). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jarod_v6 at libero.it Wed Sep 10 11:20:38 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 10 Sep 2014 11:20:38 +0200 (CEST) Subject: [Tutor] Re subprocess Message-ID: <30669640.4615051410340838372.JavaMail.httpd@webmail-07.iol.local> If I follow the exmple I have this type of error: File "./RNA_prova.py", line 73, in run for line in p1.stdout(): TypeError: 'NoneType' object is not callable This is the class I use: def run(cmd,pi): import subprocess import time import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % (levelname)s - %(message)s") #logging.debug(" Running pipelines: %s" % (cmd)) # setup logging log_file = "None" tou = "file"+"_.log.txt" if log_file is not None: logfh = open(tou, "w") else: logfh = None print "####################################################" p1 = subprocess.Popen(cmd,shell=True,stdout=logfh,stderr=logfh,cwd=pi) #logging.info(" Running pipelines: %s" % (cmd)) for line in p1.stdout(): process(line) p1.stdout.close() if p.wait() != 0: raise Exception # end logging if logfh is not None: logfh.close() return 0 How can be sure the process start finish before to proced with the other comands? thanks in advance for any help! >----Messaggio originale---- >Da: tutor-request at python.org >Data: 09/09/2014 17.05 >A: >Ogg: Tutor Digest, Vol 127, Issue 27 > >Send Tutor mailing list submissions to > tutor at python.org > >To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor >or, via email, send a message with subject or body 'help' to > tutor-request at python.org > >You can reach the person managing the list at > tutor-owner at python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. Re: Good approach regarding classes attributes (Joel Goldstick) > 2. Re: Understand subprocess poll (Peter Otten) > 3. Re: Understand subprocess poll (jarod_v6 at libero.it) > 4. Re: Good approach regarding classes attributes (Sydney Shall) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Tue, 9 Sep 2014 10:05:09 -0400 >From: Joel Goldstick >Cc: "tutor at python.org" >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: > >Content-Type: text/plain; charset=UTF-8 > >On Tue, Sep 9, 2014 at 10:02 AM, Sydney Shall wrote: >> On 09/09/2014 15:44, Peter Otten wrote: >> >> Sydney Shall wrote: >> >> On 08/09/2014 18:39, Alan Gauld wrote: >> >> On 08/09/14 15:17, Juan Christian wrote: >> >> One tiny tweak... >> >> class User(): >> >> You don't need the parens after User. You don;t have any superclasses >> so they do nothing. Python convention for an empty parent list is just >> to leave the parens off: >> >> class User: >> >> A simple question from a newbie, in response to this surprise. >> Is it not helpful to always put (object) as the parent, if the class is >> not itself a sub-class? >> >> The answer differs between Python 2 and 3. In Python 3 >> >> class C: # preferred in Python 3 >> pass >> >> and >> >> class C(object): >> pass >> >> are the same, so there is no point adding the explicit object inheritance. >> >> In Python 2 however >> >> class C: >> pass >> >> will create a "classic class" whereas >> >> class C(object): # preferred in Python 2 >> pass >> >> is a "newstyle class". The most notable difference between these is that >> properties work correctly only with newstyle classes. Therefore making all >> your classes "newstyle" is a good idea. >> >> And while I am writing, what does OP stand for in this list? >> >> Original Poster, as Leam says. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> Thanks Peter, most helpful. >> I was taught with Python 2.7, so now I understand the advice. >> >> >> -- >> Sydney Shall >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > >Please post in plain text > >-- >Joel Goldstick >http://joelgoldstick.com > > >------------------------------ > >Message: 2 >Date: Tue, 09 Sep 2014 16:18:40 +0200 >From: Peter Otten <__peter__ at web.de> >To: tutor at python.org >Subject: Re: [Tutor] Understand subprocess poll >Message-ID: >Content-Type: text/plain; charset="ISO-8859-1" > >Wolfgang Maier wrote: > >> On 09/09/2014 11:45 AM, Peter Otten wrote: >>> jarod_v6 at libero.it wrote: >>> >>>> I want to use subprocess for run some programs But I need to be sure the >>>> program end before continue with the other: >>>> >>>> subprocess.call("ls") >>>> cmd1 = i >>>> p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) >>>> >>>> while True: >>>> if p1.poll() is None: >>>> time.sleep(3) >>>> >>>> pass >>>> if p1.poll()==0: >>>> print '#' >>>> break >>>> if p1.poll() is not None and p1.poll() != 0: >>>> raise Exception('Error building Alignment using star with hg19 >>>> database') >>> >>>> This are not working. How can I do? >>>> thanks in advance for the precious help >>>> bw, >>> >>> I don't understand why you would need this loop. Why don't you use >>> subprocess.call() and be done? >>> >> >> The OP is piping the process stdout so I assume he is going to read from >> it in place of the pass in his example. >> Since the subprocess is doing genome-wide sequence alignment (at least I >> guess so from the exception string) there will be lots of output, which >> would cause subprocess.call() to block. >> >> Assuming that the posted code was indented correctly and was otherwise >> run as posted this could also be the answer to the original question: >> you have to keep on consuming data from the pipe or its buffer is going >> to fill up and block everyhing. With a simple pass statement you do not >> achieve anything that you can't do with call. > >Ah, you're right. > >I still don't see where the need to poll arises, I'd expect something like > >p = subprocess.Popen(cmd, ..., stdout=PIPE) >for line in p.stdout: > process(line) > >p.stdout.close() >if p.wait() != 0: > raise Exception > >to work. > > > >------------------------------ > >Message: 3 >Date: Tue, 9 Sep 2014 16:36:47 +0200 (CEST) >From: "jarod_v6 at libero.it" >To: >Subject: Re: [Tutor] Understand subprocess poll >Message-ID: > <28501232.4398921410273407217.JavaMail.httpd at webmail-07.iol.local> >Content-Type: text/plain;charset="UTF-8" > >Thanks for yhe help! >The comand run is this > >the class created are this: >def run(cmd,pi): > import subprocess > import time > import logging > > logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % >(levelname)s - %(messag >e)s") > > #logging.debug(" Running pipelines: %s" % (cmd)) > # setup logging > log_file = "None" > tou = "file"+"_.log.txt" > if log_file is not None: > logfh = open(tou, "w") > > else: > logfh = None > print "####################################################" > > > p1 = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=logfh, >cwd=pi) > > #logging.info(" Running pipelines: %s" % (cmd)) > while True: > if p1.poll() is None: > time.sleep(3) > pass > if p1.poll()==0: > print 'Finish this step.' > logging.info("###################: %s %s" % (cmd,time.ctime())) > break > if p1.poll() is not None and p1.poll() != 0: > raise Exception('Not working please check the error') > # end logging > if logfh is not None: > logfh.close() > > return 0 > > >step_2_out =["~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir >/home/sbsuser/d >atabases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn %s %s -- >runThreadN 12 --readFilesCommand zcat > "%(dx,sn)] > >The problems is the script end the process but not allign all the data. If I >use the comand line the same code the process work. >How can resolve this issue? > > > > >>----Messaggio originale---- >>Da: tutor-request at python.org >>Data: 09/09/2014 16.02 >>A: >>Ogg: Tutor Digest, Vol 127, Issue 26 >> >>Send Tutor mailing list submissions to >> tutor at python.org >> >>To subscribe or unsubscribe via the World Wide Web, visit >> https://mail.python.org/mailman/listinfo/tutor >>or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >>You can reach the person managing the list at >> tutor-owner at python.org >> >>When replying, please edit your Subject line so it is more specific >>than "Re: Contents of Tutor digest..." >> >> >>Today's Topics: >> >> 1. Re: Good approach regarding classes attributes (Sydney Shall) >> 2. Re: Good approach regarding classes attributes (leam hall) >> 3. Re: Understand subprocess poll (Wolfgang Maier) >> 4. Re: Good approach regarding classes attributes (Peter Otten) >> 5. Re: Good approach regarding classes attributes (Juan Christian) >> 6. Re: Good approach regarding classes attributes (Sydney Shall) >> >> >>---------------------------------------------------------------------- >> >>Message: 1 >>Date: Tue, 09 Sep 2014 15:09:32 +0200 >>From: Sydney Shall >>To: tutor at python.org >>Subject: Re: [Tutor] Good approach regarding classes attributes >>Message-ID: <540EFC0C.3000202 at virginmedia.com> >>Content-Type: text/plain; charset="windows-1252"; Format="flowed" >> >>On 08/09/2014 18:39, Alan Gauld wrote: >>> On 08/09/14 15:17, Juan Christian wrote: >>> >>> One tiny tweak... >>> >>>> class User(): >>> >>> You don't need the parens after User. You don;t have any superclasses >>> so they do nothing. Python convention for an empty parent list is just >>> to leave the parens off: >>> >>> class User: >>> >>A simple question from a newbie, in response to this surprise. >>Is it not helpful to always put (object) as the parent, if the class is >>not itself a sub-class? >>And while I am writing, what does OP stand for in this list? >> >> >>-- >>Sydney Shall >>-------------- next part -------------- >>An HTML attachment was scrubbed... >>URL: org/pipermail/tutor/attachments/20140909/ebcdb792/attachment-0001.html> >> >>------------------------------ >> >>Message: 2 >>Date: Tue, 9 Sep 2014 09:14:39 -0400 >>From: leam hall >>To: tutor >>Subject: Re: [Tutor] Good approach regarding classes attributes >>Message-ID: >> >>Content-Type: text/plain; charset=UTF-8 >> >>On Tue, Sep 9, 2014 at 9:09 AM, Sydney Shall wrote: >> >>> And while I am writing, what does OP stand for in this list? >> >>"Original Poster". So I understand. Won't answer the Python question >>since I'm a newbie here myself. >> >>-- >>Mind on a Mission >> >> >>------------------------------ >> >>Message: 3 >>Date: Tue, 09 Sep 2014 15:05:11 +0200 >>From: Wolfgang Maier >>To: tutor at python.org >>Subject: Re: [Tutor] Understand subprocess poll >>Message-ID: <540EFB07.5050901 at biologie.uni-freiburg.de> >>Content-Type: text/plain; charset=utf-8; format=flowed >> >>On 09/09/2014 11:45 AM, Peter Otten wrote: >>> jarod_v6 at libero.it wrote: >>> >>>> I want to use subprocess for run some programs But I need to be sure the >>>> program end before continue with the other: >>>> >>>> subprocess.call("ls") >>>> cmd1 = i >>>> p1 = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE) >>>> >>>> while True: >>>> if p1.poll() is None: >>>> time.sleep(3) >>>> >>>> pass >>>> if p1.poll()==0: >>>> print '#' >>>> break >>>> if p1.poll() is not None and p1.poll() != 0: >>>> raise Exception('Error building Alignment using star with hg19 >>>> database') >>> >>>> This are not working. How can I do? >>>> thanks in advance for the precious help >>>> bw, >>> >>> I don't understand why you would need this loop. Why don't you use >>> subprocess.call() and be done? >>> >> >>The OP is piping the process stdout so I assume he is going to read from >>it in place of the pass in his example. >>Since the subprocess is doing genome-wide sequence alignment (at least I >>guess so from the exception string) there will be lots of output, which >>would cause subprocess.call() to block. >> >>Assuming that the posted code was indented correctly and was otherwise >>run as posted this could also be the answer to the original question: >>you have to keep on consuming data from the pipe or its buffer is going >>to fill up and block everyhing. With a simple pass statement you do not >>achieve anything that you can't do with call. >> >>Wolfgang >> >> >> >>------------------------------ >> >>Message: 4 >>Date: Tue, 09 Sep 2014 15:44:22 +0200 >>From: Peter Otten <__peter__ at web.de> >>To: tutor at python.org >>Subject: Re: [Tutor] Good approach regarding classes attributes >>Message-ID: >>Content-Type: text/plain; charset="ISO-8859-1" >> >>Sydney Shall wrote: >> >>> On 08/09/2014 18:39, Alan Gauld wrote: >>>> On 08/09/14 15:17, Juan Christian wrote: >>>> >>>> One tiny tweak... >>>> >>>>> class User(): >>>> >>>> You don't need the parens after User. You don;t have any superclasses >>>> so they do nothing. Python convention for an empty parent list is just >>>> to leave the parens off: >>>> >>>> class User: >>>> >>> A simple question from a newbie, in response to this surprise. >>> Is it not helpful to always put (object) as the parent, if the class is >>> not itself a sub-class? >> >>The answer differs between Python 2 and 3. In Python 3 >> >>class C: # preferred in Python 3 >> pass >> >>and >> >>class C(object): >> pass >> >>are the same, so there is no point adding the explicit object inheritance. >> >>In Python 2 however >> >>class C: >> pass >> >>will create a "classic class" whereas >> >>class C(object): # preferred in Python 2 >> pass >> >>is a "newstyle class". The most notable difference between these is that >>properties work correctly only with newstyle classes. Therefore making all >>your classes "newstyle" is a good idea. >> >>> And while I am writing, what does OP stand for in this list? >> >>Original Poster, as Leam says. >> >> >> >> >>------------------------------ >> >>Message: 5 >>Date: Tue, 9 Sep 2014 10:54:22 -0300 >>From: Juan Christian >>Cc: "tutor at python.org" >>Subject: Re: [Tutor] Good approach regarding classes attributes >>Message-ID: >> >>Content-Type: text/plain; charset="utf-8" >> >>On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de > >>wrote: >> >>> >>> PS: This is not about being pythonic, but it might be more convenient for >>> client code if you use datetime objects instead of timestamps: >>> >>> >>> import datetime >>> >>> last_logoff = datetime.datetime.utcfromtimestamp(1410065399) >>> >>> print(last_logoff) >>> 2014-09-07 04:49:59 >>> >> >>Yes, I'll do it for sure, the API response is indeed returned that way to >>make things easier. >>-------------- next part -------------- >>An HTML attachment was scrubbed... >>URL: org/pipermail/tutor/attachments/20140909/aacbe49f/attachment-0001.html> >> >>------------------------------ >> >>Message: 6 >>Date: Tue, 09 Sep 2014 16:02:01 +0200 >>From: Sydney Shall >>To: tutor at python.org >>Subject: Re: [Tutor] Good approach regarding classes attributes >>Message-ID: <540F0859.5070802 at virginmedia.com> >>Content-Type: text/plain; charset="windows-1252"; Format="flowed" >> >>On 09/09/2014 15:44, Peter Otten wrote: >>> Sydney Shall wrote: >>> >>>> On 08/09/2014 18:39, Alan Gauld wrote: >>>>> On 08/09/14 15:17, Juan Christian wrote: >>>>> >>>>> One tiny tweak... >>>>> >>>>>> class User(): >>>>> You don't need the parens after User. You don;t have any superclasses >>>>> so they do nothing. Python convention for an empty parent list is just >>>>> to leave the parens off: >>>>> >>>>> class User: >>>>> >>>> A simple question from a newbie, in response to this surprise. >>>> Is it not helpful to always put (object) as the parent, if the class is >>>> not itself a sub-class? >>> The answer differs between Python 2 and 3. In Python 3 >>> >>> class C: # preferred in Python 3 >>> pass >>> >>> and >>> >>> class C(object): >>> pass >>> >>> are the same, so there is no point adding the explicit object inheritance. >>> >>> In Python 2 however >>> >>> class C: >>> pass >>> >>> will create a "classic class" whereas >>> >>> class C(object): # preferred in Python 2 >>> pass >>> >>> is a "newstyle class". The most notable difference between these is that >>> properties work correctly only with newstyle classes. Therefore making all >>> your classes "newstyle" is a good idea. >>> >>>> And while I am writing, what does OP stand for in this list? >>> Original Poster, as Leam says. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >>Thanks Peter, most helpful. >>I was taught with Python 2.7, so now I understand the advice. >> >> >>-- >>Sydney Shall >>-------------- next part -------------- >>An HTML attachment was scrubbed... >>URL: org/pipermail/tutor/attachments/20140909/502cb8e0/attachment.html> >> >>------------------------------ >> >>Subject: Digest Footer >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>https://mail.python.org/mailman/listinfo/tutor >> >> >>------------------------------ >> >>End of Tutor Digest, Vol 127, Issue 26 >>************************************** >> > > > > >------------------------------ > >Message: 4 >Date: Tue, 09 Sep 2014 17:05:46 +0200 >From: Sydney Shall >To: tutor at python.org >Subject: Re: [Tutor] Good approach regarding classes attributes >Message-ID: <540F174A.1000709 at virginmedia.com> >Content-Type: text/plain; charset="windows-1252"; Format="flowed" > >On 09/09/2014 16:05, Joel Goldstick wrote: >> On Tue, Sep 9, 2014 at 10:02 AM, Sydney Shall wrote: >>> On 09/09/2014 15:44, Peter Otten wrote: >>> >>> Sydney Shall wrote: >>> >>> On 08/09/2014 18:39, Alan Gauld wrote: >>> >>> On 08/09/14 15:17, Juan Christian wrote: >>> >>> One tiny tweak... >>> >>> class User(): >>> >>> You don't need the parens after User. You don;t have any superclasses >>> so they do nothing. Python convention for an empty parent list is just >>> to leave the parens off: >>> >>> class User: >>> >>> A simple question from a newbie, in response to this surprise. >>> Is it not helpful to always put (object) as the parent, if the class is >>> not itself a sub-class? >>> >>> The answer differs between Python 2 and 3. In Python 3 >>> >>> class C: # preferred in Python 3 >>> pass >>> >>> and >>> >>> class C(object): >>> pass >>> >>> are the same, so there is no point adding the explicit object inheritance. >>> >>> In Python 2 however >>> >>> class C: >>> pass >>> >>> will create a "classic class" whereas >>> >>> class C(object): # preferred in Python 2 >>> pass >>> >>> is a "newstyle class". The most notable difference between these is that >>> properties work correctly only with newstyle classes. Therefore making all >>> your classes "newstyle" is a good idea. >>> >>> And while I am writing, what does OP stand for in this list? >>> >>> Original Poster, as Leam says. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >>> Thanks Peter, most helpful. >>> I was taught with Python 2.7, so now I understand the advice. >>> >>> >>> -- >>> Sydney Shall >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >> Please post in plain text >> >My apologies. I thought I was. I will immediately change it. > >-- >Sydney Shall >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Subject: Digest Footer > >_______________________________________________ >Tutor maillist - Tutor at python.org >https://mail.python.org/mailman/listinfo/tutor > > >------------------------------ > >End of Tutor Digest, Vol 127, Issue 27 >************************************** > From Steve.Flynn at capita.co.uk Wed Sep 10 10:46:23 2014 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Wed, 10 Sep 2014 09:46:23 +0100 Subject: [Tutor] Real world use of recursion In-Reply-To: References: Message-ID: > Sorry to bother you all with what you might consider trivia, but someone > in my course forum posted this statement: > > "I have never seen or heard of real uses of recursion except for proving > cleverness," > > so I thought I would ask you all if that is true. Is it really not used > in real world applications? Any code which walks a tree is almost certainly going to be using recursion. This is everything from a chess game analyser, to image processing software, to your browser when it's rendering a web page and much more in-between. There's a very good reason why every single course in coding or any form of computer science is going to explain it to you at some stage in the course. It's used a lot, in a lot of places. S. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From wolfgang.maier at biologie.uni-freiburg.de Wed Sep 10 12:11:56 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Wed, 10 Sep 2014 12:11:56 +0200 Subject: [Tutor] Re subprocess In-Reply-To: <30669640.4615051410340838372.JavaMail.httpd@webmail-07.iol.local> References: <30669640.4615051410340838372.JavaMail.httpd@webmail-07.iol.local> Message-ID: On 09/10/2014 11:20 AM, jarod_v6 at libero.it wrote: > If I follow the exmple I have this type of error: > File "./RNA_prova.py", line 73, in run > for line in p1.stdout(): > TypeError: 'NoneType' object is not callable > > You have at least two errors in your script below: This time you're not piping the subprocess stdout, but redirecting it to a file so nothing is ever going to appear in p1.stdout. Second, p1.stdout is not a method so you're not supposed to call it. Use p1.stdout instead of p1.stdout(). > This is the class I use: > def run(cmd,pi): > import subprocess > import time > import logging > > logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % > (levelname)s - %(message)s") > > #logging.debug(" Running pipelines: %s" % (cmd)) > # setup logging > log_file = "None" > tou = "file"+"_.log.txt" > if log_file is not None: > logfh = open(tou, "w") > > else: > logfh = None > print "####################################################" > > > p1 = subprocess.Popen(cmd,shell=True,stdout=logfh,stderr=logfh,cwd=pi) > > #logging.info(" Running pipelines: %s" % (cmd)) > > for line in p1.stdout(): > process(line) > > p1.stdout.close() > if p.wait() != 0: > raise Exception > # end logging > if logfh is not None: > logfh.close() > > return 0 > > How can be sure the process start finish before to proced with the other > comands? > thanks in advance for any help! > For additional help it would be more motivating if we could discuss some fixed concrete code along with precise error descriptions instead of ever shifting pieces of code. From steve at pearwood.info Wed Sep 10 12:39:17 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Sep 2014 20:39:17 +1000 Subject: [Tutor] Re subprocess In-Reply-To: <30669640.4615051410340838372.JavaMail.httpd@webmail-07.iol.local> References: <30669640.4615051410340838372.JavaMail.httpd@webmail-07.iol.local> Message-ID: <20140910103917.GD9293@ando.pearwood.info> On Wed, Sep 10, 2014 at 11:20:38AM +0200, jarod_v6 at libero.it wrote: > If I follow the exmple I have this type of error: > File "./RNA_prova.py", line 73, in run > for line in p1.stdout(): > TypeError: 'NoneType' object is not callable Somehow you have p1.stdout set to None. You can confirm this by inserting this line immediately before line 73 with: print p1.stdout which will almost certainly print "None" just before the exception. More comments below: > This is the class I use: > def run(cmd,pi): > import subprocess > import time > import logging This is not a class, it is a function ("def", rather than "class"). Also, it is normally a good idea to have all your imports done once, at the top of the module, rather than inside a function or method. And it is very unusual to use two tabs for a single indent level. It is recommended to use one tab or 4 spaces. > logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % > (levelname)s - %(message)s") > #logging.debug(" Running pipelines: %s" % (cmd)) > # setup logging > log_file = "None" Here you set the log_file to the string "None". What is the purpose of this? It seems like a strange thing to do. > tou = "file"+"_.log.txt" > if log_file is not None: Since you have just set the variable log_file to a string, it CANNOT possibly be None. So this clause will ALWAYS run, and the "else" clause is dead code that cannot possibly occur. *Provided* that this is the code you are actually running. I doubt this is actually the code you are running, since the error shown tells you that p1.stdout is set to None, which requires the else clause to run. So I think that this code you show us and the code you are actually running are not the same. Am I right? > logfh = open(tou, "w") > else: > logfh = None > print "####################################################" > p1 = subprocess.Popen(cmd,shell=True,stdout=logfh,stderr=logfh,cwd=pi) For p1.stdout to be set to None, logfh must be set to None. You can check that by putting: print logfh, p1.stdout here. Please stop replying to Digests without trimming the hundreds and hundreds of lines of irrelevent quoted messages. -- Steven From timomlists at gmail.com Wed Sep 10 12:40:00 2014 From: timomlists at gmail.com (Timo) Date: Wed, 10 Sep 2014 12:40:00 +0200 Subject: [Tutor] usage difference between tabs and spaces In-Reply-To: References: <540BC08A.4000308@c12.in> <540EF247.30900@c12.in> Message-ID: <54102A80.7030008@gmail.com> Op 10-09-14 om 01:30 schreef Alan Gauld: > Its not, as others have already said, you set the tab > key to insert spaces. Of course you usually have to delete > those spaces manually - but hopefully that's a relatively > rare event - and there are usually short cuts to delete > to start of line.! > > Shift+tab does that in my editor. I don't know if this is a common keybinding or editor specific. Timo From dyoo at hashcollision.org Wed Sep 10 19:55:02 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 10 Sep 2014 10:55:02 -0700 Subject: [Tutor] Real world use of recursion In-Reply-To: References: Message-ID: > Any code which walks a tree is almost certainly going to be using > recursion. This is everything from a chess game analyser, to image > processing software, to your browser when it's rendering a web page and > much more in-between. For the comment about Chess, see minmax for a concrete example: http://en.wikipedia.org/wiki/Minimax#Pseudocode Note the recursion in the pseudocode. Here, it's used to power the basic concept of "If I make this move, and my opponent makes this move, and I respond with this move, and they make that move..." For a concrete example with image processing: the "color quantization" problem with Octrees: http://en.wikipedia.org/wiki/Octree From brian.van.den.broek at gmail.com Thu Sep 11 09:19:02 2014 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Thu, 11 Sep 2014 00:19:02 -0700 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: On 7 September 2014 21:01, Danny Yoo wrote: > Let's use a concrete example: say that we'd like to make sure a > Person's name is always capitalized. We might try to enforce this > capitalization property in the constructor. Hi all, I've just again experienced a new employer that tells my students my name is 'Van Den Broek' when I tell them that it is 'van den Broek.' This is the third time this week I've encountered this as a programming example. Perhaps the use of the example is responsible for the false belief amongst programmers that a surname always starts with a captial letter. (Also delightful is the view that no name can contain spaces.) For the love of puppies, can people please stop using this example?! (Apologies to Danny; as the other two cases I saw recently were in books, it was easiest to lash out against this example.) notVanDenly yours, Brian vdB From radhikag992 at gmail.com Thu Sep 11 15:34:32 2014 From: radhikag992 at gmail.com (Radhika Gaonkar) Date: Thu, 11 Sep 2014 19:04:32 +0530 Subject: [Tutor] Problem understanding the asarray function of numpy Message-ID: I have an implementation of lsa, that I need to modify. I am having some trouble understanding the code. This is the line where I am stuck: DocsPerWord = sum(asarray(self.A > 0, 'i'), axis=1) The link for this implementation is : http://www.puffinwarellc.com/index.php/news-and-articles/articles/33-latent-semantic-analysis-tutorial.html?showall=1 Here, A is a matrix of size vocabulary_Size X number_ofDocs As far as the documentation of asarray is concerned, this should return an array interpretation of the matrix A. But, we need to sum each row. What is happening here? Thanks! -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From jarod_v6 at libero.it Thu Sep 11 15:52:38 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Thu, 11 Sep 2014 15:52:38 +0200 (CEST) Subject: [Tutor] Re subprocess Message-ID: <15610010.5153601410443558764.JavaMail.httpd@webmail-08.iol.local> Thanks for the suggestion and corrections. I don't put the else staement onf if log_file but now I realize my mistake I have 3 comand to do: step_1_out =["STAR --genomeDir /home/sbsuser/databases/Starhg19/GenomeDir/ -- runMode alignReads --readFilesIn %s %s --runThreadN 12 --readFilesCommand zcat "%(dx[i],sn[i])] step_2_out = ["STAR --runMode genomeGenerate --genomeDir %s -- genomeFastaFiles ~/databases/bowtie2Database/hg19.fa --sjdbFileChrStartEnd % sSJ.out.tab --sjdbOverhang 49 --runThreadN 12" %(tx[i],tx[i])] step_3_out =["STAR --genomeDir %s --runMode alignReads --readFilesIn %s %s --runThreadN 12 --readFilesCommand zcat "%(Pos2,dx,sn)] So I need to run one step a time. cmd is the comand (step_1_out) e pi is the directory of the files. def run(cmd,pi): import subprocess import time import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % (levelname)s - %(message)s") #logging.debug(" Running pipelines: %s" % (cmd)) # setup logging tou = "log.txt" logfh = open(tou, "r+") p1 = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=logfh, cwd=pi) #logging.info(" Running pipelines: %s" % (cmd)) while True: if p1.poll() is None: time.sleep(120) pass if p1.poll()==0: print 'Finish this step.' logging.info("###################: %s %s" % (cmd,time.ctime())) break if p1.poll() is not None and p1.poll() != 0: raise Exception('Not working please check the error') # end logging logfh.close() return 0 I don't understand where is the error in the code above. If I change the code in this way seems work def run(cmd,pi): import subprocess import time import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(name)s - % (levelname)s - %(messag e)s") #logging.debug(" Running pipelines: %s" % (cmd)) # setup logging log_file = "None" tou = "og.txt" logfh = open(tou, "r+") p1 = subprocess.Popen(cmd,shell=True,stdout=logfh,stderr=logfh,cwd=pi) p1.wait() #logging.info(" Running pipelines: %s" % (cmd)) return 0 Someone can explain to me when we neet to choose wait or pool? Thanks for the help From __peter__ at web.de Thu Sep 11 16:13:20 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2014 16:13:20 +0200 Subject: [Tutor] Problem understanding the asarray function of numpy References: Message-ID: Radhika Gaonkar wrote: > I have an implementation of lsa, that I need to modify. I am having some > trouble understanding the code. This is the line where I am stuck: > > DocsPerWord = sum(asarray(self.A > 0, 'i'), axis=1) > > The link for this implementation is : > http://www.puffinwarellc.com/index.php/news-and-articles/articles/33-latent-semantic-analysis-tutorial.html?showall=1 > > Here, A is a matrix of size vocabulary_Size X number_ofDocs > As far as the documentation of asarray is concerned, this should return an > array interpretation of the matrix A. But, we need to sum each row. What > is happening here? A numpy array can be multidimensional: >>> import numpy >>> a = numpy.asarray([[1,2,3],[4,5,6],[7,8,9]]) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a.shape (3, 3) >>> a[0,0] 1 >>> a[2,2] 9 So this "array" works very much like a 3x3 matrix. Now let's investigate numpy.sum() (which must not be confused with the Python's built-in sum() function): >>> numpy.sum(a) 45 >>> numpy.sum(a, axis=0) array([12, 15, 18]) >>> numpy.sum(a, axis=1) array([ 6, 15, 24]) Playing around in interactive interpreter is often helpful to learn what a function or snippet of code does. From dyoo at hashcollision.org Thu Sep 11 18:21:34 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Sep 2014 09:21:34 -0700 Subject: [Tutor] Good approach regarding classes attributes In-Reply-To: References: <20140907180051.GU9293@ando.pearwood.info> <20140907181214.GV9293@ando.pearwood.info> Message-ID: > I've just again experienced a new employer that tells my students my > name is 'Van Den Broek' when I tell them that it is 'van den Broek.' > This is the third time this week I've encountered this as a > programming example. Perhaps the use of the example is responsible for > the false belief amongst programmers that a surname always starts with > a captial letter. (Also delightful is the view that no name can > contain spaces.) > My apologies! I'll try a different example next time using strip() to remove surrounding whitespace. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Sep 11 18:26:24 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Sep 2014 09:26:24 -0700 Subject: [Tutor] Problem understanding the asarray function of numpy In-Reply-To: References: Message-ID: On 9/11/2014 6:34 AM, Radhika Gaonkar wrote: > I have an implementation of lsa, that I need to modify. I am having some > trouble understanding the code. This is the line where I am stuck: > > DocsPerWord = sum(asarray(self.A > 0, 'i'), axis=1) Python doesn't provide an axis parameter for the sum builtin -- this sum function comes from numpy. See http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html for details. Emile From juan0christian at gmail.com Thu Sep 11 18:42:49 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 13:42:49 -0300 Subject: [Tutor] Convert a list to a group of separated strings Message-ID: Let's say I have the following list: my_list = ['76561198048214059', '76561198065852182', '76561198067017670', '76561198077080978', '76561198077257977', '7656119807971 7745', '76561198088368223', '76561198144945778'] and I have a function with the following signature: def fetch_users(*steamids) Usage: fetch_users("76561198048214059", "76561198065852182", "76561198067017670", [...]) Inside the 'fetch_users' function I have a call to the API using this approach: req = urllib.request.urlopen('API_URL_HERE&steamids=' + ','.join(steamids)) This way I call the API with the following URL (example): API_URL_HERE&steamids=76561198048214059,76561198065852182 And everything works. The problem is that when I give the 'my_list' directly to 'fetch_users' function it gives me "TypeError: sequence item 0: expected str instance, list found". How can I convert it to something like "fetch_users("76561198048214059", "76561198065852182", "76561198067017670", [...])" I tried with " ''.join(my_list) " but didn't work. I think it's a very simple question but I'm struggling to find the answer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carmelos at umich.edu Thu Sep 11 17:08:04 2014 From: carmelos at umich.edu (Carmel O'Shannessy) Date: Thu, 11 Sep 2014 11:08:04 -0400 Subject: [Tutor] python qn Message-ID: Hello, times = ['50.319468', '50.319468', 't1'] I want to convert [0:2] to floats. I tried: float.times = [float(i) for i in times[:2]] but get the error msg: TypeError: can't set attributes of built-in/extension type 'float' Carmel -- -- Carmel O'Shannessy, Assoc. Prof. Department of Linguistics University of Michigan 440 Lorch Hall 611 Tappan Street Ann Arbor, MI, 48109-1220 Ph: +1 734 764 0353 Fax: +1 734 936 3406 http://www-personal.umich.edu/~carmelos/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Sep 11 19:07:42 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Sep 2014 10:07:42 -0700 Subject: [Tutor] Convert a list to a group of separated strings In-Reply-To: References: Message-ID: On Thu, Sep 11, 2014 at 9:42 AM, Juan Christian wrote: > Let's say I have the following list: my_list = ['76561198048214059', > '76561198065852182', '76561198067017670', '76561198077080978', > '76561198077257977', '7656119807971 > 7745', '76561198088368223', '76561198144945778'] > > and I have a function with the following signature: def > fetch_users(*steamids) > > Usage: fetch_users("76561198048214059", "76561198065852182", > "76561198067017670", [...]) [text cut] > The problem is that when I give the 'my_list' directly to 'fetch_users' > function it gives me "TypeError: sequence item 0: expected str instance, > list found". Hi Juan, You have a "var-arity" function called fetch_users(), and you'd like to apply it with an explicit list of arguments "my_list". In this case, you want to use the application operator: https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments ######################## fetch_users(*my_list) ######################## If you have other questions, please feel free to ask. From __peter__ at web.de Thu Sep 11 19:09:19 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2014 19:09:19 +0200 Subject: [Tutor] Convert a list to a group of separated strings References: Message-ID: Juan Christian wrote: > Let's say I have the following list: my_list = ['76561198048214059', > '76561198065852182', '76561198067017670', '76561198077080978', > '76561198077257977', '7656119807971 > 7745', '76561198088368223', '76561198144945778'] > > and I have a function with the following signature: def > fetch_users(*steamids) > > Usage: fetch_users("76561198048214059", "76561198065852182", > "76561198067017670", [...]) > > > Inside the 'fetch_users' function I have a call to the API using this > approach: req = urllib.request.urlopen('API_URL_HERE&steamids=' + > ','.join(steamids)) > > This way I call the API with the following URL (example): > > API_URL_HERE&steamids=76561198048214059,76561198065852182 > > And everything works. > > The problem is that when I give the 'my_list' directly to 'fetch_users' > function it gives me "TypeError: sequence item 0: expected str instance, > list found". > > How can I convert it to something like "fetch_users("76561198048214059", > "76561198065852182", "76561198067017670", [...])" > > I tried with " ''.join(my_list) " but didn't work. I think it's a very > simple question but I'm struggling to find the answer. You can explode the list by invoking the function with fetch_users(*my_list) # prepend the list with a star but I recommend that you change the function's signature to def fetch_users(steamids): ... and invoke it in the common way with fetch_users(my_list) That of course means that even to invoke the function with a single user you have to wrap the user's id in a list: fetch_users(["76561198048214059"]) From dyoo at hashcollision.org Thu Sep 11 19:10:39 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Sep 2014 10:10:39 -0700 Subject: [Tutor] python qn In-Reply-To: References: Message-ID: On Thu, Sep 11, 2014 at 8:08 AM, Carmel O'Shannessy wrote: > > Hello, > > times = ['50.319468', '50.319468', 't1'] > > I want to convert [0:2] to floats. > > I tried: > > float.times = [float(i) for i in times[:2]] Hi Carmel, Do you intend to have a variable named "float.times" here on the left hand side of the assignment? If so, try a different name. What's happening is not variable assignment, but member assignment. The above statement is saying: Take the "float" type, and set its "times" attribute to the right hand side. And that's almost certainly not what you want to do. From __peter__ at web.de Thu Sep 11 19:14:26 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2014 19:14:26 +0200 Subject: [Tutor] python qn References: Message-ID: Carmel O'Shannessy wrote: > times = ['50.319468', '50.319468', 't1'] > > I want to convert [0:2] to floats. > > I tried: > > float.times = [float(i) for i in times[:2]] > > but get the error msg: > > TypeError: can't set attributes of built-in/extension type 'float' Try times[:2] = [float(s) for s in times[:2]] PS: What did you expect > float.times to achieve? From juan0christian at gmail.com Thu Sep 11 19:32:45 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 14:32:45 -0300 Subject: [Tutor] Convert a list to a group of separated strings In-Reply-To: References: Message-ID: On Thu, Sep 11, 2014 at 2:07 PM, Danny Yoo wrote: > > > Hi Juan, > > You have a "var-arity" function called fetch_users(), and you'd like > to apply it with an explicit list of arguments "my_list". > > In this case, you want to use the application operator: > > > https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments > > ######################## > fetch_users(*my_list) > ######################## > > If you have other questions, please feel free to ask. > Indeed, this way works flawlessly, thanks. On Thu, Sep 11, 2014 at 2:09 PM, Peter Otten <__peter__ at web.de> wrote: > > > You can explode the list by invoking the function with > > fetch_users(*my_list) # prepend the list with a star > > but I recommend that you change the function's signature to > > def fetch_users(steamids): > ... > > and invoke it in the common way with > > fetch_users(my_list) > > That of course means that even to invoke the function with a single user > you > have to wrap the user's id in a list: > > fetch_users(["76561198048214059"]) > I was thinking about that too, I'll try to implement that way. Which one would be a more pythonic way? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Sep 11 19:43:07 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Sep 2014 10:43:07 -0700 Subject: [Tutor] Convert a list to a group of separated strings In-Reply-To: References: Message-ID: > On Thu, Sep 11, 2014 at 2:09 PM, Peter Otten <__peter__ at web.de> wrote: >> >> >> You can explode the list by invoking the function with >> >> fetch_users(*my_list) # prepend the list with a star >> >> but I recommend that you change the function's signature to >> >> def fetch_users(steamids): >> ... >> >> and invoke it in the common way with >> >> fetch_users(my_list) >> >> That of course means that even to invoke the function with a single user >> you >> have to wrap the user's id in a list: >> >> fetch_users(["76561198048214059"]) > > > I was thinking about that too, I'll try to implement that way. Which one > would be a more pythonic way? Peter's suggestion is more Pythonic. The list argument is explicit. It requires less esoteric knowledge of both vararity functions and the unpacking operator. It reads much more easily. It wins. :P From juan0christian at gmail.com Thu Sep 11 19:49:24 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 14:49:24 -0300 Subject: [Tutor] Convert a list to a group of separated strings In-Reply-To: References: Message-ID: Done. thanks guys. On Thu, Sep 11, 2014 at 2:43 PM, Danny Yoo wrote: > > On Thu, Sep 11, 2014 at 2:09 PM, Peter Otten <__peter__ at web.de> wrote: > >> > >> > >> You can explode the list by invoking the function with > >> > >> fetch_users(*my_list) # prepend the list with a star > >> > >> but I recommend that you change the function's signature to > >> > >> def fetch_users(steamids): > >> ... > >> > >> and invoke it in the common way with > >> > >> fetch_users(my_list) > >> > >> That of course means that even to invoke the function with a single user > >> you > >> have to wrap the user's id in a list: > >> > >> fetch_users(["76561198048214059"]) > > > > > > I was thinking about that too, I'll try to implement that way. Which one > > would be a more pythonic way? > > > Peter's suggestion is more Pythonic. The list argument is explicit. > It requires less esoteric knowledge of both vararity functions and the > unpacking operator. It reads much more easily. > > It wins. :P > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 11 20:43:20 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 15:43:20 -0300 Subject: [Tutor] UnicodeEncodeError in python Message-ID: I'm iterating through Steam users and friend lists. So, my program was working good, but then I got some UnicodeEncodeError randomly, I didn't know where was the problem, then I was checking the names that I got from the API by hand, and then I saw users with ?, ????, ??????, ??? and tons of others different chars in their names... How can I make a "bulletproof" program against these chars? Can Python read them using some sort of function? -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 11 21:37:03 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 16:37:03 -0300 Subject: [Tutor] UnicodeEncodeError in python In-Reply-To: <1410461594.4073.2@smtp.gmail.com> References: <1410461594.4073.2@smtp.gmail.com> Message-ID: Forget to tell, sorry. I'm using Python 3.4.1 On Thu, Sep 11, 2014 at 3:53 PM, Sebastian Silva wrote: > Hi, > Python 2 suffers from these kinds of issues frequently. > > However Python 3 does not. > > Now, to deal with different encodings in Python 2 you need to cast to > unicode type, and then decode the string into unicode. > > something like this: > > name = unicode(original_name) > name = name.decode("utf-8") > > This is assuming your data source is in fact utf-8 encoded (which is the > most likely, imhe). > > Hope it helps, > Sebastian > > El jue, 11 de sep 2014 a las 1:43 PM, Juan Christian < > juan0christian at gmail.com> escribi?: > > I'm iterating through Steam users and friend lists. >> >> So, my program was working good, but then I got some UnicodeEncodeError >> randomly, I didn't know where was the problem, then I was checking the >> names that I got from the API by hand, and then I saw users with ?, ????, >> ??????, ??? and tons of others different chars in their names... >> >> How can I make a "bulletproof" program against these chars? Can Python >> read them using some sort of function? >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 11 22:09:57 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 17:09:57 -0300 Subject: [Tutor] UnicodeEncodeError in python In-Reply-To: References: <1410461594.4073.2@smtp.gmail.com> Message-ID: On Thu, Sep 11, 2014 at 4:39 PM, Juan Christian wrote: > > Using 3.4.1 > > I did try: > > self.persona_name = unicode(personaname) > self.persona_name = personaname.decode("utf-8") > > But didn't work! > Some of the chars that brakes the program: \u0183 \u2020 \u0361 \u0649 And many others crazy chars. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 11 22:23:53 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2014 22:23:53 +0200 Subject: [Tutor] UnicodeEncodeError in python References: <1410461594.4073.2@smtp.gmail.com> Message-ID: Juan Christian wrote: > On Thu, Sep 11, 2014 at 4:39 PM, Juan Christian > wrote: >> >> Using 3.4.1 >> >> I did try: >> >> self.persona_name = unicode(personaname) >> self.persona_name = personaname.decode("utf-8") >> >> But didn't work! >> > > > Some of the chars that brakes the program: > > \u0183 > \u2020 > \u0361 > \u0649 > > And many others crazy chars. You are getting an *encoding* error, so this may be triggered when you are trying to print. Can you post the traceback? Also, what is your OS and what does $ python3 -c'import locale; print(locale.getpreferredencoding())' UTF-8 show? From juan0christian at gmail.com Thu Sep 11 22:35:16 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 11 Sep 2014 17:35:16 -0300 Subject: [Tutor] UnicodeEncodeError in python In-Reply-To: References: <1410461594.4073.2@smtp.gmail.com> Message-ID: On Thu, Sep 11, 2014 at 5:23 PM, Peter Otten <__peter__ at web.de> wrote: > > > You are getting an *encoding* error, so this may be triggered when you are > trying to print. Can you post the traceback? > > Also, what is your OS and what does > > $ python3 -c'import locale; print(locale.getpreferredencoding())' > UTF-8 > > show? Show: cp1252 PS D:\Documents\HomeBroker> py .\main.py ['O Deputado Jovem', 'Bob Swaget', 'Baldrick', 'Inigo the brave', 'KeplerBR', 'Lastemp3ror', 'Amethyst', 'wildee14', 'Le Monade'] Traceback (most recent call last): File ".\main.py", line 11, in search(my_u[0]) File ".\main.py", line 8, in search search(current) File ".\main.py", line 5, in search print([user.persona_name for user in x.get_friend_list()]) File "C:\Development\Languages\Python34\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u262d' in position 322: character maps to -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 11 23:18:54 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2014 23:18:54 +0200 Subject: [Tutor] UnicodeEncodeError in python References: <1410461594.4073.2@smtp.gmail.com> Message-ID: Juan Christian wrote: > On Thu, Sep 11, 2014 at 5:23 PM, Peter Otten <__peter__ at web.de> wrote: >> >> >> You are getting an *encoding* error, so this may be triggered when you >> are trying to print. Can you post the traceback? >> >> Also, what is your OS and what does >> >> $ python3 -c'import locale; print(locale.getpreferredencoding())' >> UTF-8 >> >> show? > > > Show: cp1252 > > PS D:\Documents\HomeBroker> py .\main.py > ['O Deputado Jovem', 'Bob Swaget', 'Baldrick', 'Inigo the brave', > 'KeplerBR', 'Lastemp3ror', 'Amethyst', 'wildee14', 'Le > Monade'] > Traceback (most recent call last): > File ".\main.py", line 11, in > search(my_u[0]) > File ".\main.py", line 8, in search > search(current) > File ".\main.py", line 5, in search > print([user.persona_name for user in x.get_friend_list()]) > File "C:\Development\Languages\Python34\lib\encodings\cp437.py", line > 19, > in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u262d' in > position 322: character maps to You can advise python to print \u262d or similar for codepoints that cannot be represented in cp1252 by setting the environment variable PYTHONIOENCODING=cp1252:backslashreplace Alternatively you can wrap stdout inside your script with something like sys.stdout = codecs.getwriter(sys.stdout.encoding)( sys.stdout.buffer, "backslashreplace") PS: There may also be a way to configure the console to accept a larger charset, but I'm not a Windows and cannot help you with that. From dyoo at hashcollision.org Thu Sep 11 23:49:17 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Sep 2014 14:49:17 -0700 Subject: [Tutor] Fwd: python qn In-Reply-To: References: Message-ID: Forwarding to python-tutor. ---------- Forwarded message ---------- From: Carmel O'Shannessy Date: Thu, Sep 11, 2014 at 12:18 PM Subject: Re: [Tutor] python qn To: Danny Yoo thanks, this worked: times2 = [float(i) for i in times[:2]] On Thu, Sep 11, 2014 at 1:10 PM, Danny Yoo wrote: > > On Thu, Sep 11, 2014 at 8:08 AM, Carmel O'Shannessy wrote: > > > > Hello, > > > > times = ['50.319468', '50.319468', 't1'] > > > > I want to convert [0:2] to floats. > > > > I tried: > > > > float.times = [float(i) for i in times[:2]] > > Hi Carmel, > > Do you intend to have a variable named "float.times" here on the left > hand side of the assignment? > > If so, try a different name. What's happening is not variable > assignment, but member assignment. The above statement is saying: > > Take the "float" type, and set its "times" attribute to the right hand side. > > And that's almost certainly not what you want to do. -- -- Carmel O'Shannessy, Assoc. Prof. Department of Linguistics University of Michigan 440 Lorch Hall 611 Tappan Street Ann Arbor, MI, 48109-1220 Ph: +1 734 764 0353 Fax: +1 734 936 3406 http://www-personal.umich.edu/~carmelos/ From chowwiwa at stolaf.edu Fri Sep 12 03:42:09 2014 From: chowwiwa at stolaf.edu (Nutthanai Chowwiwat) Date: Thu, 11 Sep 2014 20:42:09 -0500 Subject: [Tutor] Python Turtle Question Message-ID: Hello, I am fairly new to python programming and I have been stuck on this question for atleast an hour now and have been trying to find some information on how to do it online. The question to thep problem is: *Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. The program should draw the polygon and then fill it in.* This is what I have so far. I am only just starting out. So if possbile I want to stick to the basics. I'm pretty sure I need to use a "for loop". Thanks! ---------------------------------------------------------------- def main(): import turtle wn = turtle.Screen() tess = turtle.Turtle() #Ask for information to draw num_sides = eval(input("How many sides does your shape have?")) length_sides = eval(input("How long are the sides?")) shape_color = eval(input("What color is your shape")) main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 12 11:09:08 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2014 10:09:08 +0100 Subject: [Tutor] Python Turtle Question In-Reply-To: References: Message-ID: On 12/09/14 02:42, Nutthanai Chowwiwat wrote: > *Write a program that asks the user for the number of sides, the length of > the side, the color, and the fill color of a regular polygon. The program > should draw the polygon and then fill it in.* > > This is what I have so far. I am only just starting out. So if possbile I > want to stick to the basics. I'm pretty sure I need to use a "for loop". Yes you will want some kind of loop and a for loop is a good candidate. But first you could try doing some easy examples without a loop - say a square or triangle - to get the turtle commands working. > def main(): > > import turtle > > wn = turtle.Screen() > tess = turtle.Turtle() > > #Ask for information to draw > num_sides = eval(input("How many sides does your shape have?")) > length_sides = eval(input("How long are the sides?")) > shape_color = eval(input("What color is your shape")) You should NOT use eval() like this. It is very insecure and a very bad habit to fall into. Instead you should convert the input() calls using explicit conversion functions, like int() or float() You will need to think about how you want to convert/store the color since that?s not a native Python data type. The turtle module can accept a color name if its a standard one that it recognises - but what if the user types a non-standard color? What will your program do then? But turtle can also accept RGB values instead of a name, would you prefer them? Its your choice as a programmer how you do that. Assuming you now have the values stored you need to start drawing the shape. I recommend you start the interpreter, import turtle and start playing with the turtle functions. Once you understand which functions you want and how to use them you can return to your program and insert them as needed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From sunil.techspk at gmail.com Fri Sep 12 16:56:29 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 12 Sep 2014 20:26:29 +0530 Subject: [Tutor] Question on dictionary Message-ID: Hi All, i have a dictionary like res = [{'description': 'Testo', 'id': '676', 'parentOf': True}, {'description': 'Pesto', 'id': '620', 'parentOf': False}] i looking for the result like this res = [{'description': 'Testo', 'id': '676', 'id_desc':'676_Testo', 'parentOf': True}, {'description': 'Pesto', 'id': '620', 'id_desc':'620_Pesto', 'parentOf': False}] to get this result i wrote a code like this for i in res: dict = {} dict['id_desc'] = str(i['id'])+','+str(i['description']) i.update(dict) is there any other simple methods to achieve this? Thanks, Sunil. G -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Sep 12 18:04:12 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 12 Sep 2014 09:04:12 -0700 Subject: [Tutor] Question on dictionary In-Reply-To: References: Message-ID: > i wrote a code like this > > for i in res: > dict = {} > dict['id_desc'] = str(i['id'])+','+str(i['description']) > i.update(dict) > > is there any other simple methods to achieve this? > Can you avoid the intermediate "dict" and just assign to i['id_desc'] directly? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Sep 12 18:21:07 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 12 Sep 2014 12:21:07 -0400 Subject: [Tutor] Question on dictionary In-Reply-To: References: Message-ID: On Fri, Sep 12, 2014 at 12:04 PM, Danny Yoo wrote: > >> i wrote a code like this >> >> for i in res: >> dict = {} >> dict['id_desc'] = str(i['id'])+','+str(i['description']) A minor revision for the right side of above: ",".join(str(i['id'], str(i['description'])) >> i.update(dict) >> >> is there any other simple methods to achieve this? >> > > Can you avoid the intermediate "dict" and just assign to i['id_desc'] > directly? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From sunil.techspk at gmail.com Fri Sep 12 18:51:13 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 12 Sep 2014 22:21:13 +0530 Subject: [Tutor] Question on dictionary In-Reply-To: References: Message-ID: Thank you Danny and Joel :) On Fri, Sep 12, 2014 at 9:51 PM, Joel Goldstick wrote: > On Fri, Sep 12, 2014 at 12:04 PM, Danny Yoo > wrote: > > > >> i wrote a code like this > >> > >> for i in res: > >> dict = {} > >> dict['id_desc'] = str(i['id'])+','+str(i['description']) > > A minor revision for the right side of above: > ",".join(str(i['id'], str(i['description'])) > > >> i.update(dict) > >> > >> is there any other simple methods to achieve this? > >> > > > > Can you avoid the intermediate "dict" and just assign to i['id_desc'] > > directly? > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Joel Goldstick > http://joelgoldstick.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Sep 12 18:59:36 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Sep 2014 02:59:36 +1000 Subject: [Tutor] Question on dictionary In-Reply-To: References: Message-ID: <20140912165932.GL9293@ando.pearwood.info> On Fri, Sep 12, 2014 at 08:26:29PM +0530, Sunil Tech wrote: > Hi All, > > i have a dictionary like > > res = [{'description': 'Testo', 'id': '676', 'parentOf': True}, > {'description': 'Pesto', 'id': '620', 'parentOf': False}] That is not a dictionary. It is a list containing two dictionaries. > i looking for the result like this > > res = [{'description': 'Testo', 'id': '676', > 'id_desc':'676_Testo', 'parentOf': True}, > {'description': 'Pesto', 'id': '620', > 'id_desc':'620_Pesto', 'parentOf': False}] > > to get this result i wrote a code like this > > for i in res: > dict = {} > dict['id_desc'] = str(i['id'])+','+str(i['description']) > i.update(dict) > > is there any other simple methods to achieve this? for d in res: d['id_desc'] = d['id'] + '_' + d['description'] d['parentOf'] = (d['id'] == 676) -- Steven From aaronmisquith at live.com Fri Sep 12 20:04:47 2014 From: aaronmisquith at live.com (aaron misquith) Date: Fri, 12 Sep 2014 23:34:47 +0530 Subject: [Tutor] Python program to search videos using Bing Message-ID: I have been trying to search videos using bing search engine. But every-time I try I get error HTTPError:HTTPError 403:Forbidden This is the code i am using: import urllib import urllib2 import json def main(): query = "'pyscripter'" print bing_search(query, 'Video') def bing_search(query, search_type): #search_type: Web, Image, News, Video key= 'LsE7jElMmTDfbrnCEmrCmCEBbaPxMG5BvKr9CsfmSNS' query = urllib.quote(query) #create credential for authentication user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)' credentials = (':%s' % key).encode('base64')[:-1] auth = 'Basic %s' % credentials url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/'+search_type+'?Query=%27'+query+'%27&$top=5&$format=json' request = urllib2.Request(url) request.add_header('Authorization', auth) request.add_header('User-Agent', user_agent) request_opener = urllib2.build_opener() response = request_opener.open(request) response_data = response.read() json_result = json.loads(response_data) result_list = json_result['d']['results'] print result_list return result_list if __name__ == '__main__': main() The error shown is: Traceback (most recent call last): File "", line 30, in File "", line 7, in main File "", line 22, in bing_search File "C:\Python27\lib\urllib2.py", line 410, in open response = meth(req, response) File "C:\Python27\lib\urllib2.py", line 523, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python27\lib\urllib2.py", line 448, in error return self._call_chain(*args) File "C:\Python27\lib\urllib2.py", line 382, in _call_chain result = func(*args) File "C:\Python27\lib\urllib2.py", line 531, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Before trying this I worked with YouTube search API which worked fine. But the only problem was that it was limited to the videos present in YouTube database. What I want is the list of URL's of all the videos related to the keyword present in internet. So I started with Bing search engine. Any help regarding this would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Sat Sep 13 00:13:18 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 12 Sep 2014 15:13:18 -0700 Subject: [Tutor] Python program to search videos using Bing In-Reply-To: References: Message-ID: Hard to say. This is not quite Tutor material, so we may not be able to give you good help. ... you seem to be asking the same question here: http://stackoverflow.com/questions/25813510/python-program-to-search-videos-using-bing and hopefully you'll get some more specialized help there. What's you're encountering is an authentication error. That could mean that the key being passed to the API isn't being accepted. I'm assuming that you're using the API described by: https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44#schema but the URL there is different than the one you're using. I am guessing that you are trying to reuse code from: http://www.guguncube.com/2771/python-using-the-bing-search-api given the similarity to your program. However, that article was written in June 2013: it may be stale or referring to outdated material. It's a bit hard to tell. From dyoo at hashcollision.org Sat Sep 13 00:21:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 12 Sep 2014 15:21:44 -0700 Subject: [Tutor] Python program to search videos using Bing In-Reply-To: References: Message-ID: ... looking slightly further. You might want to check with the MSDN forums; there are folks that run into similar issues. e.g.: http://social.msdn.microsoft.com/Forums/azure/en-US/6fb0baac-32d9-4fdd-a083-f596b85cff9b/urgent-paid-subscription-suddenly-403-forbidden-access-is-denied-no-code-changed?forum=DataMarket http://social.msdn.microsoft.com/forums/azure/en-US/aa6b17b0-971e-4c49-9b2e-19ed28000430/bing-search-api-403-with-valid-key?forum=DataMarket and so your program _might_ be perfectly ok, but perhaps the key or account hasn't been processed yet. Determining this is out of my scope, though; you'll have to check with the MSDN folks and see if that is what's going on. Good luck to you! From alan.gauld at btinternet.com Sun Sep 14 10:00:49 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 14 Sep 2014 09:00:49 +0100 Subject: [Tutor] If statement The Python Tutorial 3.4.1 In-Reply-To: References: Message-ID: <1410681649.89460.YahooMailNeo@web186004.mail.ir2.yahoo.com> OK, You are using IDLE and have discovered one of its "features"? which I consider a bug... The alignment of code breaks in IDLE when there is no >>> in the line.? You need to ignore the >>> characters. So, to IDLE, your code looks like if x < 0: ? ? ? ? ? ?print(...) ? ? ? elif x == 0: because IDLE doesn't see the >>>. So it gives you the unindent error because it thinks elif is not aligned? with if, even though it looks that way to you... To fix it you need to make it look like this on screen: >>> if x < 0: ? ? ? ? ? ? print(...) elif x == 0: ? ? ? print(....) else: ? ? ? print(....) Which looks wrong to you and me but IDLE sees it as good. And this is one of the rare cases where posting an image rather? than a cut n' paste of the code is actually useful, because it? shows that you are using IDLE... HTH Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: Gregory Donaldson >To: Alan Gauld >Sent: Sunday, 14 September 2014, 4:28 >Subject: Re: [Tutor] If statement The Python Tutorial 3.4.1 > > > > >? > > > >On Sat, Sep 6, 2014 at 7:49 PM, Alan Gauld wrote: > >On 06/09/14 00:29, Gregory Donaldson wrote: >> >> >>This is what it looks like when I try to get it to work. >>> >>> >>>x = int(input("Please enter an integer: ")) >>>>>> >>>Please enter an integer: 42 >>> >>> >>>if x < 0: >>>>>> >>>x = 0 >>> >>>print('Negative changed to zero') >>> >> I'm guessing that you actually indented the two lines >>above but not the one below - otherwise you'd get an >>indentation error by now, not a syntax error below. >> >> >>elif x == 0: >>> >>>SyntaxError: invalid syntax >>> >> Are you sure this is where you get the syntax error? >>Or did you maybe hit enter too many times thus ending >>the if block? >> >> >>It needs to follow this pattern: >> >>if x < 0: >>? ?x = 0 >>? ?print('Negative changed to zero') >>elif x == 0: >> ? ?print('you typed zero') >>else: >>? ?print('alls well') >> >>So the if/elif and else lines are all lined up with each >>other and the indented lines are likewise lined up. >>And if working in the interactive prompt you must not >>have blank lines (Note: You can have blanks when creating >>a program file) >> >>Indentation is always important in programming for readability, >>but in Python its vital for Python to understand your code >>correctly. >> >>HTH >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >>http://www.flickr.com/photos/alangauldphotos >> >> >>_______________________________________________ >>Tutor maillist? -? Tutor at python.org >>To unsubscribe or change subscription options: >>https://mail.python.org/mailman/listinfo/tutor >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Screenshot 2014-09-13 23.27.15.png Type: image/png Size: 44029 bytes Desc: not available URL: From alan.gauld at btinternet.com Sun Sep 14 17:01:31 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Sep 2014 16:01:31 +0100 Subject: [Tutor] If statement The Python Tutorial 3.4.1 In-Reply-To: <1410681649.89460.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1410681649.89460.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 14/09/14 09:00, ALAN GAULD wrote: > So, to IDLE, your code looks like > > if x < 0: > print(...) > elif x == 0: Web mail screwed things up. That should be: > if x < 0: > print(...) > elif x == 0: > To fix it you need to make it look like this on screen: >>> if x < 0: print(...) elif x == 0: print(....) else: print(....) > > Which looks wrong to you and me but IDLE sees it as good. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From questions.anon at gmail.com Wed Sep 17 11:21:36 2014 From: questions.anon at gmail.com (questions anon) Date: Wed, 17 Sep 2014 19:21:36 +1000 Subject: [Tutor] print date and skip any repeats Message-ID: Hi Tutor, I think this should be simple but I can't find the right commands. I have a date for each hour for a whole month (and more) and I would like to write a loop that prints each date that is different but skips the dates that are the same. for i in date: print i and then skip i until different print next i and then skip i until different etc. Any feedback will be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Sep 17 11:51:47 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Sep 2014 11:51:47 +0200 Subject: [Tutor] print date and skip any repeats References: Message-ID: questions anon wrote: > I think this should be simple but I can't find the right commands. > > I have a date for each hour for a whole month (and more) and I would like > to write a loop that prints each date that is different but skips the > dates that are the same. > > for i in date: > print i and then skip i until different > print next i and then skip i until different > etc. > > > Any feedback will be greatly appreciated. Store the previous date in a variable and then compare it with the current date. If the current date differs from the previos one print it and update the previous date. From cs at zip.com.au Wed Sep 17 11:35:05 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 17 Sep 2014 19:35:05 +1000 Subject: [Tutor] print date and skip any repeats In-Reply-To: References: Message-ID: <20140917093505.GA9051@cskk.homeip.net> On 17Sep2014 19:21, questions anon wrote: >I think this should be simple but I can't find the right commands. > >I have a date for each hour for a whole month (and more) and I would like to >write a loop that prints each date that is different but skips the dates that >are the same. > >for i in date: >print i and then skip i until different >print next i and then skip i until different >etc.? If the above is what you're thinking, your problem seems to be that you're putting the "skip i until different" inside the loop as though you do lots of things in each loop iteration. What you'd really be doing is _one_ thing inside each loop iteration: printing the date or not. The normal way to do this is to keep a variable for the last date _print_. Each loop iteration should compare the current date against that and either do nothing or [print the new date and update the variable]. So you loop looks like this: lastdate = "" for date in all_the_dates: if date != lastdate: ... a different date: print and then update last date ... See if adapting that gets you closer to working code. If your code doesn't work, post the actualy code and a description of what it seems to be doing wrong. Cheers, Cameron Simpson Trust the computer industry to shorten Year 2000 to Y2K. It was this thinking that caused the problem in the first place. - Mark Ovens From juan0christian at gmail.com Wed Sep 17 19:01:04 2014 From: juan0christian at gmail.com (Juan Christian) Date: Wed, 17 Sep 2014 14:01:04 -0300 Subject: [Tutor] GUI development with Python 3.4.1 Message-ID: I need to develop a GUI for my Python pogram, I already read the GuiProgramming page (https://wiki.python.org/moin/GuiProgramming). For me, the best so far was 'gui2py'. The problem is that I need a simple "C#/Java-ish" GUI builder, that is easy and simple, coding all the GUI by hand is boring, I prefer to focus on the logic, on the actual program code, than coding the GUI. Anyone here already used 'gui2py' (https://github.com/reingart/gui2py)? Any other good alternatives? -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 18 15:07:41 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 18 Sep 2014 10:07:41 -0300 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian wrote: > I need to develop a GUI for my Python pogram, I already read the > GuiProgramming page (https://wiki.python.org/moin/GuiProgramming). For > me, the best so far was 'gui2py'. > > The problem is that I need a simple "C#/Java-ish" GUI builder, that is > easy and simple, coding all the GUI by hand is boring, I prefer to focus on > the logic, on the actual program code, than coding the GUI. > > Anyone here already used 'gui2py' (https://github.com/reingart/gui2py)? > Any other good alternatives? > Anyone? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Sep 18 15:12:57 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 18 Sep 2014 09:12:57 -0400 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: On Thu, Sep 18, 2014 at 9:07 AM, Juan Christian wrote: > On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian > wrote: >> >> I need to develop a GUI for my Python pogram, I already read the >> GuiProgramming page (https://wiki.python.org/moin/GuiProgramming). For me, >> the best so far was 'gui2py'. >> >> The problem is that I need a simple "C#/Java-ish" GUI builder, that is >> easy and simple, coding all the GUI by hand is boring, I prefer to focus on >> the logic, on the actual program code, than coding the GUI. >> >> Anyone here already used 'gui2py' (https://github.com/reingart/gui2py)? >> Any other good alternatives? > > > Anyone? > I've not used it but Tkinter seems to be well used. I'm not sure what a C#/Java-ish thing is, but python isn't that. -- Joel Goldstick http://joelgoldstick.com From juan0christian at gmail.com Thu Sep 18 15:14:49 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 18 Sep 2014 10:14:49 -0300 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: On Thu, Sep 18, 2014 at 10:12 AM, Joel Goldstick wrote: > > I've not used it but Tkinter seems to be well used. > > I'm not sure what a C#/Java-ish thing is, but python isn't that. > "C#/Java-ish" in terms of GUI Builder, drag and drop, like Glade and gui2py. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Sep 18 15:27:18 2014 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 18 Sep 2014 14:27:18 +0100 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: PyQt or PySide offers QtDesigner. Which is a drag and drop builder. They are both quite complex GUI toolkits so you will need some basic knowledge on them first, but I Imagine there are good guides on using QtDesigner if it's your last option. On Thu, Sep 18, 2014 at 2:14 PM, Juan Christian wrote: > On Thu, Sep 18, 2014 at 10:12 AM, Joel Goldstick > wrote: >> >> I've not used it but Tkinter seems to be well used. >> >> I'm not sure what a C#/Java-ish thing is, but python isn't that. > > > "C#/Java-ish" in terms of GUI Builder, drag and drop, like Glade and gui2py. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From lzantal at gmail.com Thu Sep 18 18:15:22 2014 From: lzantal at gmail.com (Laszlo Z. Antal) Date: Thu, 18 Sep 2014 09:15:22 -0700 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: <6D46679F-F90B-44D3-AC07-3E262DE8EFF9@gmail.com> Hi, I used to use wxPython.com Comes with a ton of examples and has many different drag and drop tools. Laszlo http://twitter.com/LZAntal > On Sep 18, 2014, at 6:27, Matthew Ngaha wrote: > > PyQt or PySide offers QtDesigner. Which is a drag and drop builder. > They are both quite complex GUI toolkits so you will need some basic > knowledge on them first, but I Imagine there are good guides on using > QtDesigner if it's your last option. > > On Thu, Sep 18, 2014 at 2:14 PM, Juan Christian > wrote: >> On Thu, Sep 18, 2014 at 10:12 AM, Joel Goldstick >> wrote: >>> >>> I've not used it but Tkinter seems to be well used. >>> >>> I'm not sure what a C#/Java-ish thing is, but python isn't that. >> >> >> "C#/Java-ish" in terms of GUI Builder, drag and drop, like Glade and gui2py. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From johnf at jfcomputer.com Thu Sep 18 19:53:22 2014 From: johnf at jfcomputer.com (john) Date: Thu, 18 Sep 2014 10:53:22 -0700 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: <541B1C12.1030009@jfcomputer.com> On 09/18/2014 06:07 AM, Juan Christian wrote: > On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian > > wrote: > > I need to develop a GUI for my Python pogram, I already read the > GuiProgramming page (https://wiki.python.org/moin/GuiProgramming). > For me, the best so far was 'gui2py'. > > The problem is that I need a simple "C#/Java-ish" GUI builder, > that is easy and simple, coding all the GUI by hand is boring, I > prefer to focus on the logic, on the actual program code, than > coding the GUI. > > Anyone here already used 'gui2py' > (https://github.com/reingart/gui2py)? Any other good alternatives? > > > Anyone? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Dabo has a designer (currently moving to support wxPython 3.x). That said, the link you first provided suggested there was a designer for gui2py? Johnf -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 18 22:25:35 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 18 Sep 2014 17:25:35 -0300 Subject: [Tutor] Problem getting data using beautifulsoup4 + python 3.4.1 Message-ID: My code: import requests import bs4 FORUM_ID = "440" response = requests.get(' http://steamcommunity.com/app/{id}/tradingforum'.format(id = FORUM_ID)) soup = bs4.BeautifulSoup(response.text) topics = [a.attrs.get('href') for a in soup.select('a.forum_topic_overlay')] for topic in topics: r = requests.get(topic) s = bs4.BeautifulSoup(r.text) username = [a.get_text() for a in s.select('div.authorline')] profile = [a.attrs.get('href') for a in s.select('div.authorline')] print(s.select('div.authorline')) print("\nProfile value: " + str(profile)) print("\n==================================\n") Now, let's talk about the problem. The print(s.select('div.authorline')) prints what I want, that is the part of the page that I need: [
FrazerJC 14 Oct, 2013 @ 3:31pm
] But, the print("\nProfile value: " + str(profile)) isn't printing what I want. It's giving me "Profile value: [None]". This should give me the link to the person's profile, in this example, " http://steamcommunity.com/id/FrazerJC". I was following the bs4 doc, and I did the [a.attrs.get('href') for a in s.select('div.authorline')] in order to get the value of the href, but it isn't working, of course I made something wrong, but where? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 18 23:10:52 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2014 23:10:52 +0200 Subject: [Tutor] Problem getting data using beautifulsoup4 + python 3.4.1 References: Message-ID: Juan Christian wrote: > My code: > > import requests > import bs4 > > > FORUM_ID = "440" > > response = requests.get(' > http://steamcommunity.com/app/{id}/tradingforum'.format(id = FORUM_ID)) > soup = bs4.BeautifulSoup(response.text) > topics = [a.attrs.get('href') for a in > soup.select('a.forum_topic_overlay')] > > for topic in topics: > r = requests.get(topic) > s = bs4.BeautifulSoup(r.text) > > username = [a.get_text() for a in s.select('div.authorline')] > profile = [a.attrs.get('href') for a in s.select('div.authorline')] > > print(s.select('div.authorline')) > print("\nProfile value: " + str(profile)) > print("\n==================================\n") > > > Now, let's talk about the problem. The print(s.select('div.authorline')) > prints what I want, that is the part of the page that I need: > > [
> > FrazerJC class="forum_author_action_pulldown"> title="Moderator" width="12"> 14 Oct, 2013 @ > 3:31pm
] > > > But, the print("\nProfile value: " + str(profile)) isn't printing what I > want. It's giving me "Profile value: [None]". This should give me the link > to the person's profile, in this example, " > http://steamcommunity.com/id/FrazerJC". I was following the bs4 doc, and I > did the [a.attrs.get('href') for a in s.select('div.authorline')] in order > to get the value of the href, but it isn't working, of course I made > something wrong, but where? The
doesn't have an href attribute, its child has. Try [a.attrs["href"] for a in s.select("div.authorline a")] From juan0christian at gmail.com Thu Sep 18 23:28:44 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 18 Sep 2014 18:28:44 -0300 Subject: [Tutor] Problem getting data using beautifulsoup4 + python 3.4.1 In-Reply-To: References: Message-ID: On Thu, Sep 18, 2014 at 6:10 PM, Peter Otten <__peter__ at web.de> wrote: > > The
doesn't have an href attribute, its child has. Try > > [a.attrs["href"] for a in s.select("div.authorline a")] OMG, I completely forgot about the 'a'... http://goo.gl/A8sRLT Thanks! 100% Working. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Fri Sep 19 04:54:47 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 18 Sep 2014 23:54:47 -0300 Subject: [Tutor] Is there any XML lib like the default json lib in terms of usability? Message-ID: Using the default json lib is easy and straightforward: import json info = json.loads('file.json') # Use dict and list to navigate through 'info' Sadly, I'm working in a script and the only format the server gives is XML, I searched for a good alternative and didn't find anything as easy as the default json lib. Any tips? -------------- next part -------------- An HTML attachment was scrubbed... URL: From artp824 at gmail.com Thu Sep 18 01:36:17 2014 From: artp824 at gmail.com (Art Pelletier) Date: Wed, 17 Sep 2014 16:36:17 -0700 Subject: [Tutor] Help Message-ID: I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. Sent from my iPad From sebastian at fuentelibre.org Thu Sep 18 18:36:31 2014 From: sebastian at fuentelibre.org (Sebastian Silva) Date: Thu, 18 Sep 2014 11:36:31 -0500 Subject: [Tutor] GUI development with Python 3.4.1 In-Reply-To: References: Message-ID: <1411058191.3993.0@smtp.gmail.com> El jue, 18 de sep 2014 a las 8:07 AM, Juan Christian escribi?: > On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian > wrote: >> I need to develop a GUI for my Python pogram, I already read the >> GuiProgramming page (https://wiki.python.org/moin/GuiProgramming). >> For me, the best so far was 'gui2py'. >> >> The problem is that I need a simple "C#/Java-ish" GUI builder, that >> is easy and simple, coding all the GUI by hand is boring, I prefer >> to focus on the logic, on the actual program code, than coding the >> GUI. >> >> Anyone here already used 'gui2py' >> (https://github.com/reingart/gui2py)? Any other good alternatives? > > Anyone? I personally like GTK quite a lot. You can use a GUI designer like Gazpacho or Glade to create basic XML UIs, but it's good to get familiar with the APIs of your toolkit of choice. Regards, Sebastian -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.wang at ntu.edu.sg Fri Sep 19 04:41:31 2014 From: l.wang at ntu.edu.sg (Wang Lei (ERIAN)) Date: Fri, 19 Sep 2014 02:41:31 +0000 Subject: [Tutor] Python Assignment Expression and Callable Expression Message-ID: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> Hi, everyone: I really believe that python is a great language but assignment and callable are not flexible: I wish that I can do this: class matrixArray(list): bla bla bla def __call__(self, rid, cid): return self.head[rid][cid] Once I call mat(1,1), I can get a result. but I want it more a value not a reference. Considering "mat(1,1) = 5" expression, I wish the parser can dynamically map "mat(1,1)" to reference of value of that "or anonymous reference" or reference defined in class. I don't want to modify the lexical parsing in C++ but failed after trying different method in pythonic ways: decorator: fun -> object mapping, because it just substitute function name with new function and cannot read "self" object. I wish python developers could think of an idea to update the lexical parsing method or simply provide us a tool to modify it in python context. Regards, Lei Wang ________________________________ CONFIDENTIALITY:This email is intended solely for the person(s) named and may be confidential and/or privileged.If you are not the intended recipient,please delete it,notify us and do not copy,use,or disclose its contents. Towards a sustainable earth:Print only when necessary.Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From illusiontechniques at gmail.com Fri Sep 19 07:03:04 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 18 Sep 2014 22:03:04 -0700 Subject: [Tutor] Help In-Reply-To: References: Message-ID: Check this guy's youtube channel. He has very basic examples. His username is thenewboston On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier wrote: > > I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. > Sent from my iPad > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From cs at zip.com.au Fri Sep 19 07:04:11 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 19 Sep 2014 15:04:11 +1000 Subject: [Tutor] Python Assignment Expression and Callable Expression In-Reply-To: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> References: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> Message-ID: <20140919050411.GA49042@cskk.homeip.net> On 19Sep2014 02:41, Wang Lei (ERIAN) wrote: >I really believe that python is a great language but assignment and callable are not flexible: Some flexibilities are too much. But there are ways to do what you ask... >I wish that I can do this: > > class matrixArray(list): > bla bla bla > def __call__(self, rid, cid): > return self.head[rid][cid] > >Once I call mat(1,1), I can get a result. but I want it more a value not a reference. You're going to need to be less vague. If the result is, for example, an int, in what fashion is it a value instead of an int as far as you are concerned? Please describe this issue more fully. >Considering "mat(1,1) = 5" expression, I wish the parser can dynamically map "mat(1,1)" to reference of value of that "or anonymous reference" or reference defined in class. I don't want to modify the lexical parsing in C++ but failed after trying different method in pythonic ways: Define the __setitem__ method on your matrixArray class. Then you can write: mat[1,1] = 5 which is arguably more natural anyway. Assignment and calling are two very different things, and in python they are written differently. That is a good thing. >decorator: fun -> object mapping, because it just substitute function name with new function and cannot read "self" object. I must be missing your point here, too. It does just substitute a new function, but that new function can (and generally must) access "self" to do its work. I think you are forgetting that the @decorator action occurs at the time the class is defined, not at the time the function is called. Cheers, Cameron Simpson More computing sins have been committed in the name of performance, without necessariliy achieving it, than for all other reasons combined. - Wulf From dyoo at hashcollision.org Fri Sep 19 07:34:27 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 18 Sep 2014 22:34:27 -0700 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier wrote: > > I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. Hi Art, Yes, there are some good resources you can check out. Here's a link to some of them: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Personally, I like How to Think Like a Computer Scientist: http://openbookproject.net/thinkcs/python/english2e/ but any of the tutorials in the beginner's guide should be helpful. Feel free to ask questions here on this mailing list too. From dyoo at hashcollision.org Fri Sep 19 07:37:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 18 Sep 2014 22:37:48 -0700 Subject: [Tutor] Python Assignment Expression and Callable Expression In-Reply-To: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> References: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> Message-ID: > I wish python developers could think of an idea to update the lexical > parsing method or simply provide us a tool to modify it in python context. Hi Lei, This is unfortunately out of scope for Python-tutor. We don't have direct influence over the future direction of the language. If you want to contact the developers and the larger community, you may want to check the official general-purpose mailing list: https://mail.python.org/mailman/listinfo/python-list (Be aware that python-list is high-traffic.) From steve at pearwood.info Fri Sep 19 08:39:25 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 19 Sep 2014 16:39:25 +1000 Subject: [Tutor] Python Assignment Expression and Callable Expression In-Reply-To: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> References: <5C015601FAEC7448B00A7FC799389361CEBD7B@EXCHMBOX33.staff.main.ntu.edu.sg> Message-ID: <20140919063925.GX9293@ando.pearwood.info> On Fri, Sep 19, 2014 at 02:41:31AM +0000, Wang Lei (ERIAN) wrote: > Hi, everyone: > > I really believe that python is a great language but assignment and callable are not flexible: > > I wish that I can do this: > > class matrixArray(list): > bla bla bla > def __call__(self, rid, cid): > return self.head[rid][cid] You can. __call__ is used for making objects a callable, function-like object. C++ calls them "functors". (Not the same thing as what Haskell calls functors!) > Once I call mat(1,1), I can get a result. but I want it more a value not a reference. You want to change the entire execution model of Python? Why? Like most modern languages, such as Ruby, Java (mostly), and Javascript, Python values are references, not unboxed low-level primitive values. > Considering "mat(1,1) = 5" expression, I wish the parser can > dynamically map "mat(1,1)" to reference of value of that "or anonymous > reference" or reference defined in class. I'm afraid I don't understand what you are trying to say, but if you want to assign to individual items in a matrix, use indexing, not function call: mat[1, 1] = 5 will work perfectly once you add a __setitem__ method to your matrix class. > I don't want to modify the > lexical parsing in C++ but failed after trying different method in > pythonic ways: What does C++ have to do with this? > decorator: fun -> object mapping, because it just substitute function > name with new function and cannot read "self" object. > > I wish python developers could think of an idea to update the lexical > parsing method or simply provide us a tool to modify it in python > context. I think that their answer will be: "We will not complicate the language, making our job enormously harder, and Python much harder to learn and use, just because a beginner to Python who doesn't understand what the language can do or how to use it, wants to program in C++ instead of Python. If you want to program in C++, use C++. If you want to program in Python, learn Python." What do you expect to do with: mat(1, 1) = 5 that cannot be done with this instead? mat[1, 1] = 5 -- Steven From sunil.techspk at gmail.com Fri Sep 19 08:53:51 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 19 Sep 2014 12:23:51 +0530 Subject: [Tutor] Question on List of Dict Message-ID: Hi all, tes = [{'a': 1, 'b': 'this', 'c': 221}, {'a': 2, 'b': 'this', 'c': 215}, {'a': 1, 'b': 'is', 'c': 875}, {'a': 1, 'b': 'sentence', 'c': 874}, {'a': 2, 'b': 'another', 'c': 754}, {'a': 2, 'b': 'word', 'c': 745}] The above one is the result form the DB. I am trying to convert it to something like result_tes = [{'a': 1, 'b': 'this, is, sentence', 'c': '221, 875, 874'}, {'a': 2, 'b': 'this, another, word', 'c': '215, 754, 744'}] if the value of the 'a' is same, then all those other values of the dict should be merged/clubbed. I tried, but it became complex and complex. please can any one help me to get the result. Thanks, Sunil. G -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Sep 19 09:28:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 00:28:44 -0700 Subject: [Tutor] Question on List of Dict In-Reply-To: References: Message-ID: > {'a': 2, 'b': 'another', 'c': 754}, > {'a': 2, 'b': 'word', 'c': 745} > > if the value of the 'a' is same, then all those other values of the dict should be merged/clubbed. Can you write a function that takes two of these and merges them? Assume that they have the same 'a'. Can you write such a function? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sunil.techspk at gmail.com Fri Sep 19 09:42:00 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 19 Sep 2014 13:12:00 +0530 Subject: [Tutor] Question on List of Dict In-Reply-To: References: Message-ID: Danny, i wrote a method called *merge *below can you be little clear with an example I wrote something like this ?? ids = [] for i in tes: if i['a'] not in ids: ids.append(i['a']) print ids def merge(ids, tes): for jj in ids: txt = '' for i in tes: if i['a'] == jj: txt = txt + ', ' + i['b'] i['b'] = txt return tes pprint.pprint(merge(ids, tes)) result is like [1, 2] [{'a': 1, 'b': ', this', 'c': 221}, {'a': 2, 'b': ', this', 'c': 215}, {'a': 1, 'b': ', this, is', 'c': 875}, {'a': 1, 'b': ', this, is, sentence', 'c': 874}, {'a': 2, 'b': ', this, another', 'c': 754}, {'a': 2, 'b': ', this, another, word', 'c': 745}] from this result need to take off the other dict so that it'll match the result_tes = [{'a': 1, 'b': 'this, is, sentence', 'c': '221, 875, 874'}, {'a': 2, 'b': 'this, another, word', 'c': '215, 754, 744'}] On Fri, Sep 19, 2014 at 12:58 PM, Danny Yoo wrote: > > > {'a': 2, 'b': 'another', 'c': 754}, > > {'a': 2, 'b': 'word', 'c': 745} > > > > > if the value of the 'a' is same, then all those other values of the dict > should be merged/clubbed. > > Can you write a function that takes two of these and merges them? Assume > that they have the same 'a'. Can you write such a function? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 19 09:45:45 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 09:45:45 +0200 Subject: [Tutor] Is there any XML lib like the default json lib in terms of usability? References: Message-ID: Juan Christian wrote: > Using the default json lib is easy and straightforward: > > import json > info = json.loads('file.json') > # Use dict and list to navigate through 'info' > > > Sadly, I'm working in a script and the only format the server gives is > XML, I searched for a good alternative and didn't find anything as easy as > the default json lib. > > Any tips? I have never used it, but lxml.objectify seems pretty intuitive: >>> from lxml import objectify >>> a = objectify.fromstring("1020") >>> a.b 10 >>> a = objectify.fromstring("102030") >>> a.b 10 >>> a.b**2 100 >>> a.b.get("foo") 'bar' >>> a.c 20 >>> a.c[1] 30 >>> len(a.c) 2 See From dyoo at hashcollision.org Fri Sep 19 09:52:21 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 00:52:21 -0700 Subject: [Tutor] Question on List of Dict In-Reply-To: References: Message-ID: On Sep 19, 2014 12:28 AM, "Danny Yoo" wrote: > > > > {'a': 2, 'b': 'another', 'c': 754}, > > {'a': 2, 'b': 'word', 'c': 745} > > > > > if the value of the 'a' is same, then all those other values of the dict should be merged/clubbed. > > Can you write a function that takes two of these and merges them? Assume that they have the same 'a'. Can you write such a function? Specifically, can you write a function merge_two() such that: merge_two({''b': 'another', 'c': 754}, {'b': 'word', 'c': 745}) returns the merged dictionary: {'b' : ['another', 'word'], 'c':[754, 745]} I'm trying to break the problem into simpler, testable pieces that you can solve. The problem as described is large enough that I would not dare trying to solve it all at once. If you have merge_two(), them you are much closer to a solution to the whole problem. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sunil.techspk at gmail.com Fri Sep 19 13:41:22 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 19 Sep 2014 17:11:22 +0530 Subject: [Tutor] Question on List of Dict In-Reply-To: References: Message-ID: Danny i did it like this result_dict = {} for i in tes: if i['a'] in result_dict: temp = result_dict[i['a']] temp['b'].append(i['b']) temp['c'].append(i['c']) temp['a'] = i['a'] result_dict[i['a']] = temp else: result_dict[i['a']] = { 'b': [i['b']], 'c': [i['c']], 'a': i['a']} pprint.pprint(result_dict.values()) result is [{'a': 1, 'b': ['this', 'is', 'sentence'], 'c': [221, 875, 874]}, {'a': 2, 'b': ['this', 'another', 'word'], 'c': [215, 754, 745]}] any can one improve this method in terms of performance, etc.. Thanks every one. On Fri, Sep 19, 2014 at 1:22 PM, Danny Yoo wrote: > > On Sep 19, 2014 12:28 AM, "Danny Yoo" wrote: > > > > > > > {'a': 2, 'b': 'another', 'c': 754}, > > > {'a': 2, 'b': 'word', 'c': 745} > > > > > > > > if the value of the 'a' is same, then all those other values of the > dict should be merged/clubbed. > > > > Can you write a function that takes two of these and merges them? > Assume that they have the same 'a'. Can you write such a function? > > Specifically, can you write a function merge_two() such that: > > merge_two({''b': 'another', 'c': 754}, {'b': 'word', 'c': 745}) > > returns the merged dictionary: > > {'b' : ['another', 'word'], 'c':[754, 745]} > > I'm trying to break the problem into simpler, testable pieces that you can > solve. The problem as described is large enough that I would not dare > trying to solve it all at once. If you have merge_two(), them you are much > closer to a solution to the whole problem. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 19 14:29:47 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 14:29:47 +0200 Subject: [Tutor] Question on List of Dict References: Message-ID: Sunil Tech wrote: > Danny i did it like this > > result_dict = {} > for i in tes: > if i['a'] in result_dict: > temp = result_dict[i['a']] > temp['b'].append(i['b']) > temp['c'].append(i['c']) > temp['a'] = i['a'] > result_dict[i['a']] = temp > else: > result_dict[i['a']] = { > 'b': [i['b']], > 'c': [i['c']], > 'a': i['a']} > pprint.pprint(result_dict.values()) > > result is > > [{'a': 1, 'b': ['this', 'is', 'sentence'], 'c': [221, 875, 874]}, > {'a': 2, 'b': ['this', 'another', 'word'], 'c': [215, 754, 745]}] > > any can one improve this method in terms of performance, etc.. What you have is a good solution; the most important part performance-wise is that you collect records with the same `a` value in a dict. For reference here's my two-pass solution to the problem as originally specified: bc = collections.defaultdict(lambda: ([], [])) for rec in tes: b, c = bc[rec["a"]] b.append(rec["b"]) c.append(rec["c"]) result = [{"a": a, "b": ", ".join(b), "c": ", ".join(map(str, c))} for a, (b, c) in bc.items()] If you are flexible with the result data structure you could omit the second loop and use bc.items() directly. From sunil.techspk at gmail.com Fri Sep 19 15:14:18 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Fri, 19 Sep 2014 18:44:18 +0530 Subject: [Tutor] Question on List of Dict In-Reply-To: References: Message-ID: Thank you Peter Otten, actually i should study about the collections and defaultdict like how and where these can be used and its advantage. On Fri, Sep 19, 2014 at 5:59 PM, Peter Otten <__peter__ at web.de> wrote: > Sunil Tech wrote: > > > Danny i did it like this > > > > result_dict = {} > > for i in tes: > > if i['a'] in result_dict: > > temp = result_dict[i['a']] > > temp['b'].append(i['b']) > > temp['c'].append(i['c']) > > temp['a'] = i['a'] > > result_dict[i['a']] = temp > > else: > > result_dict[i['a']] = { > > 'b': [i['b']], > > 'c': [i['c']], > > 'a': i['a']} > > pprint.pprint(result_dict.values()) > > > > result is > > > > [{'a': 1, 'b': ['this', 'is', 'sentence'], 'c': [221, 875, 874]}, > > {'a': 2, 'b': ['this', 'another', 'word'], 'c': [215, 754, 745]}] > > > > any can one improve this method in terms of performance, etc.. > > What you have is a good solution; the most important part performance-wise > is that you collect records with the same `a` value in a dict. > > For reference here's my two-pass solution to the problem as originally > specified: > > bc = collections.defaultdict(lambda: ([], [])) > > for rec in tes: > b, c = bc[rec["a"]] > b.append(rec["b"]) > c.append(rec["c"]) > > result = [{"a": a, > "b": ", ".join(b), > "c": ", ".join(map(str, c))} > for a, (b, c) in bc.items()] > > If you are flexible with the result data structure you could omit the > second > loop and use bc.items() directly. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Fri Sep 19 19:30:46 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 14:30:46 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 Message-ID: This part of my code isn't working: def check_backpacktf(steamID64): with requests.get(''.join([BACKPACKTF, steamID64])) as response: status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': 'Private or invalid', 'steamrep_scammer': False} with response.json()['response']['players'][steamID64] as api: status['backpack_value'] = api['backpack_value'][GAME_ID] status['steamrep_scammer'] = bool(api['steamrep_scammer']) return status ----- Traceback (most recent call last): File "C:\[...]\shark.py", line 98, in main(sys.argv[1]) File "C:\[...]\shark.py", line 93, in main fetch_forum() File "C:\[...]\shark.py", line 79, in fetch_forum fetch_user(user_url) File "C:\[...]\shark.py", line 42, in fetch_user backpacktf = check_backpacktf(steamID64) File "C:\[...]\shark.py", line 25, in check_backpacktf with requests.get(''.join([BACKPACKTF, steamID64])) as response: AttributeError: __exit__ I'm trying to use the 'with statement' to reduce the SLOC and make the code prettier. Using 'try-expect-finally' wouldn't be good, as I have more 3 or 4 functions like this one that call different sites. What's the problem? Can't I use requests that way? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Sep 19 19:47:27 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 19 Sep 2014 13:47:27 -0400 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 1:30 PM, Juan Christian wrote: > This part of my code isn't working: > > def check_backpacktf(steamID64): > with requests.get(''.join([BACKPACKTF, steamID64])) as response: I'm not sure why my reply mangled your indents, but can you check to see that your "".join() is getting what you think it should? > status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': > 'Private or invalid', 'steamrep_scammer': False} > > with response.json()['response']['players'][steamID64] as api: > status['backpack_value'] = api['backpack_value'][GAME_ID] > status['steamrep_scammer'] = bool(api['steamrep_scammer']) > > return status > > ----- > > Traceback (most recent call last): > File "C:\[...]\shark.py", line 98, in > main(sys.argv[1]) > File "C:\[...]\shark.py", line 93, in main > fetch_forum() > File "C:\[...]\shark.py", line 79, in fetch_forum > fetch_user(user_url) > File "C:\[...]\shark.py", line 42, in fetch_user > backpacktf = check_backpacktf(steamID64) > File "C:\[...]\shark.py", line 25, in check_backpacktf > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > AttributeError: __exit__ > > > I'm trying to use the 'with statement' to reduce the SLOC and make the code > prettier. Using 'try-expect-finally' wouldn't be good, as I have more 3 or 4 > functions like this one that call different sites. What's the problem? Can't > I use requests that way? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Fri Sep 19 19:50:33 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 10:50:33 -0700 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: > Traceback (most recent call last): > File "C:\[...]\shark.py", line 98, in > main(sys.argv[1]) > File "C:\[...]\shark.py", line 93, in main > fetch_forum() > File "C:\[...]\shark.py", line 79, in fetch_forum > fetch_user(user_url) > File "C:\[...]\shark.py", line 42, in fetch_user > backpacktf = check_backpacktf(steamID64) > File "C:\[...]\shark.py", line 25, in check_backpacktf > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > AttributeError: __exit__ > > > I'm trying to use the 'with statement' to reduce the SLOC and make the code > prettier. Using 'try-expect-finally' wouldn't be good, as I have more 3 or 4 > functions like this one that call different sites. What's the problem? Can't > I use requests that way? I'm not exactly sure. Let's check the documentation on the 'with' statement to double check what it expects. https://docs.python.org/2/reference/compound_stmts.html#the-with-statement Reading... ok, so 'with' uses the term "context manager". From reading this, I think 'with' only works with things that support the context manager interface. Does the return value from requests.get() support context management? Reading... http://docs.python-requests.org/en/latest/api/#requests.Response ... I don't think so. It does have a 'close()' method, but the with statement expects an object with both '__enter__' and '__exit__' methods. So Python's "with" appears to require a bit more out the thing being managed than the similar try-with-resources in Java. (http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) From juan0christian at gmail.com Fri Sep 19 20:00:55 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 15:00:55 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 2:50 PM, Danny Yoo wrote: > > So Python's "with" appears to require a bit more out the thing being > managed than the similar try-with-resources in Java. > ( > http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html > ) > Is there anything similar in Python? Putting tons of 'try-expect' in the code would be a bit ugly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Sep 19 20:08:06 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 19 Sep 2014 14:08:06 -0400 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 2:00 PM, Juan Christian wrote: > On Fri, Sep 19, 2014 at 2:50 PM, Danny Yoo wrote: >> >> So Python's "with" appears to require a bit more out the thing being >> managed than the similar try-with-resources in Java. >> >> (http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) > > > > Is there anything similar in Python? Putting tons of 'try-expect' in the > code would be a bit ugly. You might want to look at decorators. I think that might help you > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From __peter__ at web.de Fri Sep 19 20:15:27 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 20:15:27 +0200 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 References: Message-ID: Juan Christian wrote: > This part of my code isn't working: > > def check_backpacktf(steamID64): > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': > 'Private or invalid', 'steamrep_scammer': False} > > with response.json()['response']['players'][steamID64] as api: > status['backpack_value'] = api['backpack_value'][GAME_ID] > status['steamrep_scammer'] = bool(api['steamrep_scammer']) > > return status > > ----- > > Traceback (most recent call last): > File "C:\[...]\shark.py", line 98, in > main(sys.argv[1]) > File "C:\[...]\shark.py", line 93, in main > fetch_forum() > File "C:\[...]\shark.py", line 79, in fetch_forum > fetch_user(user_url) > File "C:\[...]\shark.py", line 42, in fetch_user > backpacktf = check_backpacktf(steamID64) > File "C:\[...]\shark.py", line 25, in check_backpacktf > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > AttributeError: __exit__ > > > I'm trying to use the 'with statement' to reduce the SLOC and make the > code prettier. Using 'try-expect-finally' wouldn't be good, as I have more > 3 or 4 functions like this one that call different sites. What's the > problem? Can't I use requests that way? Let's take a step back: if you were to write > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': > 'Private or invalid', 'steamrep_scammer': False} using try-except-finally -- what would it look like? From dyoo at hashcollision.org Fri Sep 19 20:21:13 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 11:21:13 -0700 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: I should have added that you can write your own context manager for requests; it shouldn't be too bad. I'd expect the helper code to be something like: ######################################### class AutoClosable(object): def __init__(self, closable): self.closable = closable def __enter__(self): return self.closable def __exit__(self, type, value, traceback): self.closable.close() ## reraise exception if one occurred: return False ## Example usage: class Foo(object): def __init__(self, name): self.name = name def close(self): print("closing %s" % self.name) self.closed = True with AutoClosable(Foo('case 1')) as x: pass with AutoClosable(Foo('case 2')) as x: raise ValueError, "oops" ######################################### From __peter__ at web.de Fri Sep 19 20:30:29 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 20:30:29 +0200 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 References: Message-ID: Danny Yoo wrote: > I should have added that you can write your own context manager for > requests; it shouldn't be too bad. I'd expect the helper code to be > something like: > class AutoClosable(object): > def __init__(self, closable): > self.closable = closable > > def __enter__(self): > return self.closable > > def __exit__(self, type, value, traceback): > self.closable.close() > ## reraise exception if one occurred: > return False There is also From juan0christian at gmail.com Fri Sep 19 20:30:25 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 15:30:25 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 3:15 PM, Peter Otten <__peter__ at web.de> wrote: > > Let's take a step back: if you were to write > > > with requests.get(''.join([BACKPACKTF, steamID64])) as response: > > status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': > > 'Private or invalid', 'steamrep_scammer': False} > > using try-except-finally -- what would it look like? Well, this site API is ridiculous, they use JSON but let's get an example: When an user is banned this ' "backpack_tf_banned": null ' is added in the JSON, they better way would be that this entry was there all the time, and set true or false for it. Same goes for ' "steamrep_scammer": true ', it's only there when the user is indeed a scammer, but now the value is true and not null as in the other entry. That's why I need the try-expect, and I need it here: with response.json()['response']['players'][steamID64] as api: status['backpack_value'] = api['backpack_value'][GAME_ID] status['steamrep_scammer'] = bool(api['steamrep_scammer']) return status The part of the code you posted the try-expect is needed because I don't know if they have all Steam users in their DB, so the request.get() could broke. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Sep 19 20:41:30 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 11:41:30 -0700 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: >> class AutoClosable(object): [cut] > There is also > > Ah, much better! Thanks Peter. From __peter__ at web.de Fri Sep 19 20:53:05 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 20:53:05 +0200 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 References: Message-ID: Juan Christian wrote: > On Fri, Sep 19, 2014 at 3:15 PM, Peter Otten <__peter__ at web.de> wrote: >> >> Let's take a step back: if you were to write >> >> > with requests.get(''.join([BACKPACKTF, steamID64])) as response: >> > status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value': >> > 'Private or invalid', 'steamrep_scammer': False} >> >> using try-except-finally -- what would it look like? > > > Well, this site API is ridiculous, they use JSON but let's get an example: > > When an user is banned this ' "backpack_tf_banned": null ' is added in the > JSON, they better way would be that this entry was there all the time, and > set true or false for it. Same goes for ' "steamrep_scammer": true ', it's > only there when the user is indeed a scammer, but now the value is true > and not null as in the other entry. > > That's why I need the try-expect, and I need it here: > > with response.json()['response']['players'][steamID64] as api: > status['backpack_value'] = api['backpack_value'][GAME_ID] > status['steamrep_scammer'] = bool(api['steamrep_scammer']) > > return status > > The part of the code you posted the try-expect is needed because I don't > know if they have all Steam users in their DB, so the request.get() could > broke. If I understand you correctly you can test for the presence of a value. Example: api = response.json()['response']['players'][steamID64] status["steamrep_scammer"] = "steamrep_scammer" in api From juan0christian at gmail.com Fri Sep 19 20:54:15 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 15:54:15 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: This is the code using the contextlib (more than 105 lines): http://pastebin.com/jVhz7Ta6 But I'm getting another (super confusing) error now: [#] [Tf2 inventory [W]CS GO Skins Author: Pnoy Paragon << UNTIL HERE, OK! Traceback (most recent call last): File "C:\Users\Juan Christian\Desktop\trader.py", line 105, in main(sys.argv[1]) File "C:\Users\Juan Christian\Desktop\trader.py", line 100, in main fetch_forum() File "C:\Users\Juan Christian\Desktop\trader.py", line 86, in fetch_forum fetch_user(user_url) File "C:\Users\Juan Christian\Desktop\trader.py", line 52, in fetch_user backpacktf = check_backpacktf(steamID64) File "C:\Users\Juan Christian\Desktop\trader.py", line 38, in check_backpacktf with closing(response.json()['response']['players'][steamID64]) as api: File "C:\Development\Languages\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\models.py", line 763, in j son return json.loads(self.text, **kwargs) File "C:\Development\Languages\Python34\lib\json\__init__.py", line 318, in loads return _default_decoder.decode(s) File "C:\Development\Languages\Python34\lib\json\decoder.py", line 343, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Development\Languages\Python34\lib\json\decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None ValueError: Expecting value: line 1 column 1 (char 0) And SublimeText tells me 'Redefiniton of unused 'closing' from line 1' in @contextmanager. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Fri Sep 19 20:56:22 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 15:56:22 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 3:53 PM, Peter Otten <__peter__ at web.de> wrote: > > If I understand you correctly you can test for the presence of a value. > Example: > > api = response.json()['response']['players'][steamID64] > status["steamrep_scammer"] = "steamrep_scammer" in api Thanks, this way I can only have problems calling the 'requests.get()', right (In the case the URL doesn't exists)? This would be only one try-expect in each function, this way is good for me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 19 21:30:25 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 21:30:25 +0200 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 References: Message-ID: Juan Christian wrote: > This is the code using the contextlib (more than 105 lines): > http://pastebin.com/jVhz7Ta6 > > But I'm getting another (super confusing) error now: > > [#] [Tf2 inventory [W]CS GO Skins > Author: Pnoy Paragon << UNTIL HERE, OK! > > Traceback (most recent call last): > File "C:\Users\Juan Christian\Desktop\trader.py", line 105, in > main(sys.argv[1]) > File "C:\Users\Juan Christian\Desktop\trader.py", line 100, in main > fetch_forum() > File "C:\Users\Juan Christian\Desktop\trader.py", line 86, in > fetch_forum > fetch_user(user_url) > File "C:\Users\Juan Christian\Desktop\trader.py", line 52, in fetch_user > backpacktf = check_backpacktf(steamID64) > File "C:\Users\Juan Christian\Desktop\trader.py", line 38, in > check_backpacktf > with closing(response.json()['response']['players'][steamID64]) as > api: > File > "C:\Development\Languages\Python34\lib\site-packages\requests-2.3.0- py3.4.egg\requests\models.py", > line 763, in j > son > return json.loads(self.text, **kwargs) > File "C:\Development\Languages\Python34\lib\json\__init__.py", line 318, > in loads > return _default_decoder.decode(s) > File "C:\Development\Languages\Python34\lib\json\decoder.py", line 343, > in decode > obj, end = self.raw_decode(s, idx=_w(s, 0).end()) > File "C:\Development\Languages\Python34\lib\json\decoder.py", line 361, > in raw_decode > raise ValueError(errmsg("Expecting value", s, err.value)) from None > ValueError: Expecting value: line 1 column 1 (char 0) > > > And SublimeText tells me 'Redefiniton of unused 'closing' from line 1' > in @contextmanager. Well, you import closing from the stdlib with from contextlib import closing and then proceed to write your own closing @contextmanager def closing(thing): try: yield thing finally: thing.close() At the moment my advice would be: forget about closing and the with- statement. They are great to solve a problem you don't have (here). From juan0christian at gmail.com Fri Sep 19 22:00:25 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 17:00:25 -0300 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 4:30 PM, Peter Otten <__peter__ at web.de> wrote: > > Well, you import closing from the stdlib with > > from contextlib import closing > > and then proceed to write your own closing > > @contextmanager > def closing(thing): > try: > yield thing > finally: > thing.close() > > At the moment my advice would be: forget about closing and the with- > statement. They are great to solve a problem you don't have (here). So, just do as you said in the post above, 'status["steamrep_scammer"] = "steamrep_scammer" in api' and use a single try-expect in the outer requests.get() ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 19 22:32:41 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2014 22:32:41 +0200 Subject: [Tutor] Using 'requests' + 'with statement' in Python 3.4.1 References: Message-ID: Juan Christian wrote: > On Fri, Sep 19, 2014 at 4:30 PM, Peter Otten <__peter__ at web.de> wrote: >> >> Well, you import closing from the stdlib with >> >> from contextlib import closing >> >> and then proceed to write your own closing >> >> @contextmanager >> def closing(thing): >> try: >> yield thing >> finally: >> thing.close() >> >> At the moment my advice would be: forget about closing and the with- >> statement. They are great to solve a problem you don't have (here). > > > So, just do as you said in the post above, 'status["steamrep_scammer"] = > "steamrep_scammer" in api' and use a single try-expect in the outer > requests.get() ? That would be a reasonable approach. Note that if there are multiple possible exceptions that you want to handle with the same reaction you can use a single try...except. Example: def check_backpacktf(steamID64): try: data = download_data() status = extract_status from_data(data) except (DownloadFailed, MissingData): status = default_status() return status Also to keep in mind for the occasion when you are going to reinvestigate `with`: with open("not-there") as f: data = f.read() This will throw an exception, and `with` offers no way to intercept with that as __enter__() has not been called yet. From juan0christian at gmail.com Sat Sep 20 01:00:49 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 20:00:49 -0300 Subject: [Tutor] Converting timestamp read as str to "full date and time" Message-ID: Let's say I have ' 1411167038 ' string that I got from an API and I need to convert it to something like ' Fri, 19 Sep 2014 22:50:38 GMT ' or maybe even the localtime of the PC. I'm trying this way: my_date = datetime.datetime.fromtimestamp(api['backpack_update'][GAME_ID]).strftime("%D %H:%M") The key ' api['backpack_update'][GAME_ID] ' returns exactly what's expected, the timestamp in string format. But now I need to convert this to a "full date and time" so that I can print in the terminal/cmd like ' print(my_date) '. I already read the https://docs.python.org/2/library/datetime.html and I think that the func 'strptime' may resolve my problem, already tried with this one, but didn't work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Sat Sep 20 01:09:50 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 16:09:50 -0700 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 4:00 PM, Juan Christian wrote: > Let's say I have ' 1411167038 ' string that I got from an API and I need to > convert it to something like ' Fri, 19 Sep 2014 22:50:38 GMT ' or maybe even > the localtime of the PC. What does that number mean though? Let me guess: is it the number of seconds since the Epoch? >>> t = 1411167038 >>> import datetime >>> datetime.datetime.fromtimestamp(t) datetime.datetime(2014, 9, 19, 15, 50, 38) ... I think that's what that number means. It may be the number of seconds since the Epoch. References: https://docs.python.org/2/library/datetime.html#datetime.datetime.fromtimestamp https://docs.python.org/2/library/time.html#time.time From dyoo at hashcollision.org Sat Sep 20 01:22:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 19 Sep 2014 16:22:24 -0700 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: Huh. I should have read your message more closely. Sorry; it's been one of those days for me, it seems... Anyway, can you use ctime()? It looks like that might be almost right: >>> t = 1411167038 >>> datetime.datetime.utcfromtimestamp(t).ctime() 'Fri Sep 19 22:50:38 2014' though if you really do want more control over what's being printed, yes, strftime() is what's you're looking for, I think: >>> t = 1411167038 >>> datetime.datetime.utcfromtimestamp(t).strftime("%a, %d %b %Y %H:%M:%S") 'Fri, 19 Sep 2014 22:50:38' https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior From juan0christian at gmail.com Sat Sep 20 01:46:57 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 20:46:57 -0300 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 8:22 PM, Danny Yoo wrote: > Huh. I should have read your message more closely. Sorry; it's been > one of those days for me, it seems... > > Anyway, can you use ctime()? It looks like that might be almost right: > > >>> t = 1411167038 > >>> datetime.datetime.utcfromtimestamp(t).ctime() > 'Fri Sep 19 22:50:38 2014' > The thing is that I get the timestamp as string and I need to print it using something like this: print("Random text here: {}".format(my_date)) Real example: API returns -> http://backpack.tf/api/IGetUsers/v3/?steamids=76561198052911020 I get 'backpack_update' > '440' correctly, no problems and, opsss, my bad, the timestamp is int, not string. I did some debug and I was wrong. 1411044719 So, what I need is to get this 1411044719 (int) and convert to something like this 'Fri Sep 19 22:50:38 2014' and print it using format() The line I'll print is like that: print('\t\tBACKPACK VALUE: {} ( {} )'.format(status['backpack_value'], status['backpack_update'])) status['backpack_value'] is 100% OK status['backpack_update'] is the guy... > though if you really do want more control over what's being printed, > yes, strftime() is what's you're looking for, I think: > > >>> t = 1411167038 > >>> datetime.datetime.utcfromtimestamp(t).strftime("%a, %d %b %Y > %H:%M:%S") > 'Fri, 19 Sep 2014 22:50:38' > > https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sat Sep 20 02:24:45 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 21:24:45 -0300 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: So.. It seems all my problem was in the .strftime("%D %H:%M") I don't exactly know why, but I removed and it's working. It's not giving me the localtime, but I'll search how to do that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sat Sep 20 02:29:51 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 21:29:51 -0300 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: On Fri, Sep 19, 2014 at 9:24 PM, Juan Christian wrote: > So.. It seems all my problem was in the .strftime("%D %H:%M") > > I don't exactly know why, but I removed and it's working. It's not giving > me the localtime, but I'll search how to do that. > Ops, my bad again, it's indeed in the localtime, but sadly it seems that when I call the API, it doesn't update first then give me up-to-date values, it gives me "old" values, or maybe the backpack of the person didn't changed until that time, well I'll leave this this way, later I can check if the values are truly "old" or not. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Sat Sep 20 03:50:13 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 20 Sep 2014 11:50:13 +1000 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: References: Message-ID: <20140920015013.GA93134@cskk.homeip.net> On 19Sep2014 20:46, Juan Christian wrote: >On Fri, Sep 19, 2014 at 8:22 PM, Danny Yoo??wrote: > Anyway, can you use ctime()?? It looks like that might be almost right: > ? ? >>> t = 1411167038 > ? ? >>> datetime.datetime.utcfromtimestamp(t).ctime() > ? ? 'Fri Sep 19 22:50:38 2014' > >The thing is that I get the timestamp as string and I need to print it using >something like this: print("Random text here: {}".format(my_date)) # here's your timestamp as a string, however obtained t = # just an int, convert it to an int seconds_since_epoch = int(t) # get a from the timestamp dt = datetime.datetime.utcfromtimestamp(t) # write the out in desired format as a string my_date = dt.strftime("%a, %d %b %Y %H:%M:%S") # use the formatted string print("Random text here: {}".format(my_date)) Seriously, keep that steps all broken out separately like the above. Easier to read, easier to debug, easier to move relevant parts off into utility functions later when you need to do this from several places in your code. Cheers, Cameron Simpson If this experiment we're doing works, then I will follow up and push it as hard as possible. And if it doesn't work, I will write a science-fiction novel where it does work. It's a win-win situation. - John Cramer on his experiment for possible cuasality violation From juan0christian at gmail.com Sat Sep 20 04:35:42 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 19 Sep 2014 23:35:42 -0300 Subject: [Tutor] Converting timestamp read as str to "full date and time" In-Reply-To: <20140920015013.GA93134@cskk.homeip.net> References: <20140920015013.GA93134@cskk.homeip.net> Message-ID: On Fri, Sep 19, 2014 at 10:50 PM, Cameron Simpson wrote: > On 19Sep2014 20:46, Juan Christian wrote: > >> On Fri, Sep 19, 2014 at 8:22 PM, Danny Yoo >> wrote: >> Anyway, can you use ctime()? It looks like that might be almost right: >> >>> t = 1411167038 >> >>> datetime.datetime.utcfromtimestamp(t).ctime() >> 'Fri Sep 19 22:50:38 2014' >> >> The thing is that I get the timestamp as string and I need to print it >> using >> something like this: print("Random text here: {}".format(my_date)) >> > > # here's your timestamp as a string, however obtained > t = > > # just an int, convert it to an int > seconds_since_epoch = int(t) > > # get a from the timestamp > dt = datetime.datetime.utcfromtimestamp(t) > > # write the out in desired format as a string > my_date = dt.strftime("%a, %d %b %Y %H:%M:%S") > > # use the formatted string > print("Random text here: {}".format(my_date)) > > Seriously, keep that steps all broken out separately like the above. > Easier to read, easier to debug, easier to move relevant parts off into > utility functions later when you need to do this from several places in > your code. > > Cheers, > Cameron Simpson You should read the last posts before posting. (: The problem was already solved, and as I said, it was already an int, not a str as I wrongly said on the title! -------------- next part -------------- An HTML attachment was scrubbed... URL: From diliupg at gmail.com Fri Sep 19 09:13:41 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Fri, 19 Sep 2014 12:43:41 +0530 Subject: [Tutor] Help In-Reply-To: References: Message-ID: http://cscircles.cemc.uwaterloo.ca/run-at-home/ On Fri, Sep 19, 2014 at 11:04 AM, Danny Yoo wrote: > On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier wrote: > > > > I am a beginner with pythons programming I would like to see if their > is a site that has samples programs that I can practice on. > > Hi Art, > > > Yes, there are some good resources you can check out. Here's a link > to some of them: > > https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Personally, I like How to Think Like a Computer Scientist: > > http://openbookproject.net/thinkcs/python/english2e/ > > but any of the tutorials in the beginner's guide should be helpful. > > > > Feel free to ask questions here on this mailing list too. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From madecunningly at outlook.com Fri Sep 19 23:25:50 2014 From: madecunningly at outlook.com (Kate Reeher) Date: Fri, 19 Sep 2014 16:25:50 -0500 Subject: [Tutor] making a list of a custom object Message-ID: I have a custom class called Game, and it has a variable called "goals". I'd like to make this a list of custom objects, with various information about the goals. class Game: goals = {} class Goal(object): def __init__(self,time,goal_by,assist_by,team,is_powerplay ): self.time=time self.goal_by=goal_by self.assist_by=assist_by self.team=team self.is_powerplay=is_powerplay Is that Goal class set up correctly? For an instance of Game called game, is this how you'd set a variable of a goal?game.goals[i].time= time I'm finding how python does data classes INCREDIBLY confusing, for whatever reason, so any help would be appreciated. Thanks,Kate -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Sep 20 14:33:46 2014 From: davea at davea.name (Dave Angel) Date: Sat, 20 Sep 2014 08:33:46 -0400 (EDT) Subject: [Tutor] making a list of a custom object References: Message-ID: Kate Reeher Wrote in message: > I have a custom class called Game, and it has a variable called "goals". I'd like > to make this a list of custom objects, with various information about the goals. > class Game: > goals = {} That's a class attribute; the others below are instance attributes. And it's a dict not a list. Perhaps you want goals = [] But more likely you're expecting to have more than one game, each with its own list of goals. In this case you'd want an initializer method, and within it you'd say self.goals = [] You'd also want to instantiate at least one game, perhaps like (outside of the class definition) game = Game () > class Goal(object): > def __init__(self,time,goal_by,assist_by,team,is_powerplay ): > self.time=time > self.goal_by=goal_by > self.assist_by=assist_by > self.team=team > self.is_powerplay=is_powerplay > This might be where you should append self to the class attrinute. > Is that Goal class set up correctly? One of many possibilities. > For an instance of Game called game, is this how you'd set a > variable of a goal? > game.goals[i].time= time First you have to create the goal. my_goal = Goal (....) Then you probably need to add that goal to a particular Game. game.goals.append (my_goal) Then if you have appended several, and you need to patch the time of a particular one (the ith one), you might use your statement. But typically in a game, I'd figure the time for a particular goal wouldn't change. -- DaveA From crk at godblessthe.us Sun Sep 21 00:20:09 2014 From: crk at godblessthe.us (Clayton Kirkwood) Date: Sat, 20 Sep 2014 15:20:09 -0700 Subject: [Tutor] question 1 Message-ID: <007301cfd521$0ad08af0$2071a0d0$@us> I'm ramping slowly unfortunately. How does one go about knowing which module to import to make certain functions work? I have a read() that fails because there is no definition for it. I am using the Wing IDE. I have traversed much of the developer's guide and can't find any certainty. Secondarily, why can you import a module without it importing all of its daughters? And why do you have to use a 'for in to import submodule', why not ' mport module.sub'? Lastly, in some tutorials and else-sourced docs certain lines have a ';' at the end. This seems to be most often with 'opens' and 'fopen' kind of calls. Thanks, Clayton -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Sun Sep 21 03:07:54 2014 From: crushed26 at gmail.com (Crush) Date: Sat, 20 Sep 2014 21:07:54 -0400 Subject: [Tutor] Subprocess help Message-ID: Hey all, hope everyone is well. I am trying to write a script that automates a certain task I have recently found myself doing a lot lately. The command I need to run is "BYPASSROOT=yes ./octosetupBROADCASTER-linux_i386.bin" I know how to use subprocess to execute the "./octosetup..." command, however the "BYPASSROOT=yes" is stumping me seeing how it is not really a unix command. I assume it is changing a variable within "octosetup...?" How do I get the "BYPASSROOT=yes" to be included in the subprocess.call? I know i know "root" is bad, but with this, I have no choice. Thanks Bo From dyoo at hashcollision.org Sun Sep 21 03:24:47 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 20 Sep 2014 18:24:47 -0700 Subject: [Tutor] Subprocess help In-Reply-To: References: Message-ID: > The command I need to run is "BYPASSROOT=yes ./octosetupBROADCASTER-linux_i386.bin" Semantically, the command above means: execute "./octosetupBROADCASTER-linux_i386.bin" in an environment that binds BYPASSROOT to "yes". The subprocess.Popen command takes in an optional "env" argument, so that's what you want to provide when creating this new subprocess. Here's a link to the documentation. https://docs.python.org/2/library/subprocess.html#subprocess.Popen So you'll probably want to do something like: envCopy = os.environ.copy() envCopy['BYPASSROOT'] = 'yes' subprocess.Popen(["./octosetupBROADCASTER-linux_i386.bin"], env=envCopy) From dyoo at hashcollision.org Sun Sep 21 03:36:37 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 20 Sep 2014 18:36:37 -0700 Subject: [Tutor] question 1 In-Reply-To: <007301cfd521$0ad08af0$2071a0d0$@us> References: <007301cfd521$0ad08af0$2071a0d0$@us> Message-ID: On Sat, Sep 20, 2014 at 3:20 PM, Clayton Kirkwood wrote: > I?m ramping slowly unfortunately. How does one go about knowing which module > to import to make certain functions work? I have a read() that fails because > there is no definition for it. Specific details may help here. Can you tell us more? What are you trying to do? If you are seeing error messages, please copy exact error message content and present it. Error messages have more than one bit of information: they usually encode some information that folks here can try to interpret. > Secondarily, why can you import a module without it importing all of its > daughters? The act of importing a module is "recursive": if you import a module, and that module itself has import statements, then Python will do the import of the child modules too. And so forth. (You might imagine a system where the "main" module must do all this linkage by itself, rather than do this recursive walk. And there are systems that do work like this! See: https://talks.golang.org/2012/splash.article for Rob Pike's discussion on the Plan 9 compiler, which worked this way. But Python does not do this.) > And why do you have to use a ?for in to import submodule?, why > not ?import module.sub?? If I'm not mistaken, you _can_ do this. Can you point us to a source where it says you can't? (There are particular style guidelines from certain organizations that prohibit this kind of import, but that prohibition is by convention. That is, it's not because the language disallows it, but because it doesn't fit with the house coding style.) > Lastly, in some tutorials and else-sourced docs certain lines have a ?;? at > the end. This seems to be most often with ?opens? and ?fopen? kind of calls. Huh. Can you point to a reference? Note that third-party documentation (and official documentation!) might be buggy or weird. :P If you can point us to an example, maybe one of us can investigate what's going on there. From dyoo at hashcollision.org Sun Sep 21 03:41:50 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 20 Sep 2014 18:41:50 -0700 Subject: [Tutor] question 1 In-Reply-To: References: <007301cfd521$0ad08af0$2071a0d0$@us> Message-ID: >> Secondarily, why can you import a module without it importing all of its >> daughters? > > The act of importing a module is "recursive": if you import a module, > and that module itself has import statements, then Python will do the > import of the child modules too. And so forth. Hi Deb, Oh! By the way, this echoes that point about recursion from a week or so ago. https://mail.python.org/pipermail/tutor/2014-September/102715.html So yes, recursion shows up at the heart of the Python module import system too. That should have been an obvious example, but I forgot. :P From steve at pearwood.info Sun Sep 21 06:21:46 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Sep 2014 14:21:46 +1000 Subject: [Tutor] question 1 In-Reply-To: <007301cfd521$0ad08af0$2071a0d0$@us> References: <007301cfd521$0ad08af0$2071a0d0$@us> Message-ID: <20140921042146.GC29494@ando.pearwood.info> Hi Clayton, and welcome. My responses are interleaved between your questions below. On Sat, Sep 20, 2014 at 03:20:09PM -0700, Clayton Kirkwood wrote: > I'm ramping slowly unfortunately. How does one go about knowing which module > to import to make certain functions work? Experience, practice, reading the documentation, experimentation. > I have a read() that fails because > there is no definition for it. I am using the Wing IDE. I have traversed > much of the developer's guide and can't find any certainty. That's a hard question to answer. Where did you get the read() from? I can think of three scenarios: (1) You thought to yourself, "I want to read some data from somewhere, hmmm, this sounds like a job for a function called read(), maybe if I just try it, it will work!" Sadly, no it doesn't. What sort of data are you trying to read, and from where? If you tell us that, we may be able to advise on the correct way to read. (2) You are copying some code from somewhere else, and it includes something like: result = read(abc, xyz) # or whatever You need to go back through the rest of the code until you find a line that looks like either: from something import read or perhaps: read = something or even: def read(this, that, another): ... (3) You're reading a tutorial or book, and it suggests using: result = read(abc, xyz) In which case, read the tutorial a bit more closely. Perhaps earlier in the book they told you where read() comes from? Or maybe they didn't, and the tutorial is just broken, mistaken, buggy or confused. If you show us some of the code around the read() line, we may be able to guess what they meant to say. > Secondarily, why can you import a module without it importing all of its > daughters? And why do you have to use a 'for in to import submodule', why > not ' mport module.sub'? A concrete example might help, because if I'm understanding you correctly, you *can* do exactly that. When you say: import fe.fi.fo.fum Python starts off by importing fe, then fe.fi, then fe.fi.fo, then fe.fi.fo.fum, so that *all* of those dotted names will work. Here's an actual example: >>> import os.path >>> os >>> os.path So even though I only *manually* imported the os.path submodule, Python automatically imported its parent os for me. > Lastly, in some tutorials and else-sourced docs certain lines have a ';' at > the end. This seems to be most often with 'opens' and 'fopen' kind of calls. Are you sure you're reading Python tutorials, not C tutorials? :-) It's not *wrong* to end lines with a semi-colon, but it is poor style. A bit like saying "Um" at the beginning of every sentence. You would have to ask the tutorial author why they are doing such a thing. Do you have a link to an online tutorial that does that, I'm curious to see it for myself. -- Steven From steve at pearwood.info Sun Sep 21 07:13:02 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Sep 2014 15:13:02 +1000 Subject: [Tutor] making a list of a custom object In-Reply-To: References: Message-ID: <20140921051301.GE29494@ando.pearwood.info> Hi Kate, and welcome! My replies are interleaved between your questions. On Fri, Sep 19, 2014 at 04:25:50PM -0500, Kate Reeher wrote: > I have a custom class called Game, and it has a variable called > "goals". I'd like to make this a list of custom objects, with various > information about the goals. Unfortunately, either your email, or my email, mangled your code below. I've tried to reconstruct it as well I can, but please don't hesitate to correct me if I got it wrong. > class Game: > goals = {} > > class Goal(object): > def __init__(self,time,goal_by,assist_by,team,is_powerplay ): > self.time=time > self.goal_by=goal_by > self.assist_by=assist_by > self.team=team > self.is_powerplay=is_powerplay > > Is that Goal class set up correctly? I can't be absolutely sure, because I'm not sure of your intention, but it looks correct to me. That's certainly the usual way to set up a class. > For an instance of Game called game, is this how you'd set a variable > of a goal? > game.goals[i].time= time You could do it that way to modify an existing goal. (By the way, in Python circles, we prefer to talk about "attributes" of instances, not instance variables. If you are interested, I'll give you my standard rant about this later :-) Your Game class is a little unusual though. It's not *wrong*, just unusual, perhaps you intended to do it this way. You have set the Game class to use a single "class attribute", which means that all instances will share it. (Actually, the rules are a little more complex than that, but for now thinking of it as a shared attribute isn't far wrong.) Was that intentional? If you're familiar with Java, I think that a class attribute is close to a Java static variable. (I'm not a Java expert, so I may be wrong.) If you intend to have multiple Game instances, each with their own independent set of goals, you would write it like this: class Game: def __init__(self): goals = {} but I'm not sure why the goals are kept in a dict. That would require you to keep track of whether each goal is the first, second, third... goal yourself. I think you want an ordered list: class Game: def __init__(self): goals = [] red_vs_blue = Game() shirts_vs_skins = Game() # Add new goals. red_vs_blue.goals.append(Goal(...)) # Fill in the appropriate args. shirts_vs_skins.goals.append(Goal(...)) red_vs_blue.goals.append(Goal(...)) # Modify existing goals (but why would you do this?) red_vs_blue.goals[0].team = 'green' Because each game has its own list of goals, you can run multiple games at the same time. You don't have to track the index of the latest goal, you just append a new goal. You only need to care about the index if you want to modify an existing goal. On the other hand, what you originally wrote, with a shared class attribute, isn't *wrong*. If you absolutely know that there will never be more than one game at a time, there is no need to bother creating a Game instance: class Game: goals = [] Game.goals.append(Goal(...)) Game.goals.append(Goal(...)) Game.goals[0].team = 'green' In this case, you can think of the Game class as being almost like a singleton instance. (Not quite the same, but it does the same job.) As I said, this is fairly unusual in Python though. Normally you would stick to standard "one class, multiple instances, each with their own set of attributes" design. > I'm finding how python does data classes INCREDIBLY confusing, for > whatever reason, so any help would be appreciated. Sorry to hear that. Please don't hesitate to ask about anything confusing. Giving concrete examples is good, and if you are familiar with some other language, feel free to say so. -- Steven From juan0christian at gmail.com Sun Sep 21 16:18:46 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 11:18:46 -0300 Subject: [Tutor] Python 3: List Comprehensions + range Message-ID: I have a ' self.size = json['number_of_seasons'] ' that equals 5 (already checked), the problem is that the API have some series with special seasons, aka, season_number = 0, and I don't want to get those. I have the following list comp: self.season = [Season(ID, season, self) for season in range(1, self.size + 1)] Let's say I want Breaking Bad, 5 seasons, but this serie has a special season 0. Reading the list comp, I get a range from 1 (in order to ignore season 0) to 5 (range is half-open, so I need size + 1, maybe later I can implement a closed_range, but I don't think this will be necessary as this is the only place I'll ever use this). Then I get the current number and hold it on the var season, then I call Season() with this number, but I'm still fetching episodes from the season 0 and I don't know why! Code: import requests from consts import API from person import Person from character import Character class Serie: def __init__(self, ID): response = requests.get('{query}/{id}?api_key={key}'.format(query = API.QUERY_SERIE, id = ID, key = API.KEY)) json = response.json() self.id = ID self.title = json['name'] self.date = json['first_air_date'] self.size = json['number_of_seasons'] self.season = [Season(ID, season, self) for season in range(1, self.size + 1)] class Season: def __init__(self, ID, season, serie): response = requests.get('{query}/{id}/season/{s}?api_key={key}'.format(query = API.QUERY_SERIE, id = ID, s = season, key = API.KEY)) json = response.json() self.number = season self.serie = serie self.date = json['air_date'] self.episode = [Episode(ID, episode['episode_number'], self) for episode in json['episodes']] self.size = len(self.episode) class Episode: def __init__(self, ID, episode, season): response = requests.get('{query}/{id}/season/{s}/episode/{e}?api_key={key}'.format(query = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY)) json = response.json() print(json) print("\n") self.number = episode self.title = json['name'] self.date = json['air_date'] response = requests.get('{query}/{id}/season/{s}/episode/{e}/credits?api_key={key}'.format(query = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY)) json = response.json() self.cast = [Character(person['character'], Person(person['id'])) for person in json['cast']] self.cast_size = len(self.cast) s = Serie("1396") print("DEBUG: " + s.title + " : " + s.id + " : " + s.date + " : " + s.size) print(json) is giving me: {'vote_average': 0.0, 'id': 62131, 'air_date': '2009-02-17', 'still_path': '/t729tFVXPetnJlJ2VsUZQz0rX6v.jpg', 'overview ': "Hank and Marie try to spice up their relationship on Valentine's Day.", 'episode_number': 1, 'production_code': None , 'season_number': 0, 'vote_count': 0, 'name': 'Good Cop Bad Cop'} {'vote_average': 0.0, 'id': 62133, 'air_date': '2009-02-17', 'still_path': '/wT62P6ZnjKgZXk0M5hHl4e5zSjB.jpg', 'overview ': 'Walt and Hank have a talk before Hank gets married.', 'episode_number': 2, 'production_code': None, 'season_number': 0, 'vote_count': 0, 'name': 'Wedding Day'} {'vote_average': 0.0, 'id': 62132, 'air_date': '2009-02-17', 'still_path': '/gUHAqFw3Ptzya96JFFE9xVfMjze.jpg', 'overview ': 'Jesse and Badger make a behind the scenes video about their band "TwaughtHammer" and show a music video for their so ng "Fallacies."', 'episode_number': 3, 'production_code': None, 'season_number': 0, 'vote_count': 0, 'name': 'TwaughtHam mer'} [...] As you can see, 'season_number': 0, and I want 1 and above only. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Sep 21 20:11:02 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 15:11:02 -0300 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: Anyone?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Sep 21 20:28:28 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 21 Sep 2014 14:28:28 -0400 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: On Sun, Sep 21, 2014 at 10:18 AM, Juan Christian wrote: > I have a ' self.size = json['number_of_seasons'] ' that equals 5 (already > checked), the problem is that the API have some series with special seasons, > aka, season_number = 0, and I don't want to get those. > > I have the following list comp: self.season = [Season(ID, season, self) for > season in range(1, self.size + 1)] You are calling Season with different parameters than it was defined to accept. > > Let's say I want Breaking Bad, 5 seasons, but this serie has a special > season 0. Reading the list comp, I get a range from 1 (in order to ignore > season 0) to 5 (range is half-open, so I need size + 1, maybe later I can > implement a closed_range, but I don't think this will be necessary as this > is the only place I'll ever use this). Then I get the current number and > hold it on the var season, then I call Season() with this number, but I'm > still fetching episodes from the season 0 and I don't know why! > > Code: > > import requests > from consts import API > from person import Person > from character import Character > > > class Serie: > def __init__(self, ID): > response = requests.get('{query}/{id}?api_key={key}'.format(query = > API.QUERY_SERIE, id = ID, key = API.KEY)) > json = response.json() > > self.id = ID > self.title = json['name'] > self.date = json['first_air_date'] > self.size = json['number_of_seasons'] > self.season = [Season(ID, season, self) for season in range(1, self.size + > 1)] > > > class Season: > def __init__(self, ID, season, serie): > response = requests.get('{query}/{id}/season/{s}?api_key={key}'.format(query > = API.QUERY_SERIE, id = ID, s = season, key = API.KEY)) > json = response.json() > > self.number = season > self.serie = serie > self.date = json['air_date'] > self.episode = [Episode(ID, episode['episode_number'], self) for episode in > json['episodes']] > self.size = len(self.episode) > > > class Episode: > def __init__(self, ID, episode, season): > response = > requests.get('{query}/{id}/season/{s}/episode/{e}?api_key={key}'.format(query > = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY)) > json = response.json() > print(json) > print("\n") > self.number = episode > self.title = json['name'] > self.date = json['air_date'] > > response = > requests.get('{query}/{id}/season/{s}/episode/{e}/credits?api_key={key}'.format(query > = API.QUERY_EPISODE, id = ID, s = season, e = episode, key = API.KEY)) > json = response.json() > > self.cast = [Character(person['character'], Person(person['id'])) for person > in json['cast']] > self.cast_size = len(self.cast) > > > s = Serie("1396") > print("DEBUG: " + s.title + " : " + s.id + " : " + s.date + " : " + s.size) > > > print(json) is giving me: > > {'vote_average': 0.0, 'id': 62131, 'air_date': '2009-02-17', 'still_path': > '/t729tFVXPetnJlJ2VsUZQz0rX6v.jpg', 'overview > ': "Hank and Marie try to spice up their relationship on Valentine's Day.", > 'episode_number': 1, 'production_code': None > , 'season_number': 0, 'vote_count': 0, 'name': 'Good Cop Bad Cop'} > > > {'vote_average': 0.0, 'id': 62133, 'air_date': '2009-02-17', 'still_path': > '/wT62P6ZnjKgZXk0M5hHl4e5zSjB.jpg', 'overview > ': 'Walt and Hank have a talk before Hank gets married.', 'episode_number': > 2, 'production_code': None, 'season_number': > 0, 'vote_count': 0, 'name': 'Wedding Day'} > > > {'vote_average': 0.0, 'id': 62132, 'air_date': '2009-02-17', 'still_path': > '/gUHAqFw3Ptzya96JFFE9xVfMjze.jpg', 'overview > ': 'Jesse and Badger make a behind the scenes video about their band > "TwaughtHammer" and show a music video for their so > ng "Fallacies."', 'episode_number': 3, 'production_code': None, > 'season_number': 0, 'vote_count': 0, 'name': 'TwaughtHam > mer'} > > [...] > > As you can see, 'season_number': 0, and I want 1 and above only. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From juan0christian at gmail.com Sun Sep 21 20:36:48 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 15:36:48 -0300 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: On Sun, Sep 21, 2014 at 3:28 PM, Joel Goldstick wrote: > > You are calling Season with different parameters than it was defined to > accept. No, I'm not. Season > def __init__(self, ID, season, serie) and I'm calling it with Season(ID, season, self), I'm giving everything needed, don't I? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Sep 21 21:21:05 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 21 Sep 2014 15:21:05 -0400 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: On Sun, Sep 21, 2014 at 2:36 PM, Juan Christian wrote: > On Sun, Sep 21, 2014 at 3:28 PM, Joel Goldstick > wrote: >> >> You are calling Season with different parameters than it was defined to >> accept. > > > No, I'm not. > > Season > def __init__(self, ID, season, serie) > > and I'm calling it with Season(ID, season, self), I'm giving everything > needed, don't I? Shouldn't it be: Season(ID, season, serie)? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Sun Sep 21 21:25:21 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 21 Sep 2014 12:25:21 -0700 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: On Sun, Sep 21, 2014 at 11:11 AM, Juan Christian wrote: > Anyone? Please treat email as asynchronous: sometimes you'll get a response within minutes, but sometimes it takes a little longer. Reading the question quickly... I can't answer this too carefully. I haven't even had breakfast or lunch yet! :P But there appears to be a type error here. You're using the name "season" in different contexts, where sometimes you mean the season number, and in other places, you mean the season object. Particularly, you appear to expect the constructor of Episode to take in the season *number*, but within the Season constructor, you're passing it the season *object*. From juan0christian at gmail.com Sun Sep 21 21:32:05 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 16:32:05 -0300 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: On Sun, Sep 21, 2014 at 4:21 PM, Joel Goldstick wrote: > > Shouldn't it be: Season(ID, season, serie)? No, we always have to have 'self' in the first arg. On Sun, Sep 21, 2014 at 4:25 PM, Danny Yoo wrote: > > Please treat email as asynchronous: sometimes you'll get a response > within minutes, but sometimes it takes a little longer. > > Reading the question quickly... I can't answer this too carefully. I > haven't even had breakfast or lunch yet! :P > > > But there appears to be a type error here. You're using the name > "season" in different contexts, where sometimes you mean the season > number, and in other places, you mean the season object. > Particularly, you appear to expect the constructor of Episode to take > in the season *number*, but within the Season constructor, you're > passing it the season *object*. > Time here is different then =p And, no, I always treat season as a number, like season 1, 2, 3, ... In the class Season, I use season twice: on the response, s = season, giving s the season number. And self.number = season, giving, self.number, the season number, only that! And in the class Serie, the line self.season = [Season(ID, season, self) for season in range(1, self.size + 1)], self.season is the object, and season is just a random var that I used in the list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Sep 21 21:36:54 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 16:36:54 -0300 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: Thanks Danny, indeed, the problem was in these confusing names. The problem was here: Class Episode > s = season The fix: s = season.number -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Sun Sep 21 22:43:14 2014 From: crushed26 at gmail.com (Crush) Date: Sun, 21 Sep 2014 16:43:14 -0400 Subject: [Tutor] Subprocess help In-Reply-To: References: Message-ID: <5798ACE1-9294-493E-9D5B-156CE70468FF@gmail.com> Thank you Danny for your assistance. Just a couple of follow up questions to help me understand what is going on. You said... "Semantically, the command above means: execute "./octosetupBROADCASTER-linux_i386.bin" in an environment that binds BYPASSROOT to "yes"." Does the above mean "BYPASSROOT" is an environmet variable? Is this created and set by default by the system or is it created and set by "octosetupBROADCASTER-linux_i386.bin?" The code you suggested... "envCopy = os.environ.copy() envCopy['BYPASSROOT'] = 'yes' subprocess.Popen(["./octosetupBROADCASTER-linux_i386.bin"], env=envCopy)" This copies the systems environment variables and stores them in the variable "envCopy?" What do the "[ ]'s" mean? Are the variables stored in an array or list and by enclosing "BYPASSROOT" in brackets, we are ultimately selecting "BYPASSROOT" and assinging its value to "yes?" We then pass this to subprocess, but how does subprocess know we want "BYPASSROOT" to equal "yes" when we only pass on envCopy, which is coded before " envCopy['BYPASSROOT'] = 'yes'?" Does python not work from top to bottom? Bo From dyoo at hashcollision.org Sun Sep 21 23:18:47 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 21 Sep 2014 14:18:47 -0700 Subject: [Tutor] Subprocess help In-Reply-To: <5798ACE1-9294-493E-9D5B-156CE70468FF@gmail.com> References: <5798ACE1-9294-493E-9D5B-156CE70468FF@gmail.com> Message-ID: > "Semantically, the command above means: > execute "./octosetupBROADCASTER-linux_i386.bin" in an environment > that binds BYPASSROOT to "yes"." > > Does the above mean "BYPASSROOT" is an environmet variable? Is this created and set by default by the system or is it created and set by "octosetupBROADCASTER-linux_i386.bin?" The word "system" is ambiguous. Let's be specific. The actor here is the command-line shell. Assuming that you are using the 'bash' command-line shell, see: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html http://www.gnu.org/software/bash/manual/bash.html#Command-Execution-Environment http://www.gnu.org/software/bash/manual/bash.html#Environment for the background information. The particular usage you are doing here at your command line shell: $ BYPASSROOT=yes ./octosetupBROADCASTER-linux_i386.bin is a concrete instance of augmenting the environment with a temporary set of variables, as described in Section 3.7.4 of the Bash documentation: """The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.""" I do need to cut in and editorialize: a little knowledge is dangerous. You're asking questions that suggest that you have a passing familiarity with Unix, but not a deep one. Given what you appear to be doing, this frightens me. I am not joking; this is not a laughing matter. Please talk to your local friendly Unix system administrator, and take a real Unix system administration class. In the United States, you can visit one of the USENIX groups: https://www.usenix.org/legacy/membership/groups_usa.html I'm not so familiar with the situation outside the US, but I'm pretty sure similar groups can be found. > The code you suggested... > > "envCopy = os.environ.copy() > envCopy['BYPASSROOT'] = 'yes' > subprocess.Popen(["./octosetupBROADCASTER-linux_i386.bin"], env=envCopy)" > > This copies the systems environment variables and stores them in the variable "envCopy?" What do the "[ ]'s" mean? Are the variables stored in an array or list and by enclosing "BYPASSROOT" in brackets, we are ultimately selecting "BYPASSROOT" and assinging its value to "yes?" Please read: https://docs.python.org/2/tutorial/datastructures.html#dictionaries From dyoo at hashcollision.org Mon Sep 22 00:29:28 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 21 Sep 2014 15:29:28 -0700 Subject: [Tutor] Fwd: question 1 In-Reply-To: References: <007301cfd521$0ad08af0$2071a0d0$@us> <013101cfd5e4$e66f3020$b34d9060$@us> Message-ID: Forwarding response to tutor; didn't realize it was only sent to me. ---------- Forwarded message ---------- From: Danny Yoo Date: Sun, Sep 21, 2014 at 3:10 PM Subject: Re: [Tutor] question 1 To: Clayton Kirkwood On Sun, Sep 21, 2014 at 2:42 PM, Clayton Kirkwood wrote: >> Secondarily, why can you import a module without it importing all of >> its daughters? > > The act of importing a module is "recursive": if you import a module, and that module itself has import statements, then Python will do the import of the child modules too. And so forth. >> And why do you have to use a ?for in to import submodule?, why not >> ?import module.sub?? > > If I'm not mistaken, you _can_ do this. Can you point us to a source where it says you can't? > > (There are particular style guidelines from certain organizations that prohibit this kind of import, but that prohibition is by convention. > That is, it's not because the language disallows it, but because it doesn't fit with the house coding style.) > > > [Clayton Kirkwood] > From the interpreter: > > import io > import io.FileIO > Traceback (most recent call last): > File "", line 1, in > builtins.ImportError: No module named 'io.FileIO'; 'io' is not a package Hi Clayton, Ah. But 'FileIO' is not a module. It's a value in the 'io' module. We can see this here: ####################################################### dhcp-9:work dyoo$ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import io >>> io >>> io.FileIO ####################################################### When we say: import xxx then the "xxx" has to be a module. The 'from/import' statement is deceptively named, unfortunately; it's doing a little more than just module import. https://docs.python.org/2/tutorial/modules.html#more-on-modules where when we say: from xxx import yyy then xxx.yyy could be a module, or it might not. The act of module import is involved, so in a sense, the statement is doing an import. But the 'yyy' doesn't have to be a module. When we say: from io import FileIO we are taking a value from the 'io' module, and giving it the name 'FileIO So yeah, it's a little confusing. For that reason, certain style guidelines have a say when something is appropriate to write, apart from what Python technically allows. As a concrete example, see: https://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Imports#Imports Here, we see a style decision that is _more_ restrictive than what the Python language allows. > Huh. Can you point to a reference? Note that third-party documentation (and official documentation!) might be buggy or weird. > :P If you can point us to an example, maybe one of us can investigate what's going on there. > [Clayton Kirkwood] > > > Example from ' http://www.tutorialspoint.com/python/python_files_io.htm' > > #!/usr/bin/python > > str = raw_input("Enter your input: "); > print "Received input is : ", str Just because something is on the web (or email) doesn't mean it's correct or prefect. :) -- There are a few small problems with this example from tutorialspoint: 1. The semicolon is superfluous. Take it out: it will still work. 2. The name 'str' is already a built-in, https://docs.python.org/2/library/functions.html#str so the code here is shadowing the built-in. In such a small test program, this is fine. In a real program, I'd ding this for readability issues. From dyoo at hashcollision.org Mon Sep 22 00:30:00 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 21 Sep 2014 15:30:00 -0700 Subject: [Tutor] Fwd: question 1 In-Reply-To: <013101cfd5e4$e66f3020$b34d9060$@us> References: <007301cfd521$0ad08af0$2071a0d0$@us> <013101cfd5e4$e66f3020$b34d9060$@us> Message-ID: Forwarding Clayton's original request to tutor: ---------- Forwarded message ---------- From: Clayton Kirkwood Date: Sun, Sep 21, 2014 at 2:42 PM Subject: RE: [Tutor] question 1 To: Danny Yoo > Secondarily, why can you import a module without it importing all of > its daughters? The act of importing a module is "recursive": if you import a module, and that module itself has import statements, then Python will do the import of the child modules too. And so forth. > And why do you have to use a ?for in to import submodule?, why not > ?import module.sub?? If I'm not mistaken, you _can_ do this. Can you point us to a source where it says you can't? (There are particular style guidelines from certain organizations that prohibit this kind of import, but that prohibition is by convention. That is, it's not because the language disallows it, but because it doesn't fit with the house coding style.) [Clayton Kirkwood] >From the interpreter: import io import io.FileIO Traceback (most recent call last): File "", line 1, in builtins.ImportError: No module named 'io.FileIO'; 'io' is not a package from io import FileIO :end > Lastly, in some tutorials and else-sourced docs certain lines have a > ?;? at the end. This seems to be most often with ?opens? and ?fopen? kind of calls. Huh. Can you point to a reference? Note that third-party documentation (and official documentation!) might be buggy or weird. :P If you can point us to an example, maybe one of us can investigate what's going on there. [Clayton Kirkwood] Example from ' http://www.tutorialspoint.com/python/python_files_io.htm' #!/usr/bin/python str = raw_input("Enter your input: "); print "Received input is : ", str From steve at pearwood.info Mon Sep 22 03:13:23 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Sep 2014 11:13:23 +1000 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: References: Message-ID: <20140922011320.GG29494@ando.pearwood.info> On Sun, Sep 21, 2014 at 03:11:02PM -0300, Juan Christian wrote: > Anyone?? Have patience, we're not on 24/7 duty and you don't have a SLA (Service Level Agreement) with us. Normally it is considered polite to wait at least one day before sending a reminder, not six hours. Although we have list members all over the world, and even though sometimes it doesn't look like it, we do have lives outside of this mailing list and sometimes we're all away from the computer or busy doing something else. Or, perhaps your question is a hard question to answer and we need time to think about it. -- Steve From juan0christian at gmail.com Mon Sep 22 04:11:25 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 21 Sep 2014 23:11:25 -0300 Subject: [Tutor] Python 3: List Comprehensions + range In-Reply-To: <20140922011320.GG29494@ando.pearwood.info> References: <20140922011320.GG29494@ando.pearwood.info> Message-ID: On Sun, Sep 21, 2014 at 10:13 PM, Steven D'Aprano wrote: > > Have patience, we're not on 24/7 duty and you don't have a SLA (Service > Level Agreement) with us. > > Normally it is considered polite to wait at least one day before sending > a reminder, not six hours. Although we have list members all over the > world, and even though sometimes it doesn't look like it, we do have > lives outside of this mailing list and sometimes we're all away from the > computer or busy doing something else. > > Or, perhaps your question is a hard question to answer and we need time > to think about it. > I'm sorry, maybe I'm a little spoiled by forums, where I post a topic and in less than 2h someone comes up with something, usually not the answer, but something - hahaha. I promise I'll be more patient. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Mon Sep 22 22:01:36 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 22 Sep 2014 17:01:36 -0300 Subject: [Tutor] Python advice about API, JSON Message-ID: I'm trying to make my script the more pythonic possible. How would a good approach regarding external API and json be? I'm calling this API (http://docs.themoviedb.apiary.io/) using 'requests'. The thing is that I need to do a bunch of different calls to the API: - http://api.themoviedb.org/3/person << Receive ID and return person info - http://api.themoviedb.org/3/tv << Receive ID and return serie info - http://api.themoviedb.org/3/movie << Receive ID and return movie info - http://api.themoviedb.org/3/search << Receive "Name of person or serie or movie" and return ID I have the following structures: - {query}/{type}?api_key={key}&query={person or tv or movie} - {query}/{id}?api_key={key} - {query}/{id}/credits?api_key={key} - {query}/{id}/season/{season_numer}?api_key={key} - {query}/{id}/season/{season_numer}/episode/{episode_number}?api_key={key} - {query}/{id}/season/{season_numer}/episode/{episode_number}/credits?api_key={key} I'm thinking about creating a class 'API' and have all these URLs and structures there. The thing is that I need to pass my API_KEY and this key will be used for everything, so I just need to pass it once, how can I do that? Yes, I know about class attributes, but the thing is that I will call this class 'API' from different classes and I'll need to instantiate a API obj in each of them, is it a good approach? Inside this 'API' class I would have a __init__ that would receive an API_KEY and different methods, each for a type of query (person, tv, movie, search, credits). Maybe my explanation is a bit confusing but I hope you guys understood, anyway, you can ask for more information if needed! And another thing, What's better, a single module with multiple classes (total lines: ~110) or multiple modules with 1-3 classes (correlated, like class serie, season and episode in the same module, and class person and character in the same module) each? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Mon Sep 22 22:30:23 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 22 Sep 2014 17:30:23 -0300 Subject: [Tutor] Python advice about API, JSON In-Reply-To: References: Message-ID: On Mon, Sep 22, 2014 at 5:10 PM, Patrick Thunstrom wrote: > On Mon, Sep 22, 2014 at 4:01 PM, Juan Christian > wrote: > > I'm trying to make my script the more pythonic possible. How would a good > > approach regarding external API and json be? > > I don't think dealing with a specific API is actually appropriate for > this list. I'll try to answer the general elements. But I do want the "general" approach, I just talked about the API I'm using for the sake of example. I don't need multiple versions of the class API, I would have only one. I would need multiple instances, because I have a person class, movie class and serie class, and each of them would need their API obj. -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Tue Sep 23 07:08:52 2014 From: questions.anon at gmail.com (questions anon) Date: Tue, 23 Sep 2014 15:08:52 +1000 Subject: [Tutor] print date and skip any repeats In-Reply-To: <20140917093505.GA9051@cskk.homeip.net> References: <20140917093505.GA9051@cskk.homeip.net> Message-ID: Thank you for your help. Using your feedback and adding the input dates and the output dates into lists. It seems to work although I am not sure if this is the correct/fastest/pythonic way to go about it. As I said it works... I have pasted below if anyone else needs something similar thanks for your help lastdate=all_the_dates[1] onedateperday.append(lastdate) print onedateperday for date in all_the_dates: if date !=lastdate: lastdate=date onedateperday.append(lastdate) On Wed, Sep 17, 2014 at 7:35 PM, Cameron Simpson wrote: > On 17Sep2014 19:21, questions anon wrote: > >> I think this should be simple but I can't find the right commands. >> >> I have a date for each hour for a whole month (and more) and I would like >> to >> write a loop that prints each date that is different but skips the dates >> that >> are the same. >> >> for i in date: >> print i and then skip i until different >> print next i and then skip i until different >> etc. >> > > If the above is what you're thinking, your problem seems to be that you're > putting the "skip i until different" inside the loop as though you do lots > of things in each loop iteration. > > What you'd really be doing is _one_ thing inside each loop iteration: > printing the date or not. The normal way to do this is to keep a variable > for the last date _print_. Each loop iteration should compare the current > date against that and either do nothing or [print the new date and update > the variable]. > > So you loop looks like this: > > lastdate = "" > for date in all_the_dates: > if date != lastdate: > ... a different date: print and then update last date ... > > See if adapting that gets you closer to working code. If your code doesn't > work, post the actualy code and a description of what it seems to be doing > wrong. > > Cheers, > Cameron Simpson > > Trust the computer industry to shorten Year 2000 to Y2K. It was this > thinking that caused the problem in the first place. > - Mark Ovens > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Sep 23 09:05:28 2014 From: davea at davea.name (Dave Angel) Date: Tue, 23 Sep 2014 03:05:28 -0400 (EDT) Subject: [Tutor] print date and skip any repeats References: <20140917093505.GA9051@cskk.homeip.net> Message-ID: Please post in text mode, not html. questions anon Wrote in message: > > lastdate=all_the_dates[1] > onedateperday.append(lastdate) > print onedateperday > for date in all_the_dates: > if date !=lastdate: > lastdate=date > onedateperday.append(lastdate) There are a number of things you don't explicitly specify. But if you require the dates in the output list to be in the same order as the original list, you have a bug in using element [1]. You should be using element zero, or more simply: lastdate=None for date in all_the_dates: if date !=lastdate: onedateperday.append(date) lastdate=date But if you specified a bit more, even simpler answers are possible. For example, if output order doesn't matter, try: onedateperday = list (set (all_the_dates)) If output order matters, but the desired order is sorted, onedateperday = sorted ( list (set (all_the_dates))) Other approaches are possible using library functions, but this should be enough. -- DaveA From jarod_v6 at libero.it Tue Sep 23 11:40:25 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Tue, 23 Sep 2014 11:40:25 +0200 (CEST) Subject: [Tutor] Regular expression Message-ID: <13460003.470381411465225310.JavaMail.defaultUser@defaultHost> Hi there!! I need to read this file: pippo.count : 10566 ZXDC 2900 ZYG11A 7909 ZYG11B 3584 ZYX 9614 ZZEF1 17704 ZZZ3 This file present a use space on the begin then they have a number and the a word. p =re.compile("\s+\d+") with open("pippo.count") as p: for i in p: lines =i.rstrip("\n").split("\t") print t.findall(str(lines)) out: [' 994'] [' 10428'] [' 1810'] [' 4880'] [' 8905'] How can extract only the number and the work in array? Thanks for any help jarod From steve at pearwood.info Tue Sep 23 13:02:07 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 23 Sep 2014 21:02:07 +1000 Subject: [Tutor] Regular expression In-Reply-To: <13460003.470381411465225310.JavaMail.defaultUser@defaultHost> References: <13460003.470381411465225310.JavaMail.defaultUser@defaultHost> Message-ID: <20140923110206.GJ29494@ando.pearwood.info> On Tue, Sep 23, 2014 at 11:40:25AM +0200, jarod_v6 at libero.it wrote: > Hi there!! > > I need to read this file: > > pippo.count : > 10566 ZXDC > 2900 ZYG11A > 7909 ZYG11B > 3584 ZYX > 9614 ZZEF1 > 17704 ZZZ3 > How can extract only the number and the work in array? Thanks for any help There is no need for the nuclear-powered bulldozer of regular expressions just to crack this peanut. with open('pippo.count') as f: for line in f: num, word = line.split() num = int(num) print num, word Or, if you prefer the old-fashioned way: f = open('pippo.count') for line in f: num, word = line.split() num = int(num) print num, word f.close() but the first way with the with-statement is better. -- Steven From questions.anon at gmail.com Wed Sep 24 11:19:45 2014 From: questions.anon at gmail.com (questions anon) Date: Wed, 24 Sep 2014 19:19:45 +1000 Subject: [Tutor] print date and skip any repeats In-Reply-To: References: <20140917093505.GA9051@cskk.homeip.net> Message-ID: Ok, I am continuing to get stuck. I think I was asking the wrong question so I have posted the entire script (see below). What I really want to do is find the daily maximum for a dataset (e.g. Temperature) that is contained in monthly netcdf files where the data are separated by hour. The major steps are: open monthly netcdf files and use the timestamp to extract the hourly data for the first day. Append the data for each hour of that day to a list, concatenate, find max and plot then loop through and do the following day. I can do some of the steps separately but I run into trouble in working out how to loop through each hour and separate the data into each day and then repeat all the steps for the following day. Any feedback will be greatly appreciated! oneday=[] all_the_dates=[] onedateperday=[] #open folders and open relevant netcdf files that are monthly files containing hourly data across a region for (path, dirs, files) in os.walk(MainFolder): for ncfile in files: if ncfile.endswith(ncvariablename+'.nc'): print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') variable=ncfile.variables[ncvariablename][:,:,:] TIME=ncfile.variables['time'][:] ncfile.close() #combine variable and time so I can make calculations based on hours or days for v, time in zip((variable[:,:,:]),(TIME[:])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(time) timestr=str(ncfiletime) utc_dt = dt.strptime(timestr, '%Y-%m-%d %H:%M:%S') au_tz = pytz.timezone('Australia/Sydney') local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(au_tz) strp_local=local_dt.strftime('%Y-%m-%d_%H') #strips time down to date and hour local_date=local_dt.strftime('%Y-%m-%d') #strips time down to just date all_the_dates.append(local_date) #make a list that strips down the dates to only have one date per day (rather than one for each hour) onedateperday = sorted ( list (set (all_the_dates))) #loop through each day and combine data (v) where the hours occur on the same day for days in onedateperday: if strp_local.startswith(days): oneday.append(v) big_array=np.ma.dstack(oneday) #concatenate data v_DailyMax=big_array.max(axis=2) # find max #then go on to plot v_DailyMax for each day map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') map.drawcoastlines() map.drawstates() map.readshapefile(shapefile1, 'REGIONS') x,y=map(*np.meshgrid(LON,LAT)) plottitle=ncvariablename+'v_DailyMax'+days cmap=plt.cm.jet CS = map.contourf(x,y,v_DailyMax, 15, cmap=cmap) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h]) plt.colorbar(CS,cax=cax, drawedges=True) plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) plt.show() plt.close() On Wed, Sep 24, 2014 at 8:27 AM, questions anon wrote: > brilliant, thank you! > > On Tue, Sep 23, 2014 at 5:05 PM, Dave Angel wrote: > >> >> Please post in text mode, not html. >> >> questions anon Wrote in message: >> > >> > lastdate=all_the_dates[1] >> > onedateperday.append(lastdate) >> > print onedateperday >> > for date in all_the_dates: >> > if date !=lastdate: >> > lastdate=date >> > onedateperday.append(lastdate) >> >> There are a number of things you don't explicitly specify. But if >> you require the dates in the output list to be in the same order >> as the original list, you have a bug in using element [1]. You >> should be using element zero, or more simply: >> >> lastdate=None >> for date in all_the_dates: >> if date !=lastdate: >> onedateperday.append(date) >> lastdate=date >> >> But if you specified a bit more, even simpler answers are possible. >> >> For example, if output order doesn't matter, try: >> onedateperday = list (set (all_the_dates)) >> >> If output order matters, but the desired order is sorted, >> onedateperday = sorted ( list (set (all_the_dates))) >> >> Other approaches are possible using library functions, but this >> should be enough. >> >> >> >> -- >> DaveA >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Thu Sep 25 21:30:49 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 25 Sep 2014 16:30:49 -0300 Subject: [Tutor] Ubuntu 14.04 + Python 3.4.1 (pyvenv) + sqlite3 Message-ID: So, I'm coding a software using Flask and sqlite3 on Ubuntu 14.04, I read that on Python 3.4.1, sqlite3 is default, but when I try to 'import sqlite3' I get: Traceback (most recent call last): File "flaskr.py", line 5, in import sqlite3 File "/usr/local/lib/python3.4/sqlite3/__init__.py", line 23, in from sqlite3.dbapi2 import * File "/usr/local/lib/python3.4/sqlite3/dbapi2.py", line 26, in from _sqlite3 import * ImportError: No module named '_sqlite3' I'm running this code in a virtualenv using pyvenv. pip list (inside venv): Flask (0.10.1) itsdangerous (0.24) Jinja2 (2.7.3) MarkupSafe (0.23) pip (1.5.6) requests (2.4.1) setuptools (5.8) Werkzeug (0.9.6) Using Python 3.4.1 The code is question is an example code from Flask doc, here: http://flask.pocoo.org/docs/0.10/tutorial/dbinit/#tutorial-dbinit I already installed 'libsqlite3-dev' (apt-get). I don't knwo what to do! -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 25 22:32:24 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2014 22:32:24 +0200 Subject: [Tutor] Ubuntu 14.04 + Python 3.4.1 (pyvenv) + sqlite3 References: Message-ID: Juan Christian wrote: > So, I'm coding a software using Flask and sqlite3 on Ubuntu 14.04, I read > that on Python 3.4.1, sqlite3 is default, but when I try to 'import > sqlite3' I get: > > Traceback (most recent call last): > File "flaskr.py", line 5, in > import sqlite3 > File "/usr/local/lib/python3.4/sqlite3/__init__.py", line 23, in > > from sqlite3.dbapi2 import * > File "/usr/local/lib/python3.4/sqlite3/dbapi2.py", line 26, in > from _sqlite3 import * > ImportError: No module named '_sqlite3' > > > I'm running this code in a virtualenv using pyvenv. > > pip list (inside venv): > Flask (0.10.1) > itsdangerous (0.24) > Jinja2 (2.7.3) > MarkupSafe (0.23) > pip (1.5.6) > requests (2.4.1) > setuptools (5.8) > Werkzeug (0.9.6) > > Using Python 3.4.1 But not the one provided by the distribution, I presume? When you compiled your Python, did you not get a message like [...] Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _sqlite3 _ssl _tkinter readline zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. [...] ? > The code is question is an example code from Flask doc, here: > http://flask.pocoo.org/docs/0.10/tutorial/dbinit/#tutorial-dbinit > > I already installed 'libsqlite3-dev' (apt-get). So after $ sudo apt-get install libsqlite3-dev Did you invoke $ ./configure $ make again? The output should have changed slightly: [...] Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _ssl _tkinter readline zlib [...] > I don't knwo what to do! Btw, I think this is off-topic for the tutor mailing list which is supposed to help with basic usage of Python. From paulrsmith7777 at gmail.com Fri Sep 26 19:25:53 2014 From: paulrsmith7777 at gmail.com (Paul Smith) Date: Fri, 26 Sep 2014 13:25:53 -0400 Subject: [Tutor] Module? Error handling specific to SQLite3 Message-ID: Ok Tutor help please... Early stages messing with module sqlite3 in python3.4. I am successful in creating sqlite tables of my own and interacting with other sqlite tables, however in refining the code from a purely "it can do it" stage to a more stable working piece of code I run into this problem. I call the correct sqlite3 items and create table D to which I add or 'amend' specific information from tables A and Z. However since the table is already created the line of code that created the table subsequently kicks out this error when the program runs again. Traceback (most recent call last): File "C:\Users\Thechives\Desktop\pyweather\AlphaItems\ weathercodetrial1.2.py", line 206, in cur.execute('''CREATE TABLE "D" AS SELECT weather_current FROM "todays_weather" WHERE weather_current IS NOT NULL''') sqlite3.OperationalError: table "D" already exists So how does one handle the error or ignore the creation portion of the program once the table is created? Python exception handling has not helped, Try - Except - although I am mashing it I am sure. I believe since we are actually engaging sqlite via python at this point in the code it should be a sqlite error handler or some such. So simple and yet it eludes my noobile mind. Thanks in advance, Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 26 19:46:44 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2014 19:46:44 +0200 Subject: [Tutor] Module? Error handling specific to SQLite3 References: Message-ID: Paul Smith wrote: > Early stages messing with module sqlite3 in python3.4. I am successful in > creating sqlite tables of my own and interacting with other sqlite tables, > however in refining the code from a purely "it can do it" stage to a more > stable working piece of code I run into this problem. > > I call the correct sqlite3 items and create table D to which I add or > 'amend' specific information from tables A and Z. > > However since the table is already created the line of code that created > the table subsequently kicks out this error when the program runs again. > > Traceback (most recent call last): > File "C:\Users\Thechives\Desktop\pyweather\AlphaItems\ > weathercodetrial1.2.py", line 206, in > cur.execute('''CREATE TABLE "D" AS SELECT weather_current FROM > "todays_weather" WHERE weather_current IS NOT NULL''') > sqlite3.OperationalError: table "D" already exists > > So how does one handle the error or ignore the creation portion of the > program once the table is created? > > Python exception handling has not helped, Try - Except - although I am > mashing it I am sure. I believe since we are actually engaging sqlite via > python at this point in the code it should be a sqlite error handler or > some such. So simple and yet it eludes my noobile mind. While you could wrap the cur.execute() in a try except try: cur.execute('''CREATE TABLE "D" ...''') except sqlite3.OperationalError: pass # assume that the table already exists and ignore the error there is a also way to handle this in SQL: cur.execute('''CREATE TABLE IF NOT EXISTS "D" ...''') See also the sqlite3 documentation at . From yanglei.fage at gmail.com Sun Sep 28 16:53:06 2014 From: yanglei.fage at gmail.com (lei yang) Date: Sun, 28 Sep 2014 22:53:06 +0800 Subject: [Tutor] how to express shift+enter in python Message-ID: Hi expert, How to express shift+enter in python ? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Sep 28 17:04:16 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 28 Sep 2014 17:04:16 +0200 Subject: [Tutor] how to express shift+enter in python In-Reply-To: References: Message-ID: On Sun, Sep 28, 2014 at 4:53 PM, lei yang wrote: > Hi expert, > > How to express shift+enter in python ? > > Thanks What do you want to express, exactly? This key combination can have multiple meanings and ways to achieve it, depending on your needs. Do you want to send the key combination to an app? What is it, exactly, that you want to do? What app uses Shift+Enter in the way you want to use it? -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From yanglei.fage at gmail.com Sun Sep 28 17:11:26 2014 From: yanglei.fage at gmail.com (lei yang) Date: Sun, 28 Sep 2014 23:11:26 +0800 Subject: [Tutor] how to express shift+enter in python In-Reply-To: References: Message-ID: Hi Chris, I just use "xlwt" lib to newline in one cell, I find it display with one line in windows but works in linux, so I guess it maybe"shift+enter" to newline Lei On Sun, Sep 28, 2014 at 11:04 PM, Chris ?Kwpolska? Warrick < kwpolska at gmail.com> wrote: > On Sun, Sep 28, 2014 at 4:53 PM, lei yang wrote: > > Hi expert, > > > > How to express shift+enter in python ? > > > > Thanks > > What do you want to express, exactly? This key combination can have > multiple meanings and ways to achieve it, depending on your needs. Do > you want to send the key combination to an app? What is it, exactly, > that you want to do? What app uses Shift+Enter in the way you want to > use it? > > -- > Chris ?Kwpolska? Warrick > PGP: 5EAAEA16 > stop html mail | always bottom-post | only UTF-8 makes sense > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Sep 28 18:25:12 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Sep 2014 02:25:12 +1000 Subject: [Tutor] how to express shift+enter in python In-Reply-To: References: Message-ID: <20140928162511.GL19757@ando.pearwood.info> On Sun, Sep 28, 2014 at 11:11:26PM +0800, lei yang wrote: > Hi Chris, > > I just use "xlwt" lib to newline in one cell, I find it display with one > line in windows but works in linux, so I guess it maybe"shift+enter" to > newline I am afraid I have no idea what you are talking about. Can you show some code, and the expected result? Regards, Steve > Lei > > > On Sun, Sep 28, 2014 at 11:04 PM, Chris ?Kwpolska? Warrick < > kwpolska at gmail.com> wrote: > > > On Sun, Sep 28, 2014 at 4:53 PM, lei yang wrote: > > > Hi expert, > > > > > > How to express shift+enter in python ? > > > > > > Thanks > > > > What do you want to express, exactly? This key combination can have > > multiple meanings and ways to achieve it, depending on your needs. Do > > you want to send the key combination to an app? What is it, exactly, > > that you want to do? What app uses Shift+Enter in the way you want to > > use it? > > > > -- > > Chris ?Kwpolska? Warrick > > PGP: 5EAAEA16 > > stop html mail | always bottom-post | only UTF-8 makes sense > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From akleider at sonic.net Sun Sep 28 22:14:20 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 28 Sep 2014 13:14:20 -0700 Subject: [Tutor] how to express shift+enter in python In-Reply-To: References: Message-ID: <052d56953fd59042ed39f3d8da0ea8d2@sonic.net> On 2014-09-28 07:53, lei yang wrote: > Hi expert, > > How to express shift+enter in python ? Have you tried ^J or chr(10)? i.e. shift_plus_enter = chr(10) From davea at davea.name Mon Sep 29 02:07:01 2014 From: davea at davea.name (Dave Angel) Date: Sun, 28 Sep 2014 20:07:01 -0400 (EDT) Subject: [Tutor] how to express shift+enter in python References: Message-ID: lei yang Wrote in message: > > I just use "xlwt" lib to newline in one cell, I find it display with one line > in windows but works in linux, so I guess it maybe"shift+enter" to newline Xlwt isn't in the Python stdlib, so some other forum is probably preferable to tutor. Just how are you "newlining"? Can you post some example code? "It" displays with one line in Windows. Using what command, TYPE? If you're using a particular program, such as Lotus 123, you should specifit. Likewise in Linux, you might be using Open Office, or Libre Office Calc, or ... I can't see what relevancy a keystroke combination has when you're presumably writing a spreadsheet file with code. You should probably concentrate on what data in the spreadsheet is desired. -- DaveA From hgfernan at gmail.com Mon Sep 29 03:07:03 2014 From: hgfernan at gmail.com (Hilton Fernandes) Date: Sun, 28 Sep 2014 22:07:03 -0300 Subject: [Tutor] how to express shift+enter in python In-Reply-To: References: Message-ID: Dear all, the reading of specific keys is sometimes a necessity. For instance: some text fields will let you insert a newline in the block of text if you press the combination Shift+Enter, while pressing the sole Enter key will cause the whole text to be transmitted. Unfortunately, reading these combinations tend to be specific to the operating system yo use, and are not available to the standard Python library, that AFAIK is more concerned with chars than with keys. In the context of Python, i suppose that TCL/Tk probably has this feature and windowing environments for Python like wxPython, PyGTK, and PyQt. So, dear Ley Yang, would you mind please telling us what's the OS you're using ? Maybe Window ? And please comment more about your programming experience. This list has a specific focus, but the experts here are certainly able to recommend you to another list, if that's the case. I wish a nice week to everybody everywhere. 8-) All the best, Hilton On Sun, Sep 28, 2014 at 9:07 PM, Dave Angel wrote: > lei yang Wrote in message: > > > > > I just use "xlwt" lib to newline in one cell, I find it display with one > line > > in windows but works in linux, so I guess it maybe"shift+enter" to > newline > > Xlwt isn't in the Python stdlib, so some other forum is probably > preferable to tutor. > > Just how are you "newlining"? Can you post some example code? > > "It" displays with one line in Windows. Using what command, > TYPE? If you're using a particular program, such as Lotus 123, > you should specifit. Likewise in Linux, you might be using Open > Office, or Libre Office Calc, or ... > > I can't see what relevancy a keystroke combination has when you're > presumably writing a spreadsheet file with code. You should > probably concentrate on what data in the spreadsheet is > desired. > > -- > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From armindorod at gmail.com Sun Sep 28 04:36:12 2014 From: armindorod at gmail.com (Armindo Rodrigues) Date: Sat, 27 Sep 2014 22:36:12 -0400 Subject: [Tutor] List and dictionary comprehensions Message-ID: Hi everyone, This is my first post so I don't know if I am asking the correct way so let me know if I messed anything up. ***Please note. My code contains a list of quotes that has many lines. I have noted the beginning and end of the quotes list so you can easily skip and go straight to the code section. *** This is technically NOT a homework assignment. I am the teaching assistant for the Python course at my school. The teacher doesn't give me the homework ahead of time so I typically try the homework myself so I can help anyone else out that may be confused. The assignment has come and gone but I want to challenge myself with making this thing more efficient and learn comprehensions along the way. The assignment was as follows: The teacher provided the class with a list of quotes called data_list. We were to implement a very simple search algorithm that took in a user's query and we searched based on those words. If the user entered an OR then we searched for quotes that contained either of the words. Any other combination of AND OR will be an AND search. Once we completed the search algorithm, the assignment called for pre-processing that would make the search more efficient and faster. I created a dictionary based on each word in the quotes list as the key and then searched against those words. I greatly increased the search time. MY QUESTION: Can anyone look at this and explain how I could create a list comprehension and a dictionary comprehension if possible? Also any suggestions with making the search faster would be appreciated. import re from datetime import datetime import time ################### DATA LIST STARTS HERE data_list=["And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.", "All grown-ups were once children... but only few of them remember it.", "People have forgotten this truth,\" the fox said. \"But you mustn?t forget it. You become responsible forever for what you?ve tamed. You?re responsible for your rose.", "It is the time you have wasted for your rose that makes your rose so important.", "The most beautiful things in the world cannot be seen or touched, they are felt with the heart.", "What makes the desert beautiful,' said the little prince, 'is that somewhere it hides a well...", "You - you alone will have the stars as no one else has them...In one of the stars I shall be living. In one of them I shall be laughing. And so it will be as if all the stars were laughing, when you look at the sky at night...You - only you - will have stars that can laugh.", "Well, I must endure the presence of a few caterpillars if I wish to become acquainted with the butterflies.", "You see, one loves the sunset when one is so sad.", "You're beautiful, but you're empty...One couldn't die for you. Of course, an ordinary passerby would think my rose looked just like you. But my rose, all on her own, is more important than all of you together, since she's the one I've watered. Since she's the one I put under glass, since she's the one I sheltered behind the screen. Since she's the one for whom I killed the caterpillars (except the two or three butterflies). Since she's the one I listened to when she complained, or when she boasted, or even sometimes when she said nothing at all. Since she's my rose.", "If you love a flower that lives on a star, it is sweet to look at the sky at night. All the stars are a-bloom with flowers...", "And when your sorrow is comforted (time soothes all sorrows) you will be content that you have known me. You will always be my friend. You will want to laugh with me. And you will sometimes open your window, so, for that pleasure . . . And your friends will be properly astonished to see you laughing as you look up at the sky! Then you will say to them, 'Yes, the stars always make me laugh!' And they will think you are crazy. It will be a very shabby trick that I shall have played on you...", "You become responsible, forever, for what you have tamed.", "Of course I?ll hurt you. Of course you?ll hurt me. Of course we will hurt each other. But this is the very condition of existence. To become spring, means accepting the risk of winter. To become presence, means accepting the risk of absence.", "Where are the people?\" resumed the little prince at last. \"It?s a little lonely in the desert\" \"It is lonely when you?re among people, too,\" said the snake.", "All men have stars, but they are not the same things for different people. For some, who are travelers, the stars are guides. For others they are no more than little lights in the sky. For others, who are scholars, they are problems... But all these stars are silent. You-You alone will have stars as no one else has them... In one of the stars I shall be living. In one of them I shall be laughing. And so it will be as if all the stars will be laughing when you look at the sky at night..You, only you, will have stars that can laugh! And when your sorrow is comforted (time soothes all sorrows) you will be content that you have known me... You will always be my friend. You will want to laugh with me. And you will sometimes open your window, so, for that pleasure... It will be as if, in place of the stars, I had given you a great number of little bells that knew how to laugh", "She cast her fragrance and her radiance over me. I ought never to have run away from her... I ought to have guessed all the affection that lay behind her poor little stratagems. Flowers are so inconsistent! But I was too young to know how to love her...", "A rock pile ceases to be a rock pile the moment a single man contemplates it, bearing within him the image of a cathedral.", "I did not know how to reach him, how to catch up with him... The land of tears is so mysterious.", "I remembered the fox. One runs the risk of crying a bit if one allows oneself to be tamed.", "When someone blushes, doesn't that mean 'yes'?", "You're beautiful, but you're empty. No one could die for you.", "In those days, I didn't understand anything. I should have judged her according to her actions, not her words. She perfumed my planet and lit up my life. I should never have run away! I ought to have realized the tenderness underlying her silly pretensions. Flowers are so contradictory! But I was too young to know how to love her.", "I have lived a great deal among grown-ups. I have seen them intimately, close at hand. And that hasn?t much improved my opinion of them.", "Grown-ups love figures... When you tell them you've made a new friend they never ask you any questions about essential matters. They never say to you \"What does his voice sound like? What games does he love best? Does he collect butterflies? \" Instead they demand \"How old is he? How much does he weigh? How much money does his father make? \" Only from these figures do they think they have learned anything about him.", "The proof that the little prince existed is that he was charming, that he laughed, and that he was looking for a sheep. If anybody wants a sheep, that is a proof that he exists.", "No one is ever satisfied where he is.", "I was too young to know how to love her.", "I am who I am and I have the need to be.", "But the conceited man did not hear him. Conceited people never hear anything but praise.", "Men have no more time to understand anything. They buy things all ready made at the shops. But there is no shop anywhere where one can buy friendship, and so men have no friends any more. If you want a friend, tame me...", "For millions of years flowers have been producing thorns. For millions of years sheep have been eating them all the same. And it's not serious, trying to understand why flowers go to such trouble to produce thorns that are good for nothing? It's not important, the war between the sheep and the flowers? It's no more serious and more important than the numbers that fat red gentleman is adding up? Suppose I happen to know a unique flower, one that exists nowhere in the world except on my planet, one that a little sheep can wipe out in a single bite one morning, just like that, without even realizing what he'd doing - that isn't important? If someone loves a flower of which just one example exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars. He tells himself 'My flower's up there somewhere...' But if the sheep eats the flower, then for him it's as if, suddenly, all the stars went out. And that isn't important?", "I have always loved the desert. One sits down on a desert sand dune, sees nothing, hears nothing. Yet through the silence something throbs, and gleams...", "People have stars, but they aren't the same. For travelers, the stars are guides. For other people, they're nothing but tiny lights. And for still others, for scholars, they're problems... But all those stars are silent stars. You, though, you'll have stars like nobody else... since I'll be laughing on one of them, for you it'll be as if all the stars are laughing. You'll have stars that can laugh!... and it'll be as if I had given you, instead of stars, a lot of tiny bells that know how to laugh ...", "What does tamed mean? It's something that's been too often neglected. It means to create ties.", "The only things you learn are the things you tame", "One runs the risk of weeping a little, if one lets himself be tamed.", "You're not at all like my rose. You're nothing at all yet. No one has tamed you and you haven't tamed anyone. You're the way my fox was. He was just a fox like a hundred thousand others. But I've made him my own and now he is unique in the world.", "I ought not to have listened to her,' he confided to me one day. 'One never ought to listen to the flowers. One should simply look at them and breathe their fragrance. Mine perfumed all my planet. But I did not know how to take pleasure in all her grace.", "You will have five hundred million little bells, and I shall have five hundred million springs of fresh water...", "if you tame me, then we shall need each other. To me, you will be unique in all the world. To you, I shall be unique in all the world if you tame me, it will be as if the sun came to shine on my life. I shall know the sound of a step that will be different from all the others. Other steps send me hurrying back underneath the ground. Yours will call me, like music, out of my burrow", "If you tame me, it would be as if the sun came to shine on my life.", "Men have no more time to understand anything. They buy ready-made things in the shops. But since there are no shops where you can buy friends, men no longer have any friends.", "All grown-ups were children first. (But few remember it).", "Of course, I love you,' the flower said to him. 'If you were not aware of it, it was my fault.", "The thing that is important is the thing that is not seen.", "It is much more difficult to judge oneself than to judge others.", "You know...my flower...I'm responsible for her. And she's so weak! And so naive. She has four ridiculous thorns to defend her against the world...", "\"Ephemeral\" It means 'which is in danger of speedy disappearance.", "He fell as gently as a tree falls. There was not even any sound..", "The house, the stars, the desert -- what gives them their beauty is something that is invisible!", "\"My life is very monotonous,\" the fox said. \"I hunt chickens; men hunt me. All the chickens are just alike, and all the men are just alike. And, in consequence, I am a little bored.\"", "Sometimes, there is no harm in putting off a piece of work until another day.", "Only the children know what they are looking for.", "Grown ups never understood anything by themselves. And it is rather tedious to have to explain things to them time and again", "It is much more difficult to judge oneself than to judge others. If you succeed in judging yourself rightly, then you are a man of true wisdom.", "Words are the source of misunderstandings.", "And the little prince broke into a lovely peal of laughter, which irritated me very much. I like my misfortunes to be taken seriously.", "\"What a queer planet!\" he thought. \"It is altogether dry, and altogether pointed, and altogether harsh and forbidding. And the people have no imagination. They repeat whatever one says to them . . . On my planet I had a flower; she always was the first to speak . . .", "I know a planet where there is a certain red-faced gentleman. He has never smelled a flower. He has never looked at a star. He has never loved any one. He has never done anything in his life but add up figures. And all day he says over and over, just like you: 'I am busy with matters of consequence!' And that makes him swell up with pride. But he is not a man - he is a mushroom!", "But if you tame me, my life will be filled with sunshine. I'll know the sound of footsteps that will be different from all the rest. Others send me back underground. Yours will call me out of my burrow like music.", "I believe that for his escape he took advantage of the migration of a flock of wild birds.", "He had taken seriously words which were without importance, and it made him very unhappy.", "If you come at four in the afternoon, I'll begin to be happy by three.", "One must require from each one the duty which each one can perform. Accepted authority rests first of all on reason.", "Straight ahead you can't go very far.", "One sees clearly only with the heart. Anything essential is invisible to the eyes.", "I wonder if the stars are lit up so that each one of us can find her own star again.", "My drawing was not a picture of a hat. It was a picture of a boa constrictor digesting an elephant.", "To you I am just a fox, like a hundred thousand others, but if you tame me we shall need one another and I shall be unique to you in all the world.", "Don't linger like this. You have decided to go away. Now go!", "But I, alas, do not know how to see sheep through the walls of boxes. Perhaps I am a little like the grown-ups. I have had to grow old.", "I remembered the fox. You risk tears if you let yourself be tamed.", "Wait for a time, exactly under the star. Then, if a little man appears who laughs, who has golden hair and refuses to answer questions, you will know who he is, If this should happen, please comfort me. Send me word that he has come back.", "If I am attempting to describe him, it is in order not to forget him. It is sad to forget a friend. Not every one has had a friend.", "The thing that is important is the thing that is not seen", "Nevertheless he is the only one of them all who does not seem to me ridiculous. Perhaps that is because he is thinking of something else besides himself.", "If someone loves a flower of which just one exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars.", "If you want to build a ship, don't drum up people to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.", "Will you draw me a sheep?", "It's good to have a friend. Even if you're going to die.", "If you love a flower that lives on a star, then it's good at night, to look up at the sky. All the stars are blossoming."] ################## CODE STARTS HERE #Create a list of words taken from each individual word in the datalist word_list = [] for item in data_list: for word in item.split(" "): word = re.sub('^[^a-zA-z]*|[^a-zA-Z]*$','', word) #Remove punctuation word_list.append(word) word_list = sorted(list(set(word_list))) #Remove repeated words quotesDict = {} for word in word_list: quotesDict.setdefault(word,[]) #Create a dictionary with keys based on each word in the word list for key, value in quotesDict.items(): indexofquote = 0 for quote in data_list: if key in quote: quotesDict[key].append(indexofquote) #Append the index of the found quotes to the dictionary key indexofquote+=1 query=input("query: ") query = query.strip(" ").split(" ") query = list(set(query)) start_time = time.time() FoundQuotes = [] # Right now the OR search just prints out the index of the found quotes. if ("or" in query) and ("and" not in query): query.remove("or") print("Performing OR search for: ", query) for item in query: if (item in quotesDict): print("FOUND ",len(quotesDict[item]), " ", item, "QUOTES: ", quotesDict.get(item)) print("\n--- Execution ---\n", (time.time() - start_time) * 1000, "microseconds\n") else: if "and" in query: query.remove("and") if "or" in query: query.remove("or") print("Performing AND search for: ", query) for item in query: if (item in quotesDict): FoundQuotes = FoundQuotes + (quotesDict.get(item)) FoundQuotes = list(set([x for x in FoundQuotes if FoundQuotes.count(x) > 1])) for x in FoundQuotes: print(data_list[x]) print("\n--- Execution ---\n", (time.time() - start_time) * 1000, "microseconds\n") -------------- next part -------------- An HTML attachment was scrubbed... URL: From braveheartmovement at yahoo.com Fri Sep 26 13:58:09 2014 From: braveheartmovement at yahoo.com (Brave Heart) Date: Fri, 26 Sep 2014 04:58:09 -0700 Subject: [Tutor] I've been trying to make this program work so i can transfer it to final user. please do have a look and see if the code can be corrected in anyway. Message-ID: <1411732689.20273.YahooMailNeo@web120904.mail.ne1.yahoo.com> Perrsonal Monney Assistance(PMA =============================== 1. ADD Record 2. MODIFY Record 3. DELETE Record 4. SHOW All 5. SHOW Summary 6. Exit Please enter your Choise (1-6): 1 ADD Record ========== (Key in '-e' to back to main menu) Key in new record .. Date : 09-09-2013 For : sh Total : EU 10 Traceback (most recent call last): File "C:/Python34/cash.py", line 602, in main_menu() File "C:/Python34/cash.py", line 45, in main_menu resp_process(resp) File "C:/Python34/cash.py", line 52, in resp_process add_rec() File "C:/Python34/cash.py", line 115, in add_rec add_func(date, desc, amt) File "C:/Python34/cash.py", line 339, in add_func os.chdir(sqlite3_path) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:/sqlite3/' This is my code: #******************************************************************************* # Program Name : cash.py (Personal Finance Assistance) # Version : 1.8 # Desciption : This program is menu-based program which can connect to database # and then performming addition, updating, deletion and showing # the summary. It use to record personal daily expenses. # Working in : Null # Future : Add "search" function, # Add some "Analysis Tools" # Ext. Module : sqlite3 #******************************************************************************* #imported library files import sqlite3 import re import os import time import sys #global variables sqlite3_path = ("C:/sqlite3/") database = "cash.db" # format = DD-MM-YYYY date_format = r'^([0-3][\d])([-])([0-1][\d])([-])([\d]{4})$' def main_menu(): '''Display main menu (LO)''' os.system("cls") print ("Perrsonal Monney Assistance(PMA") print ("===============================") print ("1. ADD Record") print ("2. MODIFY Record") print ("3. DELETE Record") print ("4. SHOW All") print ("5. SHOW Summary") print ("6. Exit") resp = input("Please enter your Choise (1-6): ") resp_process(resp) def resp_process(r): '''Process the response from user input (L1)''' if str(r).isdigit() == 1 and int(r) >= 0 and int(r) <= 5: if r == '1': add_rec() elif r == '2': edit_rec() elif r == '3': del_rec() elif r == '4': show_all() elif r == '5': show_summ() else: exit() else: print ("You have enter an invalid input\n") time.sleep(2) # return to main menu main_menu() def add_rec(): '''Add data to db from user input (L1)''' # get current date currDate = time.strftime("%d-%m-%Y", time.localtime(time.time())) cont = 1 os.system("cls") #print function header print ("ADD Record") print ("==========") print ("(Key in '-e' to back to main menu)") while cont == 1: print ("\nKey in new record .. ") # get input for date date = input("Date : ") back_main_menu(date) if date == "": date = currDate else: while date_check(date) == 0: print ("Error! It's not a date.\n") date = raw_input("Date : ") back_main_menu(date) if date == "": date = currDate # get input for description desc = input("For : ") back_main_menu(desc) # get input for amount amt = input("Total : EU ") back_main_menu(amt) while amt_check(amt) == 0: print ("Error! It's not a money.\n") amt = raw_input("Total : EU") back_main_menu(amt) amt = "%.2f" % float(amt) # insert to sqlite add_func(date, desc, amt) resp = raw_input("Continue ? ") resp = resp.upper() if resp == 'N': cont = 0 # return to main menu main_menu() def edit_rec(): ''' Edit / Modify record in db(L1)''' os.system("cls") #print function header print ("MODIFY Record") print ("=============") print ("(Key in '-e' to back to main menu)") s_date = raw_input("Enter the DATE of record you want to modify: ") back_main_menu(s_date) col = "date" result = search_func(col, s_date) # print search result if len(result) > 0: for i in range (len(result)): dt = result[i][0] ds = result[i][1] at = result[i][2] at = ("%.2f") % float(at) print (i+1), ")", ("%s%s%s%s%s%s%s%s%s") % ((" " * (2 - (i + len(")")))), "Date: ", dt, (" " * (20 - len(dt))), "Desc: ", ds, (" " * (25 - len(ds))), "Amount: RM", at) row = raw_input("Enter the number of row you want to modify: ") back_main_menu(row) if row.isdigit() == 1: row = int(row) if row >= 0 and row <= i+1: rowNo = int(row) - 1 last_date = result[rowNo][0] last_desc = result[rowNo][1] last_amt = result[rowNo][2] print ("Key in the new version of record") print ("(Press if no update on that field)") e_date = raw_input("NEW date: ") back_main_menu(e_date) if e_date == "": e_date = last_date e_desc = raw_input("NEW description: ") back_main_menu(e_desc) if e_desc == "": e_desc = last_desc e_amt = raw_input("NEW amount: RM ") back_main_menu(e_amt) if e_amt == "": e_amt = last_amt edit_func(e_date, e_desc, e_amt, last_date, last_desc, last_amt) else: print ("Sorry, NO data match with '", s_date, "'") # return to main menu main_menu() def del_rec(): '''Delete record from db(L1)''' os.system("cls") #print function header print ("DELETE Record") print ("=============") print ("(Key in '-e' to back to main menu)") s_date = raw_input("Enter the DATE of record you want to delete: ") back_main_menu(s_date) col = "date" result = search_func(col, s_date) # print search result if len(result) > 0: for i in range (len(result)): dt = result[i][0] ds = result[i][1] at = result[i][2] print (i+1), ")", ("%s%s%s%s%s%s%s%s%s") % ((" " * (2 - (i + len(")")))), "Date: ", dt, (" " * (20 - len(dt))), "Desc: ", ds, (" " * (25 - len(ds))), "Amount: RM", at) row = raw_input("Enter the number of row you want to delete: ") back_main_menu(row) if row.isdigit() == 1: row = int(row) if row >= 0 and row <= i+1: rowNo = int(row) - 1 d_date = result[rowNo][0] d_desc = result[rowNo][1] d_amt = result[rowNo][2] print ("You been choosen ") print (row), ")", "Date: ", d_date, "\tDesc: ", d_desc, "\t\tAmount: ", d_amt resp = raw_input("Are you sure want to delete? (Y/N): ") resp = resp.upper() back_main_menu(resp) if resp == 'Y': delete_func(d_date, d_desc, d_amt) else: print ("Sorry, NO data match with '"), s_date, "'" # return to main menu main_menu() def show_all(): '''Get details of attribute for the records(L1)''' currDate = time.strftime("%d-%m-%Y", time.localtime(time.time())) nowDate = str(currDate).split("-") month = nowDate[1] year = nowDate[2][2:] os.system("cls") print ("SHOW ALL Record") print ("===============") print ("Enter details of the record you want") print ("Press for current year or month") print ("(Key in '-e' to back to main menu)") yr = raw_input("Year (YY) : ") if yr == "": yr = year mth = raw_input("Month (MM) : ") back_main_menu(mth) if mth == "": mth = month fg = 1 else: if 1 < int(mth) <= 12: fg = 1 else: fg = 0 if fg == 1: show_all_sql(yr, mth) else: print ("Unvalid date") time.sleep(2) # return to main menu main_menu() def show_summ(): # unused function # '''Get details of attribute for the records(L1)''' currDate = time.strftime("%d-%m-%Y", time.localtime(time.time())) nowDate = str(currDate).split("-") month = nowDate[1] year = nowDate[2][2:] os.system("cls") print ("SHOW SUMMARY Record") print ("===================") print ("Enter details of the record you want") print ("Press for current year or month") print ("(Key in '-e' to back to main menu)") #yr = raw_input("Year (YYYY) : ") #if yr == "": yr = year mth = raw_input("Month (MM) : ") back_main_menu(mth) if mth == "": mth = month fg = 1 else: if 1 < int(mth) <= 12: fg = 1 else: fg = 0 if fg == 1: show_summ_sql(yr, mth) else: print ("Unvalid date") time.sleep(2) # return to main menu main_menu() def exit(): '''Exit from the program(L1)''' os.system("cls") print ("Thank you for using PMA v1.8") print ("Closing Connections & Programs... ") time.sleep(1) print ("Good Bye\n") print ("another Highman (edition) program") time.sleep(2) sys.exit() def add_func(dt, ds, at): '''Insert data into db(L2)''' sql_insert = """ INSERT INTO expenses (date, desc, amount) VALUES ('%s', '%s', '%s') """ % (dt, ds, at) os.chdir(sqlite3_path) # open connection to database try: cx = sqlite.connect(database) except sqlite.Error(errmsg): print ("Can not open ") +str(errmsg) # insert data into table try: cu = cx.cursor() cu.execute(sql_insert) cx.commit() except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() def search_func(field, key): '''Search Function (L2)''' data = [] os.chdir(sqlite_path) # open connection to database try: cx = sqlite.connect(database) except sqlit.Error(errmsg): print ("Can not open ") +str(errmsg) # select data from table try: cu = cx.cursor() cu.execute(""" SELECT * FROM expenses""" + ' WHERE ("' +str(field)+ '") like ("' '%'+str(key)+'%' '")' ) data = cu.fetchall() cx.commit() except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() return data def edit_func(new_date, new_desc, new_amt, old_date, old_desc, old_amt): '''Edit / Update function (L2)''' os.chdir(sqlite_path) # open connection to database try: cx = sqlite.connect(database) except sqlite.Error(errmsg): print ("Can not open ") +str(errmsg) # select data from table try: cu = cx.cursor() cu.execute(""" UPDATE expenses """ + ' SET date = ("' +str(new_date)+ '"), desc = ("' +str(new_desc)+ '"), amount = ("' +str(new_amt)+ '") WHERE date = ("' +str(old_date)+ '") AND desc = ("' +str(old_desc)+ '") AND amount = ("' +str(old_amt)+ '") ') cx.commit() print ("Update Complete.") except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() def delete_func(del_date, del_desc, del_amt): '''Delete Function (L2)''' os.chdir(sqlite_path) # open connection to database try: cx = sqlite.connect(database) except sqlit.Error(errmsg): print ("Can not open ") +str(errmsg) # select data from table try: cu = cx.cursor() cu.execute(""" DELETE FROM expenses """ + ' WHERE date = ("' +str(del_date)+ '") AND desc = ("' +str(del_desc)+ '") AND amount = ("' +str(del_amt)+ '") ') cx.commit() print ("The record of ") print (del_date, del_desc, del_amt,) (" been Deleted.") main_menu() except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() def show_all_sql(y, m): '''Display the all of records(L2)''' j = -1 os.chdir(sqlite_path) os.system("cls") # open connection to database try: cx = sqlite.connect(database) except sqlite.Error(errmsg): print ("Can not open ") + str(errmsg) # select data from table try: cu = cx.cursor() cu.execute("""SELECT * from expenses""" + ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") ORDER BY date') summ = cu.fetchall() cu.execute("""SELECT date, sum(amount) from expenses """ + ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") GROUP BY date ') dailySum = cu.fetchall() cu.execute("""SELECT SUM(amount) from expenses""" + ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '")' ) total = cu.fetchone() cx.commit() except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() if len(summ) > 0: # print function header print ("\nFull Records for"), m, "/", y print ("===========================") # print the report print ("Date"), ('%s%s%s%s') % ((" " * (20 - len("Date"))), "Desc", (" " * (28 - len("Desc"))), "Total(RM)") print ("===="), ('%s%s%s%s') % ((" " * (20 - len("===="))), "====", (" " * (28 - len("===="))), "=========") for i in range(0, len(summ)): date = summ[i][0] desc = summ[i][1] amt = "%6.2f" % float(summ[i][2]) if date != summ[i-1][0]: # print daily subtotal if j > -1: dailyTot = "%6.2f" % float(dailySum[j][1]) print ('%s%s') % (" " * 49, "--------") print ('%s%s%s%s') % (" " * 49, "RM", dailyTot, "\n") j += 1 #print daily expenses print (date), ('%s%s%s%s') %((" " * (20 - len(date))), desc, (" " * (30 - len(desc))), amt) # print daily subtotal (for the current day) dailyTot = "%6.2f" % float(dailySum[j][1]) print ('%s%s') % (" " * 49, "--------") print ('%s%s%s%s') % (" " * 49, "RM", dailyTot, "\n") #print total of month tot = "%6.2f" % float(total[0]) print ("==========================================================") print ("Grant total until", date, "\t\t\t RM", tot) wait = raw_input("\nPress to continue") else: print ("No data for Month "), m, "\n" wait = raw_input("Press to continue") # return to main menu main_menu() def show_summ_sql(y, m): # unused function # '''Display the summary of records(L2)''' os.system("cls") os.chdir(sqlite_path) # open connection to database try: cx = sqlite.connect(database) except sqlit.Error(errmsg): print ("Can not open ") + str(errmsg) # insert data into table try: cu = cx.cursor() cu.execute("""SELECT date, sum(amount) from expenses """ + ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '") GROUP BY date ') summ = cu.fetchall() cu.execute("""SELECT SUM(amount) from expenses""" + ' WHERE date like ("' '%-'+str(m)+'-%'+str(y)+ '")') total = cu.fetchone() cx.commit() except sqlite.Error(errmsg): print ("Can not execute: ") +str(errmsg) # close connection cx.close() if len(summ) > 0: # print function header print ("\nDaily Based Summary for"), m, "/", y print ("=================================") # print the report for i in range(len(summ)): date = summ[i][0] amt = "%6.2f" % float(summ[i][1]) print ("Date: "), date, "\t Total: EU", amt tot = "%6.2f" % float(total[0]) print ("===========================================") print ("Grant total until"), date, " EU", tot wait = raw_input("Press to continue") else: print ("No data for month "), m, ", year", y, "\n" wait = raw_input("Press to continue") # return to main menu main_menu() def date_check(data): '''Data validation for date''' if re.match(date_format, data) != None: return 1 return 0 def amt_check(data): '''Check the data is in the form of money or not''' # format = 123.45 data = str(data) if data.isdigit(): return 1 else: try: new = "%.2f" % float(data) return 1 except: return 0 def back_main_menu(data): '''Check input data for requist back to main menu (L3)''' data = data.upper() if data == "-E": main_menu() if __name__ == '__main__': main_menu() -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregory.karakeussian at gmail.com Sat Sep 27 21:32:23 2014 From: gregory.karakeussian at gmail.com (Gregory Karakeussian) Date: Sat, 27 Sep 2014 15:32:23 -0400 Subject: [Tutor] Problem with pythonw.exe Message-ID: <027201cfda89$c4780b50$4d6821f0$@gmail.com> Hi there, My antivirus has uninstalled pythonw.exe by mistake and now I can`t fix it, deinstall it, reinstall it, I'm stuck.. is there a solution? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From madeleine.austen at cvcweb.net Sun Sep 28 17:26:33 2014 From: madeleine.austen at cvcweb.net (Madeleine Austen) Date: Sun, 28 Sep 2014 16:26:33 +0100 Subject: [Tutor] python code error Message-ID: Hi Here is my code: from datetime import datetime timeStart = datetime.now().strftime('%Y-%m-%d %H:%M:%S') numberPlates = 0 print("There has been {0} number plates since {1}".format (numberPlates, timeStart)) speedLimit = 25 distance = 1 class NumberPlates: """A class that holds information from sensor for ANPR system""" distance = 1 def __init__(self, name, enter, exit): self.number = name self.enter = enter self.exit = exit def speed(self): distance = 1 time = exit - enter speed = distance/time print(speed) one = NumberPlates("lemon", 1030, 1050) one.speed() It says there are no arguements Thanks Madeleine -- *Madeleine Austen* *11L* -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.cool at live.se Wed Sep 24 08:07:17 2014 From: martin.cool at live.se (=?iso-8859-1?B?TWFydGluIFNr5XJlYnk=?=) Date: Wed, 24 Sep 2014 08:07:17 +0200 Subject: [Tutor] Trouble with making a chart Message-ID: Hello!So i'm having trouble with a task i got from my teacher in a book. I'm supposed to create a chart which shows the converted numbers between Celsius and Fahrenheit. They want the Celsius to range from 40 to -40. I also get to know that Fahrenheit = 32+celsius*9/5. Now I managed to write the number 40 to -40 from top to bottom. But i'm having trouble converting celsius to fahrenheit and printing it at the same time on the side of celsius. The chart should look something like this:Fahrenheit to Celsius=================Celsius Fahrenheit40 10439 102,238 100,437 98,6etc. etc.My current code is: print("Fahrenheit to Celsius")print("=======================")print("Celsius\t Fahrenheit")for f in range(40,-41,-1): print(f)for c in range(104,-41,-1): print(32 + c * 9 / 5)Now this makes the numbers for Fahrenheit to just add below celsius. How do I make them go to the other side under the text Fahrenheit? I'm doing this in iPython Notebook. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mvg_gautam at yahoo.com Sun Sep 28 11:32:26 2014 From: mvg_gautam at yahoo.com (m.v gautam) Date: Sun, 28 Sep 2014 17:32:26 +0800 Subject: [Tutor] Python Serial Communication Message-ID: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> Hi, I am trying out serial communication between raspberry pi and atmega 32 using pyserial module . I have tried serial communication between two atmega and it is working. But when I try it rpi and atmega I get blank lines as output. My python code is import serial ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10) while True: print "try" val = ser.read(10) print val Output: try try. There is a blank line being printed every time in place of val. The logic level conversion between atmega and rpi has been done perfectly.Can you tell me why 'val' is being printed as blank value. Thanks in advance. Gautam Venkata, SolarMobil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pathunstrom at gmail.com Mon Sep 22 22:10:13 2014 From: pathunstrom at gmail.com (Patrick Thunstrom) Date: Mon, 22 Sep 2014 16:10:13 -0400 Subject: [Tutor] Python advice about API, JSON In-Reply-To: References: Message-ID: On Mon, Sep 22, 2014 at 4:01 PM, Juan Christian wrote: > I'm trying to make my script the more pythonic possible. How would a good > approach regarding external API and json be? I don't think dealing with a specific API is actually appropriate for this list. I'll try to answer the general elements. > I'm calling this API (http://docs.themoviedb.apiary.io/) using 'requests'. > The thing is that I need to do a bunch of different calls to the API: > > - http://api.themoviedb.org/3/person << Receive ID and return person info > - http://api.themoviedb.org/3/tv << Receive ID and return serie info > - http://api.themoviedb.org/3/movie << Receive ID and return movie info > - http://api.themoviedb.org/3/search << Receive "Name of person or serie or > movie" and return ID > > I have the following structures: > > - {query}/{type}?api_key={key}&query={person or tv or movie} > - {query}/{id}?api_key={key} > - {query}/{id}/credits?api_key={key} > - {query}/{id}/season/{season_numer}?api_key={key} > - {query}/{id}/season/{season_numer}/episode/{episode_number}?api_key={key} > - > {query}/{id}/season/{season_numer}/episode/{episode_number}/credits?api_key={key} > > > I'm thinking about creating a class 'API' and have all these URLs and > structures there. The thing is that I need to pass my API_KEY and this key > will be used for everything, so I just need to pass it once, how can I do > that? Yes, I know about class attributes, but the thing is that I will call > this class 'API' from different classes and I'll need to instantiate a API > obj in each of them, is it a good approach? Inside this 'API' class I would > have a __init__ that would receive an API_KEY and different methods, each > for a type of query (person, tv, movie, search, credits). First question: Why do you need multiple versions of this theoretical class floating around? Perhaps if you wrote a single module api that handles interactions with the API, you can then import that module into any other module that will use the API, and you only have to write all of this once. > Maybe my explanation is a bit confusing but I hope you guys understood, > anyway, you can ask for more information if needed! > > And another thing, What's better, a single module with multiple classes > (total lines: ~110) or multiple modules with 1-3 classes (correlated, like > class serie, season and episode in the same module, and class person and > character in the same module) each? I personally prefer multiple modules, though it absolutely depends on the demands of the project. From wdaltonarnold at gmail.com Mon Sep 22 17:16:29 2014 From: wdaltonarnold at gmail.com (itsthewendigo1111 .) Date: Mon, 22 Sep 2014 11:16:29 -0400 Subject: [Tutor] code help Message-ID: I'm taking an online intro to programing class unfortunately the teacher has not be very helpful. well this is the assignment http://burtondsc.pbworks.com/w/file/fetch/84469141/Assignment03.pdf and here is my code so far from tkinter import* master = Tk(); canvas = Canvas(master, width = simpledialog.askinteger("Canvas size", "Enter width of canvas")) canvas = Canvas(master, height = simpledialog.askinteger("Canvas size", "Enter height of canvas")) canvas = Canvas(master, background = simpledialog.askstring("Canvas color", "Enter color for canvas")) canvas.pack() s1 = canvas.create_rectangle(150,300,450,150, width = simpledialog.askinteger('Square size', "Enter side length of square")) s1 = simpledialog.askstring("Square color","Enter color for the square") I'm having trouble with the "width = simpledialog.askinteger". width almost makes like a border and not resize the square. I have tried using size,length, len, scale, but nothing seems to work. I'm also having trouble with getting the square to change color. If u guys could offer any help I would really appreciate it -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 29 13:07:58 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 12:07:58 +0100 Subject: [Tutor] Back from vacation Message-ID: I'm just home from vacation and have flushed the moderation queue so there might be some out of date or repeat messages appearing out of sequence. Apologies, but normal service should now be resumed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 13:51:20 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 12:51:20 +0100 Subject: [Tutor] List and dictionary comprehensions In-Reply-To: References: Message-ID: On 28/09/14 03:36, Armindo Rodrigues wrote: > have noted the beginning and end of the quotes list so you can easily skip > and go straight to the code section. *** It would probably have been better to just delete all but a nfew of the quotes. We don't need all of them to evaluate your code. > import re > from datetime import datetime > import time > > > ################### DATA LIST STARTS HERE > > data_list=["And now here is my secret, a very simple secret: It is only > with the heart that one can see rightly; what is essential is invisible to > the eye.", > "All grown-ups were once children... but only few of them remember it.", ... > "If you love a flower that lives on a star, then it's good at night, to > look up at the sky. All the stars are blossoming."] > > > ################## CODE STARTS HERE > > #Create a list of words taken from each individual word in the datalist > word_list = [] > for item in data_list: > for word in item.split(" "): > word = re.sub('^[^a-zA-z]*|[^a-zA-Z]*$','', word) word.strip() would be better here. You can specify a string of chars to be stripped if its not only whitespace. Consider regular expressions as a weapon of last resort. > word_list.append(word) > word_list = sorted(list(set(word_list))) #Remove repeated words You don't need to convert the set into a list. sorted() works with sets too. > quotesDict = {} > for word in word_list: > quotesDict.setdefault(word,[]) #Create a dictionary with keys based on > each word in the word list By putting the words in the dictionary you lose the sorting you did above. So the sorting was a waste of time. > for key, value in quotesDict.items(): > indexofquote = 0 > for quote in data_list: You should use enumerate for this. It will automatically give you the index and quote and be less error prone than maintaining the index yourself. > if key in quote: > quotesDict[key].append(indexofquote) #Append the index of the > found quotes to the dictionary key > indexofquote+=1 > > query=input("query: ") > query = query.strip(" ").split(" ") > query = list(set(query)) > I don;t think you need the conversion to list here either. You can just use the set. > start_time = time.time() > > FoundQuotes = [] > > # Right now the OR search just prints out the index of the found quotes. > if ("or" in query) and ("and" not in query): The logic here can be simplified by testing for 'and' first if 'and' in query remove 'or' process and elif 'or' in query process 'or' else process simple query > query.remove("or") > print("Performing OR search for: ", query) > for item in query: > if (item in quotesDict): > print("FOUND ",len(quotesDict[item]), " ", item, "QUOTES: ", > quotesDict.get(item)) > print("\n--- Execution ---\n", (time.time() - start_time) * 1000, > "microseconds\n") > > else: > if "and" in query: > query.remove("and") > if "or" in query: > query.remove("or") > print("Performing AND search for: ", query) This looks wrong. What about the case where neither and/or are in the query? > for item in query: > if (item in quotesDict): > FoundQuotes = FoundQuotes + (quotesDict.get(item)) > FoundQuotes = list(set([x for x in FoundQuotes if FoundQuotes.count(x) >> 1])) This doesn't look right either. Foundquotes is a list of indexes. The comprehension builds a list of all the indexes that appear more than once - what about a quote that was only found once? It then eliminates all the duplicates(set()) and returns it back to a list(why not leave it as a set?) I'd have expected a simple conversion of FoundQuotes to a set would be what you wanted. > for x in FoundQuotes: > print(data_list[x]) > print("\n--- Execution ---\n", (time.time() - start_time) * 1000, > "microseconds\n") The other problem is that you are serching the dictionary several times, thus losing some of the speed advantage of using a dictionary. You would get more benefit from the dictionary if you adopt a try/except approach and just access the key directly. So, instead of: > for item in query: > if (item in quotesDict): > FoundQuotes = FoundQuotes + (quotesDict.get(item)) for item in query: try: FoundQuotes = FoundQuotes + quotesDict[item] except KeyError: pass Or better still use the default value of get: for item in query: FoundQuotes = FoundQuotes + quotesDict.get(item,[]) There are a few other things that could be tidied up but that should give you something to get started with. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 13:52:51 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 12:52:51 +0100 Subject: [Tutor] Problem with pythonw.exe In-Reply-To: <027201cfda89$c4780b50$4d6821f0$@gmail.com> References: <027201cfda89$c4780b50$4d6821f0$@gmail.com> Message-ID: On 27/09/14 20:32, Gregory Karakeussian wrote: > My antivirus has uninstalled pythonw.exe by mistake and now I can`t fix it, > deinstall it, reinstall it, I'm stuck.. is there a solution? What happens when you try to reinstall? Turn off the antivirus before doing so of course. Maybe get a new antivirus program too? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 13:58:09 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 12:58:09 +0100 Subject: [Tutor] Python Serial Communication In-Reply-To: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> References: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> Message-ID: On 28/09/14 10:32, m.v gautam wrote: > import serial > ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10) > while True: > print "try" > val = ser.read(10) > print val > There is a blank line being printed every time in place of val. How do you know that val is not a blank line? Remember that a blank line is not necessarily empty, it might be full of unprintable characters. Try this instead: while True: print "try" val = ser.read(10) print 'len: ', len(val) for char in val: print ord(char) That will tell you ow many characters you actually read and what character values are being read. You might find you have and end of file in there or similar. > The logic level conversion between atmega and rpi has been done perfectly. That's a very bold claim. Very little is ever perfect in programming. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 14:08:46 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 13:08:46 +0100 Subject: [Tutor] I've been trying to make this program work so i can transfer it to final user. please do have a look and see if the code can be corrected in anyway. In-Reply-To: <1411732689.20273.YahooMailNeo@web120904.mail.ne1.yahoo.com> References: <1411732689.20273.YahooMailNeo@web120904.mail.ne1.yahoo.com> Message-ID: On 26/09/14 12:58, Brave Heart wrote: > File "C:/Python34/cash.py", line 339, in add_func > os.chdir(sqlite3_path) > FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:/sqlite3/' I assume you have checked that the folder exists? and that you (ie. the user running the program) have permission to go there? > def add_func(dt, ds, at): > '''Insert data into db(L2)''' > sql_insert = """ > INSERT INTO expenses (date, desc, amount) > VALUES ('%s', '%s', '%s') > """ % (dt, ds, at) > > os.chdir(sqlite3_path) > > # open connection to database > try: > cx = sqlite.connect(database) > except sqlite.Error(errmsg): > print ("Can not open ") +str(errmsg) > > # insert data into table > try: > cu = cx.cursor() > cu.execute(sql_insert) > cx.commit() > except sqlite.Error(errmsg): > print ("Can not execute: ") +str(errmsg) > > # close connection > cx.close() BTW Its probably better to set the database to the full path rather than change into the folder for every access of the database. In fact I usually just open the database once at the start of my program. The data functions then only need to create a cursor (in fact I often keep the cursor open too!). That reduces the work in each function and the duplication of code although you could put the open and cursor code into a function called by the other data functions - that would help with maintenance in future. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 14:19:06 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 13:19:06 +0100 Subject: [Tutor] Trouble with making a chart In-Reply-To: References: Message-ID: On 24/09/14 07:07, Martin Sk?reby wrote: > Hello!So i'm having trouble with a task i got from my teacher in a book. I'm supposed to create a chart which shows the converted numbers between Celsius and Fahrenheit. They want the Celsius to range from 40 to -40. I also get to know that Fahrenheit = 32+celsius*9/5. Now I managed to write the number 40 to -40 from top to bottom. But i'm having trouble converting celsius to fahrenheit and printing it at the same time on the side of celsius. The chart should look something like this:Fahrenheit to Celsius=================Celsius Fahrenheit40 10439 102,238 100,437 98,6etc. etc.My current code is: print("Fahrenheit to Celsius")print("=======================")print("Celsius\t Fahrenheit")for f in range(40,-41,-1): print(f)for c in range(104,-41,-1): print(32 + c * 9 / 5)Now this makes the numbers for Fahrenheit to just add below celsius. How do I make them go to the other side under the text Fahrenheit? I'm doing this in iPython Notebook. Please send emails in plain text. Yours has come out as one long line... I'll try to reformat as best I can... > same time on the side of celsius. The chart should look something > like this: > Fahrenheit to Celsius > ================= > Celsius Fahrenheit > 40 104 > 39 102 > current code is: > print("Fahrenheit to Celsius") > print("=======================") > print("Celsius\t Fahrenheit") > for f in range(40,-41,-1): > print(f) > for c in range(104,-41,-1): > print(32 + c * 9 / 5) > Now this makes the numbers for Fahrenheit to just add > below celsius. How do I make them go to the other side The normal way to do this is store the results before trying to print them. Then you can use string formatting to print both figures in a single line. Something like this pseudocode: results = [] for c in range(-41,40): f = (32+c*9/5) results.append( (c,f) ) print headers for result in results: print("{}\t{}".format(result)) The notebook of IPython can do much cleverer things with data but I'll ignore that for now and stick with simple text tables. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Sep 29 14:43:18 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Sep 2014 13:43:18 +0100 Subject: [Tutor] code help In-Reply-To: References: Message-ID: On 22/09/14 16:16, itsthewendigo1111 . wrote: > from tkinter import* > master = Tk(); > > canvas = Canvas(master, width = simpledialog.askinteger("Canvas size", > "Enter width of canvas")) Its generally a bad idea to mix interactivity with widget creation. Better(and much easier to debug) to query the width first then create the widget: w = simpledialog.askinteger("Canvas size", "Enter width of canvas") canvas = Canvas(master, width = w) Then you can print out the value of w or inspect it in a debugging tool. Also you create several canvases but store only the last one in your canvas widget. Is that really what you want? Or do you really want to configure several attributes of the same canvas? Inwhich case use the configure method of the widget: eg: h = simpledialog.... col = simpledialog.... canvas.configure(height=h, color=col) #etc... > s1 = canvas.create_rectangle(150,300,450,150, width = > simpledialog.askinteger('Square size', "Enter side length of square")) > s1 = simpledialog.askstring("Square color","Enter color for the square") Here you have overwritten your square widget variable with the string value. Is that really what you want? > I'm having trouble with the "width = simpledialog.askinteger". width > almost makes like a border and not resize the square. I'm assuming you are referring to the width in the rectangle widget not the width in the canvas. Have you checked the documentation of the square to see what the width parameter does? The size of the rectangle is set by the two points you give it s1 = canvas.create_rectangle(150,300,450,150,... So it starts at (150,300) and ends at (450,150) So its size in pixels is: 150-450 = 300 300-150 = 150 > trouble with getting the square to change color. You need to look at the fill attribute I suspect. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Sep 29 15:15:54 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Sep 2014 23:15:54 +1000 Subject: [Tutor] Python Serial Communication In-Reply-To: References: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> Message-ID: <20140929131554.GR19757@ando.pearwood.info> On Mon, Sep 29, 2014 at 12:58:09PM +0100, Alan Gauld wrote: [...] > How do you know that val is not a blank line? > Remember that a blank line is not necessarily empty, it might be full of > unprintable characters. > > Try this instead: > > while True: > print "try" > val = ser.read(10) > print 'len: ', len(val) > for char in val: > print ord(char) Another way to see invisible control characters is: print repr(val) -- Steven From steve at pearwood.info Mon Sep 29 15:23:14 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Sep 2014 23:23:14 +1000 Subject: [Tutor] Python Serial Communication In-Reply-To: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> References: <1411896746.31608.YahooMailNeo@web190104.mail.sg3.yahoo.com> Message-ID: <20140929132314.GS19757@ando.pearwood.info> On Sun, Sep 28, 2014 at 05:32:26PM +0800, m.v gautam wrote: > Hi, > I am trying out serial communication between raspberry pi and atmega 32 using pyserial module . I have tried serial communication between two atmega and it is working. > But when I try it rpi and atmega I get blank lines as output. My python code is > > import serial > ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10) > while True: > print "try" > val = ser.read(10) > print val According to this Stackoverflow question, you need to use keyword arguments. Try this: val = ser.read(size=10) http://stackoverflow.com/questions/19143360/python-writing-to-and-reading-from-serial-port -- Steven From __peter__ at web.de Mon Sep 29 16:14:51 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Sep 2014 16:14:51 +0200 Subject: [Tutor] List and dictionary comprehensions References: Message-ID: Armindo Rodrigues wrote: > Hi everyone, > > This is my first post so I don't know if I am asking the correct way so > let me know if I messed anything up. > > ***Please note. My code contains a list of quotes that has many lines. I > have noted the beginning and end of the quotes list so you can easily skip > and go straight to the code section. *** > > > This is technically NOT a homework assignment. I am the teaching assistant > for the Python course at my school. The teacher doesn't give me the > homework ahead of time so I typically try the homework myself so I can > help anyone else out that may be confused. The assignment has come and > gone but I want to challenge myself with making this thing more efficient > and learn comprehensions along the way. > > The assignment was as follows: > The teacher provided the class with a list of quotes called data_list. We > were to implement a very simple search algorithm that took in a user's > query and we searched based on those words. If the user entered an OR then > we searched for quotes that contained either of the words. Any other > combination of AND OR will be an AND search. > > Once we completed the search algorithm, the assignment called for > pre-processing that would make the search more efficient and faster. I > created a dictionary based on each word in the quotes list as the key and > then searched against those words. I greatly increased the search time. That is very unlikely. Note that you include the print() calls into your measurement. These will dominate the time you measure, i. e. searches with more matching text will appear to take longer and searches with little or no text will appear to be fast. > MY QUESTION: > Can anyone look at this and explain how I could create a list > comprehension and a dictionary comprehension if possible? I tried to solve the problem myself below -- and did not find a place where list comprehensions would fit in naturally. > Also any > suggestions with making the search faster would be appreciated. As hinted above, your code does not have speed issues; you can simplify and clean it a bit (I stopped halfway), put every separate step into a function with an informative name, avoid global variables, follow the naming conventions of PEP 8 -- and that's it. My most significant modifications: - Use the strings directly instead of indices into the list - Build the word-to-quote lookup directly without the intermediate list of all words. #!/usr/bin/env python3 import re import time from itertools import zip_longest from sys import exit data_list = [...] # won't repeat your data RED = "\033[31m" BLUE = "\033[34m" EMPTY = frozenset() def colored(s, color): # if the coloring attempt messes up your screen # change this to # return s return "%s%s\033[0m" % (color, s) def find(term): return quotes_dict.get(term.lower(), EMPTY) def mark_terms(phrase, terms): def mark(m): return colored(m.group(), RED) expr = r"\b(%s)\b" % "|".join(terms) return re.compile(expr).sub(mark, phrase) def clean(word): return re.sub('^[^a-zA-z]*|[^a-zA-Z]*$', '', word) quotes_dict = {} for item in data_list: for word in item.split(): quotes_dict.setdefault(clean(word), set()).add(item) query = input("query: ") start_time = time.time() query = query.split() if not query: exit("no search term") terms = query[::2] found_quotes = find(query[0]) for operator, term in zip_longest(query[1::2], query[2::2]): if term is None: exit("dangling operator " + operator) operator = operator.lower() if operator == "or": found_quotes |= find(term) elif operator == "and": found_quotes &= find(term) else: print("unknown operator", operator) exit(1) print( "\n--- Execution ---\n", (time.time() - start_time) * 1000, "microseconds\n") for index, quote in enumerate(found_quotes): print(colored("{} >>>".format(index), BLUE), mark_terms(quote, terms)) Note that my handling of the operators does not follow your teacher's spec. It simply `or`s or `and`s the next match to what is in the current set of matches. From davea at davea.name Tue Sep 30 01:12:07 2014 From: davea at davea.name (Dave Angel) Date: Mon, 29 Sep 2014 19:12:07 -0400 (EDT) Subject: [Tutor] python code error References: Message-ID: Madeleine Austen Wrote in message: > > It says there are no arguements I don't see any print functions with such text, so presumably you're paraphrasing an exception traceback. Please quote the entire traceback, as there is usually lots of information there. And use copy/paste, don't attempt to retype it. If I had to guess, I'd say your indentation is the problem. The methods of a class must be indented inside the class. As written, you have defined no methods. Please use text mode in your messages, not html. Frequently indentation is messed up by buggy html. Also, please specify at least the version numbers for Python, your os, and anything else relevant. -- DaveA From dyoo at hashcollision.org Tue Sep 30 01:34:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 29 Sep 2014 16:34:44 -0700 Subject: [Tutor] python code error In-Reply-To: References: Message-ID: On Sun, Sep 28, 2014 at 8:26 AM, Madeleine Austen wrote: > Hi > > Here is my code: > > > from datetime import datetime > timeStart = datetime.now().strftime('%Y-%m-%d %H:%M:%S') > numberPlates = 0 > print("There has been {0} number plates since {1}".format (numberPlates, > timeStart)) > > speedLimit = 25 > distance = 1 > > class NumberPlates: > """A class that holds information from sensor for ANPR system""" > distance = 1 > def __init__(self, name, enter, exit): > self.number = name > self.enter = enter > self.exit = exit > def speed(self): > distance = 1 > time = exit - enter > speed = distance/time > print(speed) > > > one = NumberPlates("lemon", 1030, 1050) > > > one.speed() > > > > > It says there are no arguements Hi Madeleine, Unlike English class, you're not penalized for copying-and-pasting errors for diagnostic, bug tracking purposes. I can tell that you've paraphrased the error in some way because what you report has a spelling mistake that's not present anywhere in the Python source tree. What you've done is somewhat akin to what happened to the poor Ecce Homo painting: http://en.wikipedia.org/wiki/Ecce_Homo_(El%C3%ADas_Garc%C3%ADa_Mart%C3%ADnez) in paraphrasing a perfectly good error message. :P Please include the exact error message. When you do so, copy-and-paste is your friend. When you see the error message, please copy and paste the exact error text. It helps to copy the entire error context if it's not too large. Show the program run. Provide more precise information, and that will help folks here give you good help. Good luck! From vigneshsathiamoorthy at yahoo.com Tue Sep 30 19:03:19 2014 From: vigneshsathiamoorthy at yahoo.com (Vignesh Sathiamoorthy) Date: Tue, 30 Sep 2014 10:03:19 -0700 Subject: [Tutor] python code error In-Reply-To: References: Message-ID: <8B6C529D-D19B-430E-AE08-D32BCD259F99@yahoo.com> You will find the answer here - http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do On Sep 29, 2014, at 4:34 PM, Danny Yoo wrote: > On Sun, Sep 28, 2014 at 8:26 AM, Madeleine Austen > wrote: >> Hi >> >> Here is my code: >> >> >> from datetime import datetime >> timeStart = datetime.now().strftime('%Y-%m-%d %H:%M:%S') >> numberPlates = 0 >> print("There has been {0} number plates since {1}".format (numberPlates, >> timeStart)) >> >> speedLimit = 25 >> distance = 1 >> >> class NumberPlates: >> """A class that holds information from sensor for ANPR system""" >> distance = 1 >> def __init__(self, name, enter, exit): >> self.number = name >> self.enter = enter >> self.exit = exit >> def speed(self): >> distance = 1 >> time = exit - enter >> speed = distance/time >> print(speed) >> >> >> one = NumberPlates("lemon", 1030, 1050) >> >> >> one.speed() >> >> >> >> >> It says there are no arguements > > Hi Madeleine, > > > Unlike English class, you're not penalized for copying-and-pasting > errors for diagnostic, bug tracking purposes. I can tell that you've > paraphrased the error in some way because what you report has a > spelling mistake that's not present anywhere in the Python source > tree. > > What you've done is somewhat akin to what happened to the poor Ecce > Homo painting: > > http://en.wikipedia.org/wiki/Ecce_Homo_(El%C3%ADas_Garc%C3%ADa_Mart%C3%ADnez) > > in paraphrasing a perfectly good error message. :P > > > Please include the exact error message. When you do so, > copy-and-paste is your friend. When you see the error message, please > copy and paste the exact error text. It helps to copy the entire > error context if it's not too large. Show the program run. > > > Provide more precise information, and that will help folks here give > you good help. Good luck! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: