From chaostorm at gmail.com Sat Sep 1 00:54:27 2012 From: chaostorm at gmail.com (Lazar) Date: Fri, 31 Aug 2012 15:54:27 -0700 Subject: [Tutor] Power of Two Function Message-ID: Hello, I'm fairly new to Python and still learning. Can someone please explain to me in what way the following function checks if a number is a power of two? Basically, the second line of code is what I can't really grasp: def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) Thank you, Lazar From rdmoores at gmail.com Sat Sep 1 01:16:40 2012 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 31 Aug 2012 16:16:40 -0700 Subject: [Tutor] Problem caused by installing 2.7.3 In-Reply-To: References: Message-ID: On Fri, Aug 31, 2012 at 10:57 AM, eryksun wrote: > On Fri, Aug 31, 2012 at 12:49 PM, Richard D. Moores wrote: > https://bitbucket.org/vinay.sajip/pylauncher > https://bitbucket.org/vinay.sajip/pylauncher/raw/tip/Doc/launcher.rst Thank you! You solved my problem. Dick From visar.zejnullahu at gmail.com Sat Sep 1 01:17:04 2012 From: visar.zejnullahu at gmail.com (Visar Zejnullahu) Date: Sat, 1 Sep 2012 01:17:04 +0200 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: 2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you check if (num & (num - 1)) == 0. Visar Zejnullahu On Sat, Sep 1, 2012 at 12:54 AM, Lazar wrote: > Hello, > > I'm fairly new to Python and still learning. > > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) > > Thank you, > Lazar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From visar.zejnullahu at gmail.com Sat Sep 1 01:22:28 2012 From: visar.zejnullahu at gmail.com (Visar Zejnullahu) Date: Sat, 1 Sep 2012 01:22:28 +0200 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 You have many useful bit hacks here. Visar Zejnullahu On Sat, Sep 1, 2012 at 1:17 AM, Visar Zejnullahu wrote: > 2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So > if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you > check if (num & (num - 1)) == 0. > > Visar Zejnullahu > > > > On Sat, Sep 1, 2012 at 12:54 AM, Lazar wrote: > >> Hello, >> >> I'm fairly new to Python and still learning. >> >> Can someone please explain to me in what way the following function >> checks if a number is a power of two? Basically, the second line of >> code is what I can't really grasp: >> >> def is_power2(num): >> return num != 0 and ((num & (num - 1)) == 0) >> >> Thank you, >> Lazar >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Sep 1 01:30:42 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 31 Aug 2012 19:30:42 -0400 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: <50414922.3000206@gmail.com> On 8/31/2012 6:54 PM, Lazar wrote: > Hello, > > I'm fairly new to Python and still learning. > > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) A power of 2 in binary is (in general) one followed by zero-or-more zeroes. Thus 2 = 10 4 = 100 8 = 1000 The python manual informs us 5.4.1. Bit-string Operations on Integer Types Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2's complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation). x & y bitwise /and/ of /x/ and /y/ in other words & takes two bit strings, does a boolean and on pairs of bits. Thus 1100 & 1010 = 1000 (you get 1 only where the two bits are 1. for any /integer /n that is a power of 2, n-1 will be a string of all ones length one less than n. Thus given n = 4 (100), n-1 is 11. Attach a leading 0, perform the & and the result will be 0. Thus num & (num - 1)) == 0 will be one only for powers of 2. The function returns 1 or 0 which may be interpreted as True or False by the caller. Why the function does not ensure that its argument is of type int is a problem. HTH. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaostorm at gmail.com Sat Sep 1 01:45:47 2012 From: chaostorm at gmail.com (Lazar) Date: Fri, 31 Aug 2012 16:45:47 -0700 Subject: [Tutor] Power of Two Function In-Reply-To: <50414922.3000206@gmail.com> References: <50414922.3000206@gmail.com> Message-ID: Visar and Bob, Thank you for your detailed explanations, I appreciate your help. Kind regards, Lazar From breamoreboy at yahoo.co.uk Sat Sep 1 01:50:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Sep 2012 00:50:32 +0100 Subject: [Tutor] Problem caused by installing 2.7.3 In-Reply-To: References: Message-ID: On 01/09/2012 00:16, Richard D. Moores wrote: > On Fri, Aug 31, 2012 at 10:57 AM, eryksun wrote: >> On Fri, Aug 31, 2012 at 12:49 PM, Richard D. Moores wrote: > >> https://bitbucket.org/vinay.sajip/pylauncher > >> https://bitbucket.org/vinay.sajip/pylauncher/raw/tip/Doc/launcher.rst > > Thank you! You solved my problem. > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > For the record this is described in PEP 397 and forms part of the Python 3.3 release. -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Sat Sep 1 01:52:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Sep 2012 00:52:15 +0100 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: On 31/08/12 23:54, Lazar wrote: > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) In binary any positive power of 2 looks like 1 followed by zeros: 10, 100, 1000 etc If you subtract 1 from any of those numbers you get a zero followed by all 1s: 01, 011, 0111 etc So if you bitwise and N and N-1 you get 1....0 & 0....1 ---------- 0....0 ie all zeros which equals the decimal number zero. So your function first checks that the argument is not zero if that is true then it evaluates the second part which as we've seen does equal zero for a power of two. Unfortunately it breaks down for fractions like 1/2, 1/4 etc which are negative powers of 2. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 1 01:58:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Sep 2012 00:58:51 +0100 Subject: [Tutor] Using a calling program to change Python script arguments In-Reply-To: <504131EC.7010907@gmail.com> References: <5040EEE8.3020103@gmail.com> <504131EC.7010907@gmail.com> Message-ID: On 31/08/12 22:51, Ray Jones wrote: > Okay. Now I must figure out how to create the module and have my calling > script look in the right place.... ;) Creating a module is just a matter of creating a standard python file <--------start of myvar.py -----> #! /bin/python # you don't even really need a shebang for modules! myVar = 66 <-------- end of myvar.py ------> import myvar print myvar.myVal And so long as the location of the module is in your sys.path (or in the PYHONPATH environment variable) python will find it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Sep 1 02:20:42 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 01 Sep 2012 10:20:42 +1000 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> Message-ID: <504154DA.1070306@pearwood.info> On 31/08/12 18:31, Mark Lawrence wrote: > On 31/08/2012 04:27, William R. Wing (Bill Wing) wrote: >> >> How about - >> >>>>> for item in iter(list): >>>>> ?.print item > > Overengineering? :) A list is an iterator. Technically, no it isn't, it is an "iterable" or a "sequence" but not an iterator. py> mylist = [1, 2, 3] py> next(mylist) Traceback (most recent call last): File "", line 1, in TypeError: list object is not an iterator You are right to question the call to iter, it is redundant in this case, but your terminology is mixed up. There are three terms normally used to describe things that can be used in for-loops: Sequence The generalisation of lists, tuples and strings. Any object that has a known length where individual items can be retrieved with the __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... Iterator Any object that obeys the "iterator protocol", that is, it must have a method __iter__ which returns itself, and a method __next__ which returns the iterator items one at a time, then raises StopIteration when there are no more items. Examples of iterators include generator expressions, generators, the functions from the itertools module, and in Python 3, built-ins map, filter and zip. Iterable Any object which can be iterated over, that is, a sequence or iterator. The iter() built-in calls the object's __iter__ method. If the object is already an iterator, it returns itself unchanged. Since lists are not iterators, iter(list) returns a new iterator object: py> it = iter(mylist) py> it py> iter(it) is it True -- Steven From crawlzone at gmail.com Sat Sep 1 02:23:55 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 31 Aug 2012 17:23:55 -0700 Subject: [Tutor] Using a calling program to change Python script arguments In-Reply-To: References: <5040EEE8.3020103@gmail.com> <504131EC.7010907@gmail.com> Message-ID: <5041559B.2070804@gmail.com> On 08/31/2012 04:58 PM, Alan Gauld wrote: > > Creating a module is just a matter of creating a standard python file > > <--------start of myvar.py -----> > #! /bin/python # you don't even really need a shebang for modules! > myVar = 66 > <-------- end of myvar.py ------> > > import myvar > print myvar.myVal > > > And so long as the location of the module is in your sys.path > (or in the PYHONPATH environment variable) python will find it. Yep. I got my 'pymodules' directory created, and I will append it to the sys.path list a run time. So far it appears to work in testing mode....next we'll see what happens in real life! Thanks. Ray From etanes.rm at gmail.com Sat Sep 1 03:08:41 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 31 Aug 2012 18:08:41 -0700 Subject: [Tutor] List all possible 10digit number Message-ID: First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like For I in range(1000000000, 9999999999): Print I Without crashing or throwing an exception. I've also tried to do something like I in range (100, 900): Etc And then concatenate the results but also to no avail. Again, any shoves in the right direction would be greatly appreciated. Scott From eryksun at gmail.com Sat Sep 1 03:46:33 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 31 Aug 2012 21:46:33 -0400 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: <504154DA.1070306@pearwood.info> References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> <504154DA.1070306@pearwood.info> Message-ID: On Fri, Aug 31, 2012 at 8:20 PM, Steven D'Aprano wrote: > > Sequence > The generalisation of lists, tuples and strings. Any object that has > a known length where individual items can be retrieved with the > __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... To expand on this, any object that has a __getitem__ method can be iterated over until it raises an IndexError, not just object's that have an __iter__ method, and __len__ is not a factor. For example: class Test(object): def __getitem__(self, n): if n > 4: raise IndexError return 'test' >>> list(Test()) ['test', 'test', 'test', 'test', 'test'] From d at davea.name Sat Sep 1 04:01:01 2012 From: d at davea.name (Dave Angel) Date: Fri, 31 Aug 2012 22:01:01 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: <50416C5D.1080101@davea.name> On 08/31/2012 09:08 PM, Scurvy Scott wrote: > First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. > > My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list > > List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like > > For I in range(1000000000, 9999999999): > Print I > > Without crashing or throwing an exception. > > I've also tried to do something like > > I in range (100, 900): > Etc > And then concatenate the results but also to no avail. > > Again, any shoves in the right direction would be greatly appreciated. > You should have mentioned that you're using Python 2.x. (Things are different in 3.x ) The range() function is the wrong answer, since 9 billion integers aren't going to fit in memory, on most machines. You should at least have tried xrange(). Unfortunately, it's limited to ints, which only go to a couple billion. That's probably why your assignment specifies 10 digits. The easy answer is to do a while loop that's equivalent to the xrange(). Initialize your counter to the smallest value you're interested in, and each time through the loop, print the counter and increment it. The loop should terminate when you pass the highest value of interest. The "right" answer is to write a generator, using yield to yield each value. Interestingly, it's the same loop as previous, but it yields instead of prints. Then, once you have the generator, you write a loop using it, rather than xrange. -- DaveA From eryksun at gmail.com Sat Sep 1 05:42:42 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 31 Aug 2012 23:42:42 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: On Fri, Aug 31, 2012 at 9:08 PM, Scurvy Scott wrote: > > My question is this- I've been trying for a month to generate a list of > all possible 10 digit numbers. I've googled, looked on stackoverflow, > experimented with itertools, In itertools, look at count() and islice(). An alternative to islice in this case is takewhile(). count() works with Python long integers. For example, counter = count(start=10**9L). islice() is limited to sys.maxint (sys.maxsize in Python 3), so you need to chain several together on a 32-bit platform (also 64-bit Windows, I gather, since a C long is always 32-bit on Windows). Use a generator expression with chain.from_iterable: counter = count(start=10**9L) slices = (islice(counter, 10**9) for i in range(10)) nums = chain.from_iterable(slices) Since printing performance is limited by the terminal's speed, you probably don't need the efficiency of islice (with its machine word size limit). Instead, you can use takewhile() with a pure Python predicate. For example: counter = count(start=10**9L) nums = takewhile(lambda x: x < 10**10, counter) From d at davea.name Sat Sep 1 07:00:10 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:00:10 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: <5041965A.60409@davea.name> On 08/31/2012 10:14 PM, Scurvy Scott wrote: > Thanks for the reply. This isn't an assignment per se as I'm just learning python for my own sake- not in classes or school or what have you. As I said I'm pretty new to python picking up whatever I can and generators are something that I haven't grasped. They're functions(kinda) that in some way deal with lists, tuples, or dict,(kinda?). I am probably wrong on this. Some clarification would be excellent. > > Thank you in advance and I apologize for being not so sharp sometimes. > > You seem plenty sharp enough to me. I do have to point out a couple of list etiquette points: 1) You top-posted. That means you put your message BEFORE the part you're quoting. Once a few replies go back and forth, this thoroughly scrambles the order, so you might as well delete all the context. 2) You replied privately to me. I've been participating in public forums like this for over 20 years, and the key word is "public." The only messages to send privately are thank-yous, and ones with personal information in them, such as passwords and such. Instead you should reply-all, and if your email is too broken to offer that, add the cc of tutor at python.org A simple generator could be def bigrange(start, end): i = start while i < end: yield i i += 1 The yield is a little like a return, in that the "caller" gets the value. But the function stack is kept active, and next time the loop needs a value, it resumes the same function. Control gets batted back and forth between the loop code and the generator code, until the generator finally returns. In this case it returns when it reaches the end value. So it'd be used like: for x in bigrange(100, 1000): print x I do hope you've been testing with smaller numbers than 10**10, to make sure the loops you write really do start and end with reasonable results. > I = 1000000000 > While I < 9999999999: > Print I > Is that more like it? -- Did you try running it? You never increment I, so it'll repeat forever on the one value. > I meant; > > I = 1000000000 > While I < 9999999999: > I += 1 > Print I > > > But that doesn't work. Want to explain what about it doesn't work? That phrase could mean that you got an error (post traceback), or it ran forever, or it displayed roman numerals. The only problem I see is it starts one-too-high. Fix that by swapping the last two lines. > Apologies for not mentioning I'm on 2.x.x I've seen so much about > avoiding 3.x I just thought it was assumed. And I've seen so much about avoiding 2.x that i figured 3.x would be assumed. Best to be explicit: python version, operating system, etc. DaveA From d at davea.name Sat Sep 1 07:14:14 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:14:14 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: <504199A6.3050900@davea.name> On 08/31/2012 10:38 PM, Scurvy Scott wrote: > Now I've got > > A = 1000000000 > I = raw_input("file name> ") > TheFile = open(I, 'w') > > TheFile.truncate > def allten(a): > while a < 9999999999: > a = + 1 > TheFile.write(a) > allten(a) > > The result is: > Open file 'file.txt', mode w at 0xb7331ee8 > Traceback line 13 etc.... > Top-posted again. You stop the traceback before showing anything interesting. i don't see 13 lines, so I have to totally guess which line is getting the error, and also what error it's getting. Paste the code and the traceback directly, and if that means you have to get email working on whatever machine you're running Python on, then do so. Retyping on your iphone isn't productive for anyone. There are a pile of typos in that code. Are they just because you retyped, or is that really what you tried? 1) TheFile.truncate doesn't call anything. The line is useless without parentheses. Of course, that doesn't matter much, since the open already truncated it. 2) allien(a) There's no such variable as 'a' defined. you do have one called A 3) write() takes a string. You're passing it an int or long. Convert with the str function, or other method, depending on what you really want. 4) Once you fix #2 and #3, the first value you write will be 10000001 That's off by one. As i said in my last message, you should swap the two lines. And once you do, you'll end one value too low. As I also said there, you should test the loop with smaller numbers. -- DaveA From dwightdhutto at gmail.com Sat Sep 1 07:20:38 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:20:38 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <50416C5D.1080101@davea.name> References: <50416C5D.1080101@davea.name> Message-ID: Dear Scurvy, I don't know if this has been suggested yet, but I just broke the larger list of 10 digit nums into segments, and at the end of the loop, kept the previous last num in the segment as the beginning of the next range() that goes through the same amount of ints in each segmentation of the larger list to iterate through. Except the next list of ints is starting where the last set segmentation of possible length int segments ends, and keeps iterating through all possible nums until it hits a match high_num. The following goes through 10,000 element lists until it hits a target high_num, which in this case is 1,000,000. def iterToHighNum(increment,high_num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: #print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Sep 1 07:20:55 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 1 Sep 2012 01:20:55 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: On Sat, Sep 1, 2012 at 12:29 AM, Scurvy Scott wrote: > > The while loop works for simply printing. Now I'm trying to save to a file > > I = 1000000000 > Boogers = raw_input("file") > Baseball = open(Boogers) As ASCII, that's 11 bytes per number times 9 billion numbers. That's approximately 92 GiB (about 21 DVD-5 discs). Are you sure you want to do that? Minor correction: >> counter = count(start=10**9L) >> slices = (islice(counter, 10**9) for i in range(10)) >> nums = chain.from_iterable(slices) That should have been range(9), not range(10). From dwightdhutto at gmail.com Sat Sep 1 07:24:14 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:24:14 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: You can also watch this happen by uncommenting print on line 8: def iterToHighNum(increment,high_ num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:26:39 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:26:39 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: I mean line 7. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:31:17 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:31:17 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: It might be a little buggy, but I'm in a rush, so it has a flaw in it. But I think you get the point I'm trying to make. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:46:24 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:46:24 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: Here's the better function fixed with a return statement I forgot, but might not be as quick as the pre-built functions already shown: def iterToHighNum(increment,high_num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) return previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Sep 1 07:55:49 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:55:49 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: <5041A365.207@davea.name> On 09/01/2012 01:46 AM, Dwight Hutto wrote: > Here's the better function fixed with a return statement I forgot, but > might not be as quick as the pre-built functions already shown: > > def iterToHighNum(increment,high_num): > end_point = 0 > a = [i for i in range(0,increment)] > while (end_point != high_num) == True: > for integer in a: > if integer != high_num: > print "no match, integer = %i" % (integer) > end_point += 1 > if end_point == high_num and integer != (high_num - 1): > print 'match, integer = %i, high_num = %i' % > (integer,high_num) > return > > previous_increment = increment > increment += increment > a = [i for i in range(previous_increment,increment)] > > #instance > increment = 10000 > high_num = 1000000 > iterToHighNum(increment,high_num) > > I'm not sure what the point of any of that is; you're making a simple problem complex. If you're wanting to accomplish the task without using any of the itertools stuff, why not just: current = 10**9 lim = 10**10 while current < lim: print current #or write to file, or whatever current += 1 -- DaveA From dwightdhutto at gmail.com Sat Sep 1 08:00:00 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 02:00:00 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041A365.207@davea.name> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> <5041A365.207@davea.name> Message-ID: I could comment this better. We have a function, iterToHighNum, that takes two parameters: increment and high_num. increment is how long the list of numbers being added to the old increment list of ints, to create a shorter int list that maintains the sequential count, looking for the high number you're trying to reach. I guess this is a benchmark thing, not sure, so if you comment out(#) the print 'no match' function in line 7, it will run quicker. end_point increments as a boolean, to match the high_num. When that happens, an if occurs, the match is printed, and the function returns to the instance caller. Use the other posters suggestions if they are better suited for you, however, I'd read what those functions do to give a more experienced lesson in how the 'experts' would code it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 08:12:36 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 02:12:36 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041A365.207@davea.name> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> <5041A365.207@davea.name> Message-ID: I'm not sure what the point of any of that is; you're making a simple > problem complex. If you're wanting to accomplish the task without using > any of the itertools stuff, why not just: > > > current = 10**9 > lim = 10**10 > while current < lim: > print current #or write to file, or whatever > current += 1 > > Rough draft, in a hurry to try and help, and would have gotten a little more zen elegance if it were for a client. Plus the OP stated he needed a list. What's that list of ints for? Unless this is benchmarking, they might be in need of an unordered list of ints in which there are 10**9 different random values that need to have the proverbial needle(or 2, or 3) in a hey stack found. I thought there might be a reason, hopefully, other than trying to find the max range you could count to. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Sep 1 09:18:03 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 03:18:03 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: <5041B6AB.4090108@davea.name> On 08/31/2012 09:08 PM, Scurvy Scott wrote: > First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. > > My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list > > List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like > > For I in range(1000000000, 9999999999): > Print I > > Without crashing or throwing an exception. > > I've also tried to do something like > > I in range (100, 900): > Etc > And then concatenate the results but also to no avail. > > Again, any shoves in the right direction would be greatly appreciated. > > Scott for i in xrange(start, end): print i Somehow i missed the point that xrange() is NOT necessarily limited to Python int values. So it may be usable on your machine, if your Python is 64bit. All I really know is that it works on mine (2.7 64bit, on Linux). See the following quote from http://docs.python.org/library/functions.html#xrange *CPython implementation detail:*xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (?short? Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using theitertools module:islice(count(start,step),(stop-start+step-1+2*(step<0))//step). Anyway, if you're not sure that xrange() will work for your particular range of values, then use current = 10**9 lim = 10**10 while current < lim: print current #or write to file, or whatever current += 1 or use the combination of islice and count listed above. -- DaveA From breamoreboy at yahoo.co.uk Sat Sep 1 10:52:10 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Sep 2012 09:52:10 +0100 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: <504154DA.1070306@pearwood.info> References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> <504154DA.1070306@pearwood.info> Message-ID: On 01/09/2012 01:20, Steven D'Aprano wrote: > On 31/08/12 18:31, Mark Lawrence wrote: >> On 31/08/2012 04:27, William R. Wing (Bill Wing) wrote: >>> >>> How about - >>> >>>>>> for item in iter(list): >>>>>> ?.print item >> >> Overengineering? :) A list is an iterator. > > > Technically, no it isn't, it is an "iterable" or a "sequence" but > not an iterator. > > py> mylist = [1, 2, 3] > py> next(mylist) > Traceback (most recent call last): > File "", line 1, in > TypeError: list object is not an iterator > > > > You are right to question the call to iter, it is redundant in this > case, but your terminology is mixed up. > > There are three terms normally used to describe things that can > be used in for-loops: > > Sequence > The generalisation of lists, tuples and strings. Any object that has > a known length where individual items can be retrieved with the > __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... > > Iterator > Any object that obeys the "iterator protocol", that is, it must have > a method __iter__ which returns itself, and a method __next__ which > returns the iterator items one at a time, then raises StopIteration > when there are no more items. Examples of iterators include generator > expressions, generators, the functions from the itertools module, > and in Python 3, built-ins map, filter and zip. > > Iterable > Any object which can be iterated over, that is, a sequence or > iterator. > > > The iter() built-in calls the object's __iter__ method. If the object > is already an iterator, it returns itself unchanged. Since lists are > not iterators, iter(list) returns a new iterator object: > > py> it = iter(mylist) > py> it > > py> iter(it) is it > True > > > I thought that when I wrote it, but left it on the grounds that I was too lazy to look up the correct terminology and I figured you'd soon correct me :) -- Cheers. Mark Lawrence. From eryksun at gmail.com Sat Sep 1 11:08:50 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 1 Sep 2012 05:08:50 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041B6AB.4090108@davea.name> References: <5041B6AB.4090108@davea.name> Message-ID: On Sat, Sep 1, 2012 at 3:18 AM, Dave Angel wrote: > > Somehow i missed the point that xrange() is NOT necessarily limited to > Python int values. So it may be usable on your machine, if your Python > is 64bit. All I really know is that it works on mine (2.7 64bit, on > Linux). See the following quote Since xrange uses a C long type, it's limited to sys.maxint. On a 64-bit Linux system a C long is 64-bit. In Windows, a C long is always 32-bit, so I would suppose sys.maxint is 2**31 - 1 on both 32-bit and 64-bit systems. Someone running 64-bit Windows can confirm that. > islice(count(start,step),(stop-start+step-1+2*(step<0))//step) Or more commonly with step==1: islice(count(start), stop - start) This works so long as the 2nd argument is less than sys.maxsize. On my 32-bit system, that's limited to 2**31 - 1. So instead I decided to slice a billion numbers at a time and use chain.from_iterable() to chain several slices from a generator expression. Previously I thought it had to be less than sys.maxint. The error on my 32-bit Debian system said the value had to be <= maxint, so I assumed islice uses a C long type. But I looked in the itertoolsmodule.c source (2.7.3) and discovered that islice uses a C ssize_t. So the error should have said the size has to be <= maxsize. On a 64-bit platform that's 2**63 - 1, even on 64-bit Windows. Again, someone running 64-bit Windows can confirm that. From wayne at waynewerner.com Sat Sep 1 14:54:56 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 1 Sep 2012 07:54:56 -0500 (CDT) Subject: [Tutor] Why begin a function name with an underscore In-Reply-To: <503E4526.2050408@pearwood.info> References: <503E4526.2050408@pearwood.info> Message-ID: On Thu, 30 Aug 2012, Steven D'Aprano wrote: > On 28/08/12 21:24, Wayne Werner wrote: >> On Mon, 27 Aug 2012, Richard D. Moores wrote: > >>> What the best way to test if something's an integer? >> >> try: >> whatever_you_want(supposed_integer) >> except ValueError: >> print("Oops, that wasn't an integer! Please try again") >> >> That's usually the best way... > > Actually, that's close to the worst way, since you take a nice, useful > exception which prints a traceback showing exactly what went wrong, and > replace it with a pointless, silly message which can't be caught by the > caller. > > Trying again may be impossible, or inappropriate, and certainly isn't > up to the function to make that decision, that's up to the caller to > decide what is the appropriate response to invalid data. I suppose I should've replaced the print() call with # Whatever recovery/handling code you need here My intention was to remove the bit about checking for an integer away from the spot that was checking it, out into an exception handler where it belongs. I was also under the (mistaken?) impression that the use case was an interactive type call, and used something like: supposed_integer = raw_input("Please enter an integer: ") # exception handling here But yes, if you're writing code that is meant to be called by someone else then that code is horrible, and exactly the wrong pattern to follow. -Wayne From wayne at waynewerner.com Sat Sep 1 15:14:53 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 1 Sep 2012 08:14:53 -0500 (CDT) Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Thu, 30 Aug 2012, Abhishek Pratap wrote: > Hi Guys > > I have a with few million lines. I want to process each block of 8 > lines and from my estimate my job is not IO bound. In other words it > takes a lot more time to do the computation than it would take for > simply reading the file. > > I am wondering how can I go about reading data from this at a faster > pace and then farm out the jobs to worker function using > multiprocessing module. > > I can think of two ways. > > 1. split the split and read it in parallel(dint work well for me ) > primarily because I dont know how to read a file in parallel > efficiently. > 2. keep reading the file sequentially into a buffer of some size and > farm out a chunks of the data through multiprocessing. As other folks have mentioned, having at least your general algorithm available would make things a lot better. But here's another way that you could iterate over the file if you know exactly how many you have available (or at least a number that it's divisible by): with open('inputfile') as f: for line1, line2, line3, line4 in zip(f,f,f,f): # do your processing here The caveat to this is that if your lines aren't evenly divisible by 4 then you'll loose the last count % 4 lines. The reason that this can work is because zip() combines several sequences and returns a new iterator. In this case it's combining the file handles f, which are themselves iterators. So each successive call to next() - i.e. pass through the for loop - next() is successively called on f. The problem of course is that when you reach the end of the file - say your last pass through and you've only got one line left. Well, when zip's iterator calls next on the first `f`, that returns the last line. But since f is now at the end of the file, calling next on it will raise StopIteration, which will end your loop without actually processing anything on the inside! So, this probably isn't the best way to handle your issue, but maybe it is! HTH, Wayne From mjolewis at gmail.com Sun Sep 2 05:29:35 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 1 Sep 2012 20:29:35 -0700 Subject: [Tutor] Running a script in the background Message-ID: Hi everyone, I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. Thanks! -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From dalupus at gmail.com Sun Sep 2 05:38:41 2012 From: dalupus at gmail.com (Michael Crawford) Date: Sat, 1 Sep 2012 23:38:41 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> For windows not sure but for osx just add an & after the command. python myscript.py & On Sep 1, 2012, at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. > > I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. > > Thanks! > > -- > Michael J. Lewis > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Sun Sep 2 06:00:07 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 1 Sep 2012 21:00:07 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: > For windows not sure but for osx just add an & after the command. > > python myscript.py & > Thanks, but I know about that. I should have been more clear. What I want to do is have the script run in the background without even seeing the terminal. Adding the & after the command will let do other things, but the terminal still needs to be open. Once the program is running, I don't want either the terminal or the interpreter displayed. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From illusiontechniques at gmail.com Sun Sep 2 06:12:37 2012 From: illusiontechniques at gmail.com (c smith) Date: Sun, 2 Sep 2012 00:12:37 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: You are thinking of && & is what you want -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sun Sep 2 06:28:25 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 2 Sep 2012 00:28:25 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: On Sat, Sep 1, 2012 at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding > the subject, but I've spent the past two days trying to figure this out and > I don't get it. > > I have a script that will run forever > Forever is a very loose term. > . Since it runs forever, I don't want to see the interpreter or command > line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every > x minutes to see if any files have been updated and then moves them to > dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If > need be, I can create two separate scripts to separate out the two OS's. > > I haven't tested this yet. I was about to use this instead of a cron job for autoresponders. In my limited knowledge in this area, I'd think that calling the script in startup/boot like this describes: http://embraceubuntu.com/2005/09/07/adding-a-startup-script-to-be-run-at-bootup/ might help. Or maybe a tkinter/wxpython app, that hides itself continuously, buit there might still be a launched icon on the app bar your OS should have. I haven't used OSX Mountain Lion, yet. I like looking at different OS setups. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sun Sep 2 06:35:52 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 2 Sep 2012 00:35:52 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: Here's a little more reading for you, found under google search term 'no terminal python script' http://stackoverflow.com/questions/2338951/how-can-i-run-a-py2exe-program-in-windows-without-the-terminal http://ginstrom.com/scribbles/2007/09/12/running-a-python-script-on-windows-without-the-console/ > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Sun Sep 2 07:44:48 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sat, 01 Sep 2012 22:44:48 -0700 Subject: [Tutor] 2.7.3 generator objects Message-ID: <5042F250.4070200@gmail.com> I was playing with os.walk today. I can use os.walk in a for loop (does that make it an iterator or just an irritable? ^_^), but if I assign os.walk to 'test' (test = os.walk()), that variable becomes a generator object that does not work in a for loop. From what I can tell, it's supposed to work in a generator function using 'yield', but I'm at a loss at how that all works. I suppose I should just stick with using the os.walk in the for loop, but I'd like to make sense of the whole thing. Please someone explain this to me? Thanks. Ray From eryksun at gmail.com Sun Sep 2 07:48:31 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 01:48:31 -0400 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Sat, Sep 1, 2012 at 9:14 AM, Wayne Werner wrote: > > with open('inputfile') as f: > for line1, line2, line3, line4 in zip(f,f,f,f): > # do your processing here Use itertools.izip_longest (zip_longest in 3.x) for this. Items in the final batch are set to fillvalue (defaults to None) if the iterator has reached the end of the file. Below I've included a template that uses a multiprocessing.Pool, but only if there are cores available. On a single-core system it falls back to using itertools.imap (use built-in map in 3.x). from multiprocessing import Pool, cpu_count from itertools import izip_longest, imap FILE_IN = '...' FILE_OUT = '...' NLINES = 1000000 # estimate this for a good chunk_size BATCH_SIZE = 8 def func(batch): """ test func """ import os, time time.sleep(0.001) return "%d: %s\n" % (os.getpid(), repr(batch)) if __name__ == '__main__': # <-- required for Windows file_in, file_out = open(FILE_IN), open(FILE_OUT, 'w') nworkers = cpu_count() - 1 with file_in, file_out: batches = izip_longest(* [file_in] * BATCH_SIZE) if nworkers > 0: pool = Pool(nworkers) chunk_size = NLINES // BATCH_SIZE // nworkers result = pool.imap(func, batches, chunk_size) else: result = imap(func, batches) file_out.writelines(result) From alan.gauld at btinternet.com Sun Sep 2 08:34:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:34:05 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: On 02/09/12 04:29, Michael Lewis wrote: > I have a script that will run forever. Since it runs forever, I don't > want to see the interpreter or command line. I want the program to run > in the background so I don't see it at all. That's an OS thing not a Python thing. On Unix it means adding an entry in the startup scripts. For an old BSD type like me that was one of the init scripts in the /etc tree but nowadays there are different mechanisms, and I'm especially unclear on how MacOS/Darwin starts up. You'll need to do some Googling. On windows you can just put it into the Run registry entry under the appropriate key. Again search the Microsoft help system for the answers. > How can I do this? For some background, my script essentially check > every x minutes to see if any files have been updated and then moves > them to dropbox. In that case using a long running Python script is probably the wrong answer. You would be better with a short running, do it once, script that the OS launches regularly. Look at 'cron' on *nix and 'at' on Windows. That will be less resource hungry, there is no point in having running programs that do nothing for most of the time. > ... I can create two separate scripts to separate out the two OS's. One of the beauties of Python is that you rarely need separate scripts. Put the file location(s) in a config file and the same script will work for both. Only the startup mechanism will differ. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 2 08:39:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:39:28 +0100 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5042F250.4070200@gmail.com> References: <5042F250.4070200@gmail.com> Message-ID: On 02/09/12 06:44, Ray Jones wrote: > I was playing with os.walk today. I can use os.walk in a for loop (does > that make it an iterator or just an irritable? ^_^), but if I assign > os.walk to 'test' (test = os.walk()), that variable becomes a > generator object that does not work in a for loop. It does for me.... >>> home = os.walk('/home/alang/src/Python') >>> for root,dirs,files in home: ... print root ... /home/alang/src/Python /home/alang/src/Python/modcopy /home/alang/src/Python/modcopy/src >>> What happened when you tried? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 2 08:41:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:41:51 +0100 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On 02/09/12 06:48, eryksun wrote: > > from multiprocessing import Pool, cpu_count > from itertools import izip_longest, imap > > FILE_IN = '...' > FILE_OUT = '...' > > NLINES = 1000000 # estimate this for a good chunk_size > BATCH_SIZE = 8 > > def func(batch): > """ test func """ > import os, time > time.sleep(0.001) > return "%d: %s\n" % (os.getpid(), repr(batch)) > > if __name__ == '__main__': # <-- required for Windows Why? What difference does that make in Windows? > file_in, file_out = open(FILE_IN), open(FILE_OUT, 'w') > nworkers = cpu_count() - 1 > > with file_in, file_out: > batches = izip_longest(* [file_in] * BATCH_SIZE) > if nworkers > 0: > pool = Pool(nworkers) > chunk_size = NLINES // BATCH_SIZE // nworkers > result = pool.imap(func, batches, chunk_size) > else: > result = imap(func, batches) > file_out.writelines(result) just curious. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Sun Sep 2 08:55:15 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sat, 01 Sep 2012 23:55:15 -0700 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: References: <5042F250.4070200@gmail.com> Message-ID: <504302D3.6060600@gmail.com> On 09/01/2012 11:39 PM, Alan Gauld wrote: > On 02/09/12 06:44, Ray Jones wrote: >> I was playing with os.walk today. I can use os.walk in a for loop (does >> that make it an iterator or just an irritable? ^_^), but if I assign >> os.walk to 'test' (test = os.walk()), that variable becomes a >> generator object that does not work in a for loop. > > > It does for me.... > > >>> home = os.walk('/home/alang/src/Python') > >>> for root,dirs,files in home: > ... print root > ... > /home/alang/src/Python > /home/alang/src/Python/modcopy > /home/alang/src/Python/modcopy/src > >>> > > What happened when you tried? I'll be dipped. It worked - the first time, anyway. It wouldn't go a second round. Don't I have to reset the object somehow? When I originally tried it, I placed print root print dirs print files within the for loop, and I ended up with nuthin'. Or perhaps it flashed by while I wasn't watching, and it wouldn't do it a second time??? Ray From eryksun at gmail.com Sun Sep 2 08:57:09 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 02:57:09 -0400 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5042F250.4070200@gmail.com> References: <5042F250.4070200@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 1:44 AM, Ray Jones wrote: > > I was playing with os.walk today. I can use os.walk in a for loop (does > that make it an iterator or just an irritable? ^_^), The output from os.walk is a generator, which is an iterator. os.walk actually calls itself recursively, creating a chain of generators. Take a look: print inspect.getsource(os.walk) > os.walk to 'test' (test = os.walk()), that variable becomes a > generator object that does not work in a for loop. You'll have to provide more information. That should work fine if you haven't already exhausted the generator. > it's supposed to work in a generator function using 'yield', but I'm at > a loss at how that all works. > > I suppose I should just stick with using the os.walk in the for loop, > but I'd like to make sense of the whole thing. Please someone explain > this to me? A generator function is a function that uses the keyword "yield" instead of "return" (an empty return statement is allowed). When you call a generator function, the return value is a generator object. Think of the generator function as a factory for generator objects. A return in the generator function (implicit or with a "return" statement) corresponds to the generator object raising StopIteration. A generator object is an iterator. Specifically, it has the methods __iter__ and "next" (in 3.x it's __next__), and "iter(genobject) is genobject". To be an iterable in general, it suffices to have either an __iter__ method or a __getitem__ method. Here are the glossary definitions: http://docs.python.org/glossary.html#term-iterable http://docs.python.org/glossary.html#term-iterator Also, here is the PEP for simple generators: http://www.python.org/dev/peps/pep-0255/ From crawlzone at gmail.com Sun Sep 2 09:09:51 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 00:09:51 -0700 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: References: <5042F250.4070200@gmail.com> Message-ID: <5043063F.7010404@gmail.com> On 09/01/2012 11:57 PM, eryksun wrote: > To be an iterable in general, it suffices to have either an __iter__ > method or a __getitem__ method. Here are the glossary definitions: > http://docs.python.org/glossary.html#term-iterable > http://docs.python.org/glossary.html#term-iterator After a few times re-reading, I'm beginning to get a glimmer.... > Also, here is the PEP for simple generators: > http://www.python.org/dev/peps/pep-0255/ ....but this is complete Greek! ;) But didn't I read somewhere that you can reset an iterator to go through the whole process again? Ray From eryksun at gmail.com Sun Sep 2 09:16:26 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 03:16:26 -0400 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Sun, Sep 2, 2012 at 2:41 AM, Alan Gauld wrote: > >> if __name__ == '__main__': # <-- required for Windows > > Why? > What difference does that make in Windows? It's a hack to get around the fact that Win32 doesn't fork(). Windows calls CreateProcess(), which loads a fresh interpreter. multiprocessing then loads the module under a different name (i.e. not '__main__'). Otherwise another processing Pool would be created, etc, etc. This is also why you can't share global data in Windows. A forked process in Linux uses copy on write, so you can load a large block of data before calling fork() and share it. In Windows the module is executed separately for each process, so each has its own copy. To share data in Windows, I think the fastest option is to use a ctypes shared Array. The example I wrote is just using the default Pool setup that serializes (pickle) over pipes. FYI, the Win32 API imposes the requirement to use CreateProcess(). The native NT kernel has no problem forking (e.g. for the POSIX subsystem). I haven't looked closely enough to know why they didn't implement fork() in Win32. From eryksun at gmail.com Sun Sep 2 09:34:21 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 03:34:21 -0400 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5043063F.7010404@gmail.com> References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 3:09 AM, Ray Jones wrote: > > But didn't I read somewhere that you can reset an iterator to go through > the whole process again? You could implement that ability in your own objects, but it's not part of the protocol. I forgot to mention generator expressions. This is an expression (typically requiring parentheses) that evaluates to a generator object. You can omit the parentheses if it's the only argument in a call. For example: >>> g = (chr(i) for i in range(65, 69)) >>> ", ".join(g) 'A, B, C, D' >>> ", ".join(chr(i) for i in range(65, 69)) 'A, B, C, D' http://docs.python.org/glossary.html#generator%20expression From steve at pearwood.info Sun Sep 2 12:05:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 02 Sep 2012 20:05:40 +1000 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5043063F.7010404@gmail.com> References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> Message-ID: <50432F74.3030905@pearwood.info> On 02/09/12 17:09, Ray Jones wrote: > But didn't I read somewhere that you can reset an iterator to go through > the whole process again? In general, no. The usual way to "reset" an iterator is to re-create it. walker = os.walk("/home/steve/start") # ... process files in walker walker = os.walk("/home/steve/start") # ... and process them again -- Steven From fomcl at yahoo.com Sun Sep 2 13:30:45 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 2 Sep 2012 04:30:45 -0700 (PDT) Subject: [Tutor] making len() and __len__ return a non-int Message-ID: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Hi, ? If I implement __len__ in my own class, does it really have to return an int? Is there no way around this (other than modifying the source code of python itself ;-) It would be nice if len(Example(row, col)) would return a dictionary, or a two-tuple (see code below). The strange thing is that calling __len__ directly does work: Example(1, 2).__len__() returns the dictionary. I always thought len() was a convenient "shorthand" for __len__. I've even been reading about metaclasses (interesting, dark, mysterious), thinking the answer might lie there. Note that my question is not whether it's a good idea to do this, I just find it interesting to understand how it could be done. ? Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 >>> class Example(object): ?def __init__(self, row, col): ??self.row = row ??self.col = col ?def __len__(self): ??return {self.row: self.col} ?>>> len(Example(1, 2)) Traceback (most recent call last): ? File "", line 1, in ??? len(Example(1, 2)) TypeError: an integer is required >>> Example(1, 2).__len__() {1: 2} Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Sep 2 13:31:31 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Sep 2012 13:31:31 +0200 Subject: [Tutor] 2.7.3 generator objects References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> <50432F74.3030905@pearwood.info> Message-ID: Steven D'Aprano wrote: > On 02/09/12 17:09, Ray Jones wrote: > >> But didn't I read somewhere that you can reset an iterator to go through >> the whole process again? > > In general, no. > > The usual way to "reset" an iterator is to re-create it. > > > walker = os.walk("/home/steve/start") > # ... process files in walker > walker = os.walk("/home/steve/start") > # ... and process them again Python doesn't enforce this behaviour for iterators in general, but it is part of the spec: """ - Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators). Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration. """ See http://www.python.org/dev/peps/pep-0234/ For illustration purposes here's a non-compliant iterator: WRONG: >>> class Iterator: ... def __init__(self, max, factor=2): ... self.max = max ... self.factor = factor ... self.value = 1 ... def __iter__(self): ... return self ... def __next__(self): ... result = self.value ... if result >= self.max: ... raise StopIteration ... self.value *= self.factor ... return result ... def reset(self): ... self.value = 1 ... >>> it = Iterator(8) >>> next(it) 1 >>> next(it) 2 >>> next(it) 4 >>> next(it) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration >>> next(it) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration >>> it.reset() >>> next(it) 1 >>> next(it) 2 BETTER (Iterator is the same as above, without* the reset() method): >>> class Iterable: ... def __init__(self, max, factor=2): ... self.max = max ... self.factor = factor ... def __iter__(self): ... return Iterator(self.max, self.factor) ... >>> it = Iterable(8) >>> next(it) Traceback (most recent call last): File "", line 1, in TypeError: 'Iterable' object is not an iterator >>> x = iter(it) >>> next(x) 1 >>> next(x) 2 >>> next(x) 4 >>> next(x) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration Now instead of resetting the iterator ask the iterable for a new iterator: >>> x = iter(it) >>> next(x) 1 >>> next(x) 2 >>> next(x) 4 >>> next(x) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration (*) Of course I cheated and left it in ;) PS: Since the advent of generators people usually write def g(max, factor=2): value = 1 while value < max: yield value value *= factor They're all lazy bastards... PPS: 'max' should rather be called 'stop' since it indicates the upper bound of a half-open interval. From __peter__ at web.de Sun Sep 2 14:36:49 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Sep 2012 14:36:49 +0200 Subject: [Tutor] making len() and __len__ return a non-int References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > If I implement __len__ in my own class, does it really have to return an > int? Is there no way around this (other than modifying the source code of > python itself ;-) It would be nice if len(Example(row, col)) would return > a dictionary, or a two-tuple (see code below). The strange thing is that > calling __len__ directly does work: Example(1, 2).__len__() returns the > dictionary. I always thought len() was a convenient "shorthand" for > __len__. I've even been reading about metaclasses (interesting, dark, > mysterious), thinking the answer might lie there. Note that my question is > not whether it's a good idea to do this, Ah, you already know it's a bad idea... > I just find it interesting to understand how it could be done. It cannot be done without modifying the source. Here's the implementation of len() in Python 3.3: static PyObject * builtin_len(PyObject *self, PyObject *v) { Py_ssize_t res; res = PyObject_Size(v); if (res < 0 && PyErr_Occurred()) return NULL; return PyLong_FromSsize_t(res); } I did not successfully drill down further, but you can see that it may signal an error or return a Python long (which I think is the same as a Python int in 3.x) and that the underlying code operates on Py_size_t, so you'd have to modify that code, too. Py_ssize_t is implementation dependent -- on my 64-bit Linux valid lengths are in range(0, 2**63): >>> class A: ... def __len__(self): return self._len ... def __init__(self, len): ... self._len = len ... >>> len(A(-1)) Traceback (most recent call last): File "", line 1, in ValueError: __len__() should return >= 0 >>> len(A(2**63)) Traceback (most recent call last): File "", line 1, in OverflowError: cannot fit 'int' into an index-sized integer >>> len(A(2**63-1)) 9223372036854775807 From wprins at gmail.com Sun Sep 2 16:06:41 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 2 Sep 2012 15:06:41 +0100 Subject: [Tutor] Fwd: Running a script in the background In-Reply-To: References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: forwarding accidental reply to person only ---------- Forwarded message ---------- From: Walter Prins Date: 2 September 2012 15:05 Subject: Re: [Tutor] Running a script in the background To: Michael Lewis On 2 September 2012 05:00, Michael Lewis wrote: > >> For windows not sure but for osx just add an & after the command. >> >> python myscript.py & > > > Thanks, but I know about that. I should have been more clear. What I want to > do is have the script run in the background without even seeing the > terminal. Adding the & after the command will let do other things, but the > terminal still needs to be open. Once the program is running, I don't want > either the terminal or the interpreter displayed. try: nohup python myscript.py & Then you can close the terminal afterwards. "nohup" means"no hangup". It tells the system that the python process launched as a result of this command should not be terminated when its parent shell is terminated. You can also put the above command in a shell script and run the script directly via whatever method suits you best. (Launcher, scheduled job, login script etc.) Walter -- Walter Prins Trendata Solutions Limited 26 Kirfield Drive, Hinckley, Leicestershire, LE10 1SX Tel: 01455 635 994 (fax/landline) 077 8713 1543 (mobile) Email: info at trendatasolutions.ltd.uk Registered Office: 8 Emmanuel Court, 10 Mill Street, Birmingham, B72 1TJ Company registered in England No: 07364060 VAT No: 998 3569 37 From fomcl at yahoo.com Sun Sep 2 21:06:38 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 2 Sep 2012 12:06:38 -0700 (PDT) Subject: [Tutor] making len() and __len__ return a non-int In-Reply-To: References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> Albert-Jan Roskam wrote: > >> If I implement __len__ in my own class, does it really have to return an >> int? Is there no way around this (other than modifying the source code of >> python itself ;-) It would be nice if len(Example(row, col)) would return >> a dictionary, or a two-tuple (see code below). The strange thing is that >> calling __len__ directly does work: Example(1, 2).__len__() returns the >> dictionary. I always thought len() was a convenient "shorthand" for >> __len__. I've even been reading about metaclasses (interesting, dark, >> mysterious), thinking the answer might lie there. Note that my question is >> not whether it's a good idea to do this, > >Ah, you already know it's a bad idea... > >> I just find it interesting to understand how it could be done. > >It cannot be done without modifying the source. > >Here's the implementation of len() in Python 3.3: > >static PyObject * >builtin_len(PyObject *self, PyObject *v) >{ >? ? Py_ssize_t res; > >? ? res = PyObject_Size(v); >? ? if (res < 0 && PyErr_Occurred()) >? ? ? ? return NULL; >? ? return PyLong_FromSsize_t(res); >} > >===> aha. So if I do len(Example(1, 2)) the C function "builtin_len" will be called, whereas if I formulate it like Example(1, 2).__len__(), only the __len__ special method of my own bogus class will be called. Interesting. I was already checking if I could find __builtin__.__len__, but that's not possible, probably because they're all compiled. > >Thanks for your help! > >I did not successfully drill down further, but you can see that it may >signal an error or return a Python long (which I think is the same as a >Python int in 3.x) and that the underlying code operates on Py_size_t, so >you'd have to modify that code, too. Py_ssize_t is implementation dependent >-- on my 64-bit Linux valid lengths are in range(0, 2**63): > >>>> class A: >...? ? def __len__(self): return self._len >...? ? def __init__(self, len): >...? ? ? ? ? ? self._len = len >... >>>> len(A(-1)) >Traceback (most recent call last): >? File "", line 1, in >ValueError: __len__() should return >= 0 >>>> len(A(2**63)) >Traceback (most recent call last): >? File "", line 1, in >OverflowError: cannot fit 'int' into an index-sized integer >>>> len(A(2**63-1)) >9223372036854775807 > > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > ________________________________ From: Peter Otten <__peter__ at web.de> To: tutor at python.org Sent: Sunday, September 2, 2012 2:36 PM Subject: Re: [Tutor] making len() and __len__ return a non-int -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Sep 2 21:30:02 2012 From: d at davea.name (Dave Angel) Date: Sun, 02 Sep 2012 15:30:02 -0400 Subject: [Tutor] making len() and __len__ return a non-int In-Reply-To: <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> Message-ID: <5043B3BA.2070507@davea.name> On 09/02/2012 03:06 PM, Albert-Jan Roskam wrote: > Albert-Jan Roskam wrote: > If you're not going to put anything of your own into the reply message, please delete all the context you're not responding to, and then delete the message instead of sending. On the other hand, if the message actually had some content, please observe convention, and let us actually find it. Your reply should follow the parts you're quoting, and those parts should have attribution, and the > indentation at the beginning of the line should be consistent with whichever attribution it matches. New stuff should be at the left margin, without > symbol. In other words, use a decent email program, and use an before and after the stuff you type. -- DaveA From wrw at mac.com Sun Sep 2 22:30:13 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 16:30:13 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> On Sep 1, 2012, at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. > > I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. > > Thanks! > > -- > Michael J. Lewis Michael, I see you have several Windows answers, but it doesn't look as though you found quite what you were hoping for on OSX. My suggestion would be to take the script and run it through py2app, which will turn it into a stand-alone application which can then be added to your list of StartUp or LogIn applications. If you never request input or produce output, it will quite happily run in the background with no window and no menu (although by default there will be an icon in the dock). At that point it is so much a background application that the ONLY way you can quit it is via the Force Quit dialog. If you generate status or housekeeping print messages, they will show up in ~/Library/Logfiles. Py2app isn't particularly memory efficient, even a minimal application tends to run close to 9-10 Mbytes, but if it spends most of its time sleeping, it will use very little in the way of system resources. If you want it to run even when you aren't logged in, you will have to go to a bit more trouble. You will have to make up an installer plist file and use launchctl to add it to the list of stuff under control of the launchd daemon. Good luck, Bill From eryksun at gmail.com Sun Sep 2 23:04:38 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 17:04:38 -0400 Subject: [Tutor] Fwd: Running a script in the background In-Reply-To: References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 10:06 AM, Walter Prins wrote: > > nohup python myscript.py & > > Then you can close the terminal afterwards. "nohup" means"no hangup". > It tells the system that the python process launched as a result of > this command should not be terminated when its parent shell is > terminated. bash starts a background process in a new group. When you close the terminal (SIGHUP), the OS won't forward the HUP to this group, but bash defaults to forwarding it. If you "exit", on the other hand, bash won't be around to forward anything. To skip forwarding HUP in any case, just "disown" the process. If you use nohup, you can avoid creating nohup.out files if you redirect stdout somewhere such as a log file or /dev/null. If instead you just "exit" or use "disown", remember to redirect both stdout and stderr so the program doesn't try to write to a non-existent tty. From mjolewis at gmail.com Sun Sep 2 23:06:03 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 2 Sep 2012 14:06:03 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> Message-ID: > > > > Michael, I see you have several Windows answers, but it doesn't look as > though you found quite what you were hoping for on OSX. My suggestion > would be to take the script and run it through py2app, which will turn it > into a stand-alone application which can then be added to your list of > StartUp or LogIn applications. If you never request input or produce > output, it will quite happily run in the background with no window and no > menu (although by default there will be an icon in the dock). At that > point it is so much a background application that the ONLY way you can quit > it is via the Force Quit dialog. If you generate status or housekeeping > print messages, they will show up in ~/Library/Logfiles. Py2app isn't > particularly memory efficient, even a minimal application tends to run > close to 9-10 Mbytes, but if it spends most of its time sleeping, it will > use very little in the way of system resources. > > Good luck, > Bill > Thanks, Bill. That is definitely more of what I am looking for and actually found that through some googling. What I am confused about now, is what's really the difference between py2app and the python Build Applet? -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Sun Sep 2 23:32:56 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 17:32:56 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> Message-ID: <899AE6F6-8D7B-4F03-9CD7-0C3EAF92FA37@mac.com> On Sep 2, 2012, at 5:06 PM, Michael Lewis wrote: > > > Michael, I see you have several Windows answers, but it doesn't look as though you found quite what you were hoping for on OSX. My suggestion would be to take the script and run it through py2app, which will turn it into a stand-alone application which can then be added to your list of StartUp or LogIn applications. If you never request input or produce output, it will quite happily run in the background with no window and no menu (although by default there will be an icon in the dock). At that point it is so much a background application that the ONLY way you can quit it is via the Force Quit dialog. If you generate status or housekeeping print messages, they will show up in ~/Library/Logfiles. Py2app isn't particularly memory efficient, even a minimal application tends to run close to 9-10 Mbytes, but if it spends most of its time sleeping, it will use very little in the way of system resources. > > Good luck, > Bill > > Thanks, Bill. That is definitely more of what I am looking for and actually found that through some googling. What I am confused about now, is what's really the difference between py2app and the python Build Applet? > -- > Michael J. Lewis I've never played with Build Applet, only py2app, so this may be partially or totally bogus, but py2app uses a fairly elaborate "setup" script that allows you to specify things like a custom icon (if you want one) as well as specific libraries. Build Applet, on the other hand, is a much simpler tool that takes a single source file, pulls in any "includes" it finds and builds a default. It might in fact be sufficient for your needs. If you've downloaded the python from python.org, you will definitely find both the Build Applet and PythonLauncher in a PythonXX folder in your Applications folder. Good luck, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Mon Sep 3 00:14:53 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 15:14:53 -0700 Subject: [Tutor] Running a script in the background Message-ID: <5043DA5D.3010202@gmail.com> This is only tangentially related to the thread. Someone mentioned that so long as a script didn't require user input or output to the user, it could run silently in the background. But is there a way for a Python (2.7.3) script to determine whether it was called by the user or called by something like cron or kalarm? That way user inputs could be used when called by a user, but defaults could be used if run by a bot. Or is this more of a Linux question? Ray From alan.gauld at btinternet.com Mon Sep 3 00:30:57 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 23:30:57 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: <5043DA5D.3010202@gmail.com> References: <5043DA5D.3010202@gmail.com> Message-ID: On 02/09/12 23:14, Ray Jones wrote: > could run silently in the background. But is there a way for a Python > (2.7.3) script to determine whether it was called by the user or called > by something like cron or kalarm? That way user inputs could be used > when called by a user, but defaults could be used if run by a bot. Yes you can query the user via the os module.(getuid or getlogin for example) > Or is this more of a Linux question? The details are likely to be implementation dependant, differing even between local hosts since it depends on how the admin has set up the user for cron etc hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Mon Sep 3 00:36:49 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 15:36:49 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> Message-ID: <5043DF81.1070405@gmail.com> On 09/02/2012 03:30 PM, Alan Gauld wrote: > On 02/09/12 23:14, Ray Jones wrote: >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > > Yes you can query the user via the os module.(getuid or getlogin for > example) > >> Or is this more of a Linux question? > > The details are likely to be implementation dependant, differing even > between local hosts since it depends on how the admin has set up the > user for cron etc > Thanks. I'll add this to my to-learn list (It's frustrating to come up with questions and answers faster than I can assimilate it all :-p) Ray From steve at pearwood.info Mon Sep 3 03:03:02 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 3 Sep 2012 11:03:02 +1000 Subject: [Tutor] Running a script in the background In-Reply-To: <5043DA5D.3010202@gmail.com> References: <5043DA5D.3010202@gmail.com> Message-ID: <20120903010302.GA20674@ando> On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: > This is only tangentially related to the thread. Someone mentioned that > so long as a script didn't require user input or output to the user, it > could run silently in the background. But is there a way for a Python > (2.7.3) script to determine whether it was called by the user or called > by something like cron or kalarm? That way user inputs could be used > when called by a user, but defaults could be used if run by a bot. The usual way to detect this is by checking whether or not there is a terminal available. os.isatty(sys.stdout.fileno()) If the script is running directly in a console, isatty will return True; if it is running from cron, or via a pipe or similar, then it will return False. -- Steven From wrw at mac.com Mon Sep 3 03:04:41 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 21:04:41 -0400 Subject: [Tutor] Running a script in the background (this time Cc'd to the list) In-Reply-To: <5043DA74.1040903@btinternet.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> <5043DA74.1040903@btinternet.com> Message-ID: <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> On Sep 2, 2012, at 6:15 PM, Alan Gauld wrote: > On 02/09/12 21:30, William R. Wing (Bill Wing) wrote: > >> My suggestion would be to take the script and run it through py2app, >> which will turn it into a stand-alone application which can then >> be added to your list of StartUp or LogIn applications. > > Why not just create a one line shell script that starts the python program and add that to the Startup? What value does using py2app add in this case? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ Apple's mechanism for launching applications at login is picky about what it will accept as a legitimate application to add to the list. You could get there by creating an "AppleScript" that did the same thing. AppleScripts can be saved as applications and an AppleScript can call a python script (I've actually done that, but it leaves you maintaining two bits of code, not just one). To the best of my knowledge, there is no way you can convince the application-picker to accept a shell script (or a raw python script) as an application. You can add it to the list, but at login, what happens is that the editor you used to create the script gets invoked with the script opened in it. -Bill From eryksun at gmail.com Mon Sep 3 06:34:32 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 3 Sep 2012 00:34:32 -0400 Subject: [Tutor] Running a script in the background (this time Cc'd to the list) In-Reply-To: <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> <5043DA74.1040903@btinternet.com> <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> Message-ID: On Sun, Sep 2, 2012 at 9:04 PM, William R. Wing (Bill Wing) wrote: > > Apple's mechanism for launching applications at login is picky > about what it will accept as a legitimate application to add to > the list. Here's an Ask Different (Apple Stack Exchange) answer with a template for a launchd plist: http://apple.stackexchange.com/a/822 I don't use OS X, so I can't offer anymore held than that. From crawlzone at gmail.com Mon Sep 3 08:33:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 23:33:30 -0700 Subject: [Tutor] Running a script in the background (offshoot - sorry, OP) In-Reply-To: <20120903010302.GA20674@ando> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: <50444F3A.90608@gmail.com> On 09/02/2012 06:03 PM, Steven D'Aprano wrote: > On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: >> This is only tangentially related to the thread. Someone mentioned that >> so long as a script didn't require user input or output to the user, it >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > The usual way to detect this is by checking whether or not there is a > terminal available. > > os.isatty(sys.stdout.fileno()) > > If the script is running directly in a console, isatty will return True; > if it is running from cron, or via a pipe or similar, then it will > return False. Okay. Your solution works with cron - it does not work with kalarm (KDE's system alarm). The only reason I'm using kalarm rather than cron to begin with is that kalarm is TZ aware while anacron only looks at the system TZ (i.e. with kalarm I can start each task based on its own individual time zone). I read that fcron is fully TZ aware, but when I tried to install it, it wanted to automatically remove anacron and the entire kubuntu-desktop! Now this definitely gets into the Linux side of things. I'll go hit the Ubuntu forums and see what I can find. Thanks, everyone. Ray From richkappler at gmail.com Mon Sep 3 16:04:39 2012 From: richkappler at gmail.com (richard kappler) Date: Mon, 3 Sep 2012 10:04:39 -0400 Subject: [Tutor] multi processes or threads? Message-ID: I'm not sure which direction to go. I need to be able to run multiple ?processes? ?threads? (not sure which) concurrently. I'm working on AI for a robot and because I'm not sure what direction to go I'll use the term "thread" to illustrate my question, realizing threads may not be what I'm looking for. The bot would have several "threads" running concurrently so as to be aware of it's state, such as a vision thread, an object and face recognition thread, a chat thread, a command and control thread, a nav thread, you get the idea. In order to do this in python, should I be looking at threads, multiprocessing, something else or is this not practicable in python? regards, Richard -- Eat a live toad the first thing in the morning and nothing worse will happen to you the rest of the day. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Mon Sep 3 17:01:28 2012 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 3 Sep 2012 10:01:28 -0500 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: Hi. I started running the program in the terminal rather than IDLE. It works, and I can run several programs at the same time. The problem is that when the program is finished running, it prints: exit status: 0 logout [Process completed] And I can't access the data that the program returned. Do I need the program to be saved to a text file, or is there a way to simply print it out? It's a small amount of data, and I'd rather just print it out. Ben On Aug 29, 2012, at 9:24 AM, Marc Tompkins wrote: > On Tue, Aug 28, 2012 at 7:35 PM, Steven D'Aprano wrote: > > In Windows, that is the DOS prompt -- either cmd.com or command.exe, I never remember which one is which. > > I'm pretty sure that was intentional, but just in case... > > In MS-DOS/PC-DOS, and in 16-bit versions of Windows (up to Windows 98/Me, in other words), the command interpreter is COMMAND.COM > > In 32-bit versions of Windows, you can still use the 16-bit interpreter if you want - although it's deprecated, and has been removed entirely in 64-bit Windows - but the native 32-bit command interpreter is CMD.EXE > > (I used all-caps for emphasis without requiring HTML formatting, but in fact Windows is generally case-insensitive.) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Mon Sep 3 18:26:27 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Mon, 03 Sep 2012 12:26:27 -0400 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> On Sep 3, 2012, at 11:01 AM, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It works, and I can run several programs at the same time. The problem is that when the program is finished running, it prints: > exit status: 0 > logout > > [Process completed] > > And I can't access the data that the program returned. Do I need the program to be saved to a text file, or is there a way to simply print it out? It's a small amount of data, and I'd rather just print it out. > Ben > Ben, You will probably get several answers to this, since there are several ways to solve the issue. The simplest (sort of kludgy) solution is simply to make the last line in your program be: junk = raw_input("Yes Master?") and when your program hits this line, it will print out "Yes Master?" in the terminal window and then sit there waiting for you to type something terminated by a key. For future reference, what you've typed goes into the variable junk. This is a dead easy way to get interactive data into ANY future python script you write. -Bill PS: this assumes you are running python 2.x. In python 3.x, raw_input has been renamed input, but it works the say way. From alan.gauld at btinternet.com Mon Sep 3 19:41:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Sep 2012 18:41:40 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 03/09/12 15:04, richard kappler wrote: > what I'm looking for. The bot would have several "threads" running > concurrently so as to be aware of it's state, such as a vision thread, > an object and face recognition thread, a chat thread, a command and > control thread, a nav thread, you get the idea. In order to do this in > python, should I be looking at threads, multiprocessing, something else > or is this not practicable in python? Threads. Multiple processes would be overkill for this. And yes its fine in Python. Check out the threading module. Several online tutorials on how to use it too. My only caveat is not to have too many, especially conflicting controls. For example anything that causes the bot to move should be in a single thread or you wind up with two threads competing with each other to move the bot in two directions at once. Similarly vision and face recognition could conflict. Hopefully you get my drift. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Sep 3 19:55:43 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Sep 2012 18:55:43 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: On 03/09/12 16:01, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It > works, and I can run several programs at the same time. The problem is > that when the program is finished running, it prints: > exit status: 0 > logout > > [Process completed] That is probably writing to stderr so you can redirect the stderr output to a file (or /dev/null if you're feeling confident!) $ python myprog.py myargs 2> myprog.err & runs myprog.opy in the background and redirects stderr to the file myprog.err. You can then open mpyprog.err in any text editor to read it if you wish - hopefully it will be very boring! > And I can't access the data that the program returned. Do I need the > program to be saved to a text file, or is there a way to simply print it > out? It's a small amount of data, and I'd rather just print it out. It should print to stdout so you can see it but in general its probably better to redirect that to a file too... Especially if you have multiple programs in one terminal! So your command lines should probably look like $ python myprog.py myargs 2> myprog.err 1> myprog.out & HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Mon Sep 3 21:50:32 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 03 Sep 2012 20:50:32 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: On Mon, 03 Sep 2012 18:55:43 +0100, Alan Gauld wrote: > On 03/09/12 16:01, Benjamin Fishbein wrote: > > Hi. I started running the program in the terminal rather than IDLE. It > > works, and I can run several programs at the same time. The problem is > > that when the program is finished running, it prints: > > exit status: 0 > > logout > > > > [Process completed] What do you mean when you say you ran the program in the terminal? Do you mean that you opened a terminal window and then typed 'python myprog.py'? Or did you click on the python file and choose 'run in terminal' or similar? That output looks to me like what happens on OSX when a terminal window is open but the shell has been closed. I think the instruction to run in a terminal should look like: 1) open the terminal (how to do this depends on your OS). 2) type 'cd /path/to/my/script/folder' and then hit enter. 3) type 'python script.py' and then hit enter. Is that similar to what you're doing? Oscar From dwightdhutto at gmail.com Mon Sep 3 23:32:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:32:43 -0400 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: Think assembly, or procedural with this, and how the mind of a CPU works. Instructional steps toward an endpoint. Your mind works the fastest when one problems is given, and is being solved, otherwise allocation of certain areas take place in order to find a rewarding solution. Not having used threads in the past, I would suggest that you know there has to be either equal allocation of time, or priority based in order to perform each procedure given in threading, until there is a final result. My first thought on giving computers imagination was monkeys banging on a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's interlocking molecular vectors, and run simulations which is much more difficult, but defined algorithmically, and procedurally, unless you network several cpus and allocate to each a specific thought/theory/hypothesis to process. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 3 23:46:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:46:43 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: <20120903010302.GA20674@ando> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On Sun, Sep 2, 2012 at 9:03 PM, Steven D'Aprano wrote: > On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: > > This is only tangentially related to the thread. Someone mentioned that > > so long as a script didn't require user input or output to the user, it > > could run silently in the background. But is there a way for a Python > > (2.7.3) script to determine whether it was called by the user or called > > by something like cron or kalarm? That way user inputs could be used > > when called by a user, but defaults could be used if run by a bot. > > The usual way to detect this is by checking whether or not there is a > terminal available. > > os.isatty(sys.stdout.fileno()) > > If the script is running directly in a console, isatty will return True; > if it is running from cron, or via a pipe or similar, then it will > return False. But a script is always running in the background of the OS main console of the upfront GUI app users usually see, correct? Cron has to coninually run, or have another process that checks x number per minute(hertz of the process) to see what is going on, so it all goes back to a main script in OS runtime checking for processes to run, even for other processes, for other processes, etc. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 3 23:48:17 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:48:17 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: > > Cron or another process that oversees cron has to continually run. > > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com* > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 4 01:57:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 00:57:25 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On 03/09/12 22:46, Dwight Hutto wrote: > But a script is always running in the background of the OS main console > of the upfront GUI app users usually see, correct? Not every OS has a main console behind the GUI, but in the case of *nix its true. On *nix there is a cron daemon that runs in the background. but one job running in the background controlling dozens(?) of others is way more efficient than dozens of programs all running idle in the background and periodically springing into action. > back to a main script in OS runtime checking for processes to run, even > for other processes, for other processes, etc. Ultimately it all goes back to the OS scheduler which constantly swaps processes in and out of run mode... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 4 01:59:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 00:59:28 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 03/09/12 22:32, Dwight Hutto wrote: > Think assembly, or procedural with this, and how the mind of a CPU > works. Instructional steps toward an endpoint. > > Your mind works the fastest when one problems is given, and is being > solved, otherwise allocation of certain areas take place in order to > find a rewarding solution. > > Not having used threads in the past, I would suggest that you know there > has to be either equal allocation of time, or priority based in order to > perform each procedure given in threading, until there is a final result. > > My first thought on giving computers imagination was monkeys banging on > a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's > interlocking molecular vectors, and run simulations which is much more > difficult, but defined algorithmically, and procedurally, unless you > network several cpus and allocate to each a specific > thought/theory/hypothesis to process. > I have no idea what all that means! Nor how it relates to the OPs question. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dwightdhutto at gmail.com Tue Sep 4 02:19:07 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 20:19:07 -0400 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On Mon, Sep 3, 2012 at 7:59 PM, Alan Gauld wrote: > On 03/09/12 22:32, Dwight Hutto wrote: > >> Think assembly, or procedural with this, and how the mind of a CPU >> works. Instructional steps toward an endpoint. >> >> Your mind works the fastest when one problems is given, and is being >> solved, otherwise allocation of certain areas take place in order to >> find a rewarding solution. >> >> Not having used threads in the past, I would suggest that you know there >> has to be either equal allocation of time, or priority based in order to >> perform each procedure given in threading, until there is a final result. >> I'm working on AI for a robot and because I'm not sure what direction >> to go I'll use the term "thread" to illustrate my question, realizing >> threads may not be what I'm looking for. >> My first thought I'm working on AI for a robot and because I'm not sure >> what direction to go I'll use the term "thread" to illustrate my question, >> realizing threads may not be what I'm looking for. on giving computers >> imagination was monkeys banging on >> a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's >> interlocking molecular vectors, and run simulations which is much more >> difficult, but defined algorithmically, and procedurally, unless you >> network several cpus and allocate to each a specific >> thought/theory/hypothesis to process. >> >> > I have no idea what all that means! > Nor how it relates to the OPs question. > >From the OP: I'm working on AI for a robot and because I'm not sure what direction to go I'll use the term "thread" to illustrate my question, realizing threads may not be what I'm looking for. Tell me Alan, what is threading within a CPU, coming from a higher level language, that passes through a processor executing one instruction at time from the instruction pointer, unless otherwise designed from multiple instructions through separate cpu's(i.e. real thread commands)? -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Tue Sep 4 02:26:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 20:26:43 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On Mon, Sep 3, 2012 at 7:57 PM, Alan Gauld wrote: > On 03/09/12 22:46, Dwight Hutto wrote: > > But a script is always running in the background of the OS main console >> of the upfront GUI app users usually see, correct? >> > > Not every OS has a main console behind the GUI, but in the case of *nix > its true. > > On *nix there is a cron daemon that runs in the background. > but one job running in the background controllingfat boy slim dozens(?) of > others is way more efficient than dozens of programs all running idle in > the background and periodically springing into action. > But each OS(BIOS handler) has a way of providing/accepting instructions to the processor, which is constantly procedural. This has to have a terminal at some point. What is meant by behind a console, and running without a console, just a window system, and a file set that deals with instructions/errors based on BIOS input/output? -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 4 03:47:32 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 04 Sep 2012 11:47:32 +1000 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: <50455DB4.2070808@pearwood.info> On 04/09/12 01:01, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It works, > and I can run several programs at the same time. The problem is that when the >program is finished running, it prints: > exit status: 0 > logout > > [Process completed] Which terminal is that? I've never come across a terminal with that behaviour. > And I can't access the data that the program returned. Programs don't return data. They can output data to a file or pipe, or print to the screen. The execution model of functions within a program and of the program itself are quite different and you need to wrap your brain around the differences. Normally, you would output your program's result to a file-like thing. Two common idioms used by most command-line tools are: 1) the program always writes data to "standard output" (stdout); the caller can re-direct stdout using the usual pipe and redirection operators; 2) the program takes a command-line argument telling it which file to write to; if no file name is given, you can write to a default file, or stdout as above, or print an error message and stop. Variations include "verbose mode", that formats the result in a nice, human- readable format intended for human readers, and "terse mode" intended to be piped to another program. I recommend you study the various conventions of the command-line tools on your operating system. In Python, normally you would divide your program into two separate layers: * a calculation layer that calculates the result you need; * a display layer that is responsible for output. That allows you to easily separate the two parts of the problem: you can isolate "display bugs" from "calculation bugs", test and debug each separately, and even use the calculation functions from other Python code. The display layer might be as simple as the print command: if __name__ == '__main__': result = do_some_calculation() print(result) Last but not least, to be a "well-behaved" command line tool, you should set the return code. The easiest way to do this from Python is with sys.exit: import sys if an_error_occurred: sys.exit(error_code) else: sys.exit(0) There are supposed to be conventions for what the error codes mean, but nobody agrees on them. The easiest is to just return 1 or 2 to mean "an error occurred". -- Steven From steve at pearwood.info Tue Sep 4 03:56:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 04 Sep 2012 11:56:44 +1000 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: <50455FDC.6070900@pearwood.info> On 04/09/12 10:26, Dwight Hutto wrote: >> On *nix there is a cron daemon that runs in the background. >> but one job running in the background controlling dozens(?) of >> others is way more efficient than dozens of programs all running idle in >> the background and periodically springing into action. >> > > But each OS(BIOS handler) has a way of providing/accepting instructions to > the processor, which is constantly procedural. This has to have a terminal > at some point. > > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based on > BIOS input/output? I'm afraid these sentences sound like gobbledygook to me. No offense Dwight, but it sounds like you're randomly inserting "computer terms" into sentences with no meaning. The only part that actually makes sense to me is: "This has to have a terminal at some point." but that is not true. The fact that cron runs without a tty (a terminal) is proof of that. -- Steven From Garry.Willgoose at newcastle.edu.au Tue Sep 4 03:57:48 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 4 Sep 2012 11:57:48 +1000 Subject: [Tutor] making a shortcut in windows Message-ID: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error AttributeError: function 'CreateSymbolicLinkW' not found so does anybody have any suggestions? __CSL = None def create_alias(source, linkname): """ Each operating system has a different way of creating an alias. This is the windows version """ import os try: global __CSL if __CSL is None: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte __CSL = csl flags = 0 if source is not None and os.path.isdir(source): flags = 1 if __CSL(linkname, source, flags) == 0: raise ctypes.WinError() except: print('#### Error creating a file alias from '+str(source)+' to '+str(linkname)) return() From dwightdhutto at gmail.com Tue Sep 4 04:21:36 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 22:21:36 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: <50455FDC.6070900@pearwood.info> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> <50455FDC.6070900@pearwood.info> Message-ID: On Mon, Sep 3, 2012 at 9:56 PM, Steven D'Aprano wrote: > On 04/09/12 10:26, Dwight Hutto wrote: > > On *nix there is a cron daemon that runs in the background. >>> but one job running in the background controlling dozens(?) of >>> >>> others is way more efficient than dozens of programs all running idle in >>> the background and periodically springing into action. >>> >>> >> But each OS(BIOS handler) has a way of providing/accepting instructions to >> the processor, which is constantly procedural. This has to have a terminal >> at some point. >> >> What is meant by behind a console, and running without a console, just a >> window system, and a file set that deals with instructions/errors based on >> BIOS input/output? >> > > > On Mon, Sep 3, 2012 at 9:56 PM, Steven D'Apran > > Best regards, > o wrote: > >> On 04/09/12 10:26, Dwight Hutto wrote: >> >> On *nix there is a cron daemon that runs in the background. >>>> but one job running in the background controlling dozens(?) of >>>> >>>> others is way more efficient than dozens of programs all running idle in >>>> the background and periodically springing into action. >>>> >>>> >>> But each OS(BIOS handler) has a way of providing/accepting instructions >>> to >>> the processor, which is constantly procedural. This has to have a >>> terminal >>> at some point. >>> >>> What is meant by behind a console, and running without a console, just a >>> window system, and a file set that deals with instructions/errors based >>> on >>> BIOS input/output? >>> >> >> I'm afraid these sentences sound like gobbledygook to me. No offense >> Dwight, >> but it sounds like you're randomly inserting "computer terms" into >> sentences >> with no meaning. >> >> Which one's. If yuou could, please reply on a line by line, because some of what you listed above isn't mine. What's wrong with: But each OS(BIOS handler) has a way of providing/accepting instructions to the processor, which is constantly procedural. This has to have a terminal at some point. What is meant by behind a console, and running without a console, just a window system, and a file set that deals with instructions/errors based on BIOS input/output? I'll add Intel/AMD to the instructions secton. The gobbledy gook, might be a little smeared on your face...Want a rag?...Steven By the way, you can call me David...buddy. The only part that actually makes sense to me is: >> >> >> "This has to have a terminal at some point." >> >> but that is not true. The fact that cron runs without a tty (a terminal) >> is >> proof of that. >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > I'm afraid these sentences sound like gobbledygook to me. No offense > Dwight, > but it sounds like you're randomly inserting "computer terms" into > sentences > with no meaning. > > The only part that actually makes sense to me is: > > > "This has to have a terminal at some point." > > but that is not true. The fact that cron runs without a tty (a terminal) is > proof of that. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 4 07:56:43 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 4 Sep 2012 15:56:43 +1000 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: <20120904055643.GA28719@ando> On Tue, Sep 04, 2012 at 11:57:48AM +1000, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > Python 2.6 or later. In Unix its easy using os.symlink but I can't > find anything equivalent for windows. My searches on the web led me to > the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found If you expect us to actually debug the error, you need to give the right debugging information. That means you have to show the FULL traceback printed, not just the final error message without any context. Do not retype the error from memory, or summarise it, do a copy and paste of the entire traceback, starting with the line Traceback (most recent call last): all the way to the end. And then make sure that the code you are giving us is the same as the code you are running. I say this because I believe that the code you sent us is not the code you are running. I cannot see any possible way for the code you gave to raise AttributeError. But in this case, I recommend against using ctypes. Here are some better ways to manage Windows shortcuts: http://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts/ http://mail.python.org/pipermail/python-win32/2003-March/000862.html > __CSL = None > > def create_alias(source, linkname): > """ > Each operating system has a different way of creating an alias. > This is the windows version > """ That's technically incorrect. *Alias* (MacOS), *shortcut* (Windows) and *symlink* (Linux, Unix, MacOS, and others) are all slightly different things, although they all solve more-or-less the same problem. In principle you could have a single OS offer all three. MacOS offers both aliases and symlinks. (And even more pedantically: it isn't the *operating system* which matters, but the file system. So Windows with a Linux file system could have symlinks.) > import os > try: [...] > except: > print('#### Error creating a file alias from '+str(source)+' to '+str(linkname)) Please never, ever, ever do that. Every time somebody writes an except block that catches everything like that, god kills a kitten. Catch-all exceptions like that are one of the worst bad-ideas in Python ever. The problems include: * They catch too much -- not only do they catch legitimate errors that should be caught, but they catch non-errors like KeyboardInterrupt which *don't* indicate an error. * They mask programming bugs -- because they catch too much, they hide programming bugs which should be exposed with a traceback so that you can fix them. * They give you no way to access the exception caught. * They tempt beginners into thinking that they have to *hide problems* by catching the exception and just printing a message, instead of *fixing problems* so no exception happens in the first place. There are exceptions (pun not intended) to the rule "never use a bare except", but they're rare. In general, a try...except block should: * always explicitly state the exception(s) you want to catch; * cover only the minimum amount of code necessary. > return() That line is wrong -- it returns an empty tuple (). To return nothing, just say "return" on its own, or better still, don't say anything and the function will return nothing when it is finished. (To be precise: it will return the None object.) -- Steven From alan.gauld at btinternet.com Tue Sep 4 09:51:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 08:51:32 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On 04/09/12 01:26, Dwight Hutto wrote: > But each OS(BIOS handler) has a way of providing/accepting instructions > to the processor, which is constantly procedural. This has to have a > terminal at some point. No it doesn't. Most OS do not run in a 'procedural' way (by which I assume you mean sequential?) Most are event driven and that often at the hardware level. The processor has an interrupt mechanism which causes a section of code to run. The section chosen is determined by the interrupt number and results in a jump to a predefined address. The interrupts are driven by hardware events with no software control. Some interrupts are pre-emptive - they will stop any current processing and take control, others will wait for current processing to finish. The processor will also have a software interrupt mechanism which does the same thing but is driven by an INT call in the software. Operating systems from CP/M and DOS onwards are driven by interrupts at the kernel level they do not sit in some kind of giant event loop looking for things to process. > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based > on BIOS input/output? Again no, a terminal is an I/O mechanism. It reads input and displays output. The terminal does not process the commands it passes those to the program running inside it. Even the shell is not part of the Terminal, it just runs inside. And daemon programs do not use a terminal at all. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 4 10:05:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 09:05:49 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 04/09/12 01:19, Dwight Hutto wrote: > I have no idea what all that means! > Nor how it relates to the OPs question. > From the OP: > > I'm working on AI for a robot and because I'm not sure what direction OK, I see that connection now. > Tell me Alan, what is threading within a CPU, coming from a higher level > language, that passes through a processor executing one instruction at > time from the instruction pointer, unless otherwise designed from > multiple instructions through separate cpu's(i.e. real thread commands)? I'm still not certain what you mean here but I think you are referring to the time-slicing technique used by the OS to run multiple processes/threads on a single CPU? The CPU (or core) doesn't understand the concept of threading that's a higher level concept usually managed by the OS (although with multi-core CPUs increasingly done at hardware too). The point of threading is to avoid programs blocking while still having valid work to do. In effect taking advantage of the multi-processing features of the OS to allow parts of a program to keep running when it would otherwise block while waiting for input or output to complete. As such it will make the application more responsive and for bulk data processing run faster (with fewer wait states). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Tue Sep 4 11:13:37 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Sep 2012 10:13:37 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> <15DDF669-1A6D-448B-8091-B2847ED8D70C@gmail.com> Message-ID: Hi Ben, It's best if you can avoid top-posting and put your responses in between the appropriate parts of the message you are replying to like I have below: On 4 September 2012 02:53, Benjamin Fishbein wrote: > I used Python Launcher and it opened it in the terminal. > Ben > > On Sep 3, 2012, at 2:50 PM, Oscar Benjamin wrote: > > > On Mon, 03 Sep 2012 18:55:43 +0100, Alan Gauld < > alan.gauld at btinternet.com> wrote: > >> On 03/09/12 16:01, Benjamin Fishbein wrote: > >> > Hi. I started running the program in the terminal rather than > > IDLE. It > >> > works, and I can run several programs at the same time. The > > problem is > >> > that when the program is finished running, it prints: > >> > exit status: 0 > >> > logout > >> > > >> > [Process completed] > > > > What do you mean when you say you ran the program in the terminal? Do > you mean that you opened a terminal window and then typed 'python > myprog.py'? Or did you click on the python file and choose 'run in > terminal' or similar? That output looks to me like what happens on OSX when > a terminal window is open but the shell has been closed. > So you were using the python launcher on the dock? I guess you are using OSX, then (it's good to provide this kind of information). The reason you're not seeing any output is probably because you're not printing it. If your program has a variable called 'total' that you would like to see the value of simply put a line like 'print(total)' at the end of your script. Then you should see the output. > > > > I think the instruction to run in a terminal should look like: > > 1) open the terminal (how to do this depends on your OS). > > 2) type 'cd /path/to/my/script/folder' and then hit enter. > > 3) type 'python script.py' and then hit enter. > Have you tried the instructions above. Assuming you're using OSX you can do step 1 by hitting cmd-space to open spotlight. Then you type 'terminal' and hit enter and you will have a terminal window. Oscar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 4 11:14:50 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 4 Sep 2012 05:14:50 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> <50455FDC.6070900@pearwood.info> Message-ID: On Mon, Sep 3, 2012 at 10:21 PM, Dwight Hutto wrote: > What's wrong with: > > But each OS(BIOS handler) has a way of providing/accepting instructions to > the processor, which is constantly procedural. This has to have a terminal > at some point. What do you mean by 'terminal' in this context? A terminal is a device (possibly virtual) for entering data and displaying output from a computer. cron isn't scheduling active processes/threads like the kernel does. Every minute, it checks a job table and possibly starts one or more programs. This is an efficient way to schedule a large number of programs to run at various times throughout the day, week, and month. Otherwise all of these programs would need to have at least a stub that runs as a daemon, wasting memory and CPU resources needlessly. Scheduling processes is an entirely different domain. In a preemptive multitasking system, it's up to the kernel to schedule access to the CPU. Each process (or thread on some systems) is assigned a quantum of ticks. The ticks are based on a hardware timer. Periodically (e.g. 10 milliseconds) this timer triggers a hardware interrupt that enables the kernel to preempt the current thread. The kernel schedules the next (possibly the same) process to run, based on a priority scheme, out of the pool of ready processes. Preempting a running process requires a context switch, i.e. the process control block (e.g. PID, priority, execution state such as running/ready/waiting, CPU number/registers/flags, virtual memory, signal handlers, I/O, credentials, accounting, etc) has to be saved on the current stack. Then the PCB of the next process is loaded; the CPU state is restored; and execution resumes seamlessly. Here's the task_struct used by the Linux scheduler (lines 1235-1593): http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=blob;f=include/linux/sched.h#l1235 > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based on > BIOS input/output? Windows NT typically boots without a console. It doesn't have virtual terminals, but you can run console programs in a Win32 console managed by the Client/Server Runtime Subsystem (csrss.exe) In contrast, Linux boots in console mode. Typically it maps the "console" (boot parameter) to the current virtual terminal (i.e. /dev/tty0), but it could also be a dumb terminal or modem. It creates several virtual terminals depending on the system configuration. Debian has tty's 1-63 and runs getty on tty 1-6 to allow text-mode logins and an Xorg display manager (e.g. lightdm) on tty7 for logging in to a graphical desktop environment (e.g. xfce4). From eryksun at gmail.com Tue Sep 4 12:31:43 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 4 Sep 2012 06:31:43 -0400 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On Mon, Sep 3, 2012 at 9:57 PM, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > > AttributeError: function 'CreateSymbolicLinkW' not found A simple search for "msdn CreateSymbolicLink" leads to the following page: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363866.aspx Scroll down to the requirements, and you'll see that CreateSymbolicLink was added to Kernel32 (and NTFS) in Windows Vista (NT 6.x). Kernel32 in Windows XP (NT 5.x) doesn't have that function; hence the AttributeError. From oscar.j.benjamin at gmail.com Tue Sep 4 14:06:55 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Sep 2012 13:06:55 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > Python 2.6 or later. In Unix its easy using os.symlink but I can't find > anything equivalent for windows. My searches on the web led me to the code > below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > > so does anybody have any suggestions? > Are you really trying to create a symbolic link? Note that this is not the same thing as a 'shortcut' in Windows. If you say why you want the shortcut someone may be able to help you find another way of doing what you want. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Sep 4 14:55:27 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Sep 2012 13:55:27 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Hi, On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > so does anybody have any suggestions? IIRC and as implied by other responses so far, "Symbolic Links" are an NTFS feature only relatively recently added to NTFS. Creating a Symbolic Link (whether on Windows or elsewhere) is not the same as creating a "Shortcut" in Windows, even though they can in some contexts (e.g. a GUI desktop environment) be used to fulfil the same role. Anyway, to be backwards compatible with Win XP you should be creating a "Shortcut", more properly known as a "Shell link". See here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776891%28v=vs.85%29.aspx Basically you need to use the IShellLink COM interface to create the link. You can use PythonCOM to do this (not sure if you'll be happy about adding a dependency on COM to your application though), either way, here's a presentation that also mentions IShellLink (note it's a bit old so make allowances for the age): http://starship.python.net/~skippy/conferences/tools99/html/ppframe.htm Walter From Garry.Willgoose at newcastle.edu.au Tue Sep 4 15:10:19 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 4 Sep 2012 23:10:19 +1000 Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Oscar, I actually just want the functionality of a shortcut so that I can put an icon on the desktop. symlink allows that in Unix (and a few other capabilities that I'm not that intersted in) and just want something equivalent to the menu item for making a shortcut in Windows. > On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > > so does anybody have any suggestions? > > Are you really trying to create a symbolic link? Note that this is not the same thing as a 'shortcut' in Windows. If you say why you want the shortcut someone may be able to help you find another way of doing what you want. > > Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Tue Sep 4 16:37:22 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 4 Sep 2012 09:37:22 -0500 (CDT) Subject: [Tutor] running more than one python program at the same time In-Reply-To: <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> Message-ID: On Mon, 3 Sep 2012, William R. Wing (Bill Wing) wrote: > junk = raw_input("Yes Master?") You don't even need the 'junk' bit: raw_input("Yes Master?") Will run just fine. HTH, -Wayne From wayne at waynewerner.com Tue Sep 4 16:44:01 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 4 Sep 2012 09:44:01 -0500 (CDT) Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On Tue, 4 Sep 2012, Garry Willgoose wrote: > Oscar, > > I actually just want the functionality of a shortcut so that I can put an > icon on the desktop. symlink allows that in Unix (and a few other > capabilities that I'm not that intersted in) and just want something > equivalent to the menu item for making a shortcut in Windows.? At least in Windows 7+, you can use the mklink command (as administrator): import subprocess subprocess.check_call(['mklink', '/D', #Use /H for a hard link '\users\yourname\desktop\yourfile.txt', '\path\to\yourfile.txt']) HTH, Wayne From wprins at gmail.com Tue Sep 4 18:10:46 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Sep 2012 17:10:46 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Hi, On 4 September 2012 15:44, Wayne Werner wrote: >> I actually just want the functionality of a shortcut so that I can put an >> icon on the desktop. symlink allows that in Unix (and a few other >> capabilities that I'm not that intersted in) and just want something >> equivalent to the menu item for making a shortcut in Windows. > > > At least in Windows 7+, you can use the mklink command (as administrator): > > import subprocess > subprocess.check_call(['mklink', > '/D', #Use /H for a hard link > '\users\yourname\desktop\yourfile.txt', > '\path\to\yourfile.txt']) > > HTH, > Wayne Yes, but as already noted symbolic links are a newish feature that is not available on older OS's, so the original poster probably wants to look at API's to create actual shortcut's given that he's targeting WinXP etc. Regards Walter From chigga101 at gmail.com Tue Sep 4 20:45:12 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 19:45:12 +0100 Subject: [Tutor] help me decide Message-ID: hey guys as i program more, i think of silly questions i would like answers to. if anyone doesnt mind entertaining my question, please do answer:) I have just about finished my beginner tutorial, just a few exercises left. i feel confident using Python now but im still not sure which direction i want to go in. I would at some point like to learn how to use GUIs and a web Framework(Django). But i don't know which of the 2 to start out with. a) IF you happen to have used both, which one fills you with joy and is more fun for you to program with, GUI programming, or web related / Framework programming? b) which was easier and less complex for you to learn? or should i say had a lower learning curve? i ask this because the sooner i get an understanding of one, i can maybe give the other one a go. But if it's too hard i usually give 100% to it and never try learning anything else until it computes. my tutorial had a small section on tkinter. I have now looked for some tutorials and noticed Python tutorials on both tkinter and Tk. As i understand they are not the same thing but tkinter is like the interface of Tk? my question is: c) which tutorial would be better to study, Tkinter or Tk? and what exactly is the difference? why do they have separate tutorials? i looked at some pyQT articles, but its coding looks less organised than Tkinter. d) is this true? is Tkinter a lot more straight forward and Python friendly? e) Does pyQT have grids (rows and columns) to place your widgets on like Tkinter, or do you have to use x and y axis to position widgets etc..? Before i try to learn either, GUIs or a web Framework, i was looking into maybe getting a deeper understanding of OOP. my tutorial only covered it briefly. f) would this be a good idea tackling OOP next before the other 2, or is this a skill you master with more programming experience? ok my last question is not so important:) im just curious as i grow more fond of programming. well i keep reading Python is an all-purpose general programming language(web frameworks, desktop apps, science/maths etc..). I notice Java has similar features so should also be considered an all-purpose general programming language. my question is: g) not a comparison in 1 specific area, but which language is better or more suited to all around all-purpose quality. thanks guys From leamhall at gmail.com Tue Sep 4 21:40:12 2012 From: leamhall at gmail.com (leam hall) Date: Tue, 4 Sep 2012 15:40:12 -0400 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: Matthew, Program what is fun for you. I prefer PHP for web work but I'm learning Python for my day job. Python provides a wider range of abilities but PHP is more "fun" for me. If Python GUIs are fun, then do that. The more you enjoy the topic the more reason you will have to learn more and more. I doubt you will exhaust Python's capabilities any time soon. Python or Java? For me it's Python. The only real Java advantage might be Android programming. Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Tue Sep 4 22:20:31 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 21:20:31 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: sorry wrong i didnt send mail right. hey i didnt explain it properly, i wasn't asking what language to use or learn. I am only going to be using Python. I meant whic area to study on 1st, GUI programing e.g Tkinter or Programming with a web framwork e.g Django. From chigga101 at gmail.com Tue Sep 4 22:31:18 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 21:31:18 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: hey you didnt read my question:( i dont enjoy either because i have no experience with them. so im asking questions about peoples personal experiences with the 2 areas which can give me further information to research on. From crawlzone at gmail.com Wed Sep 5 11:42:31 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 02:42:31 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) Message-ID: <50471E87.60607@gmail.com> I have directory names that contain Russian characters, Romanian characters, French characters, et al. When I search for a file using glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the directory names. I thought simply identifying them as Unicode would clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. These representations of directory names are eventually going to be passed to Dolphin (my file manager). Will they pass to Dolphin properly? Do I need to run a conversion? Can that happen automatically within the script considering that the various types of characters are all mixed together in the same directory (i.e. # coding: Latin-1 at the top of the script is not going to address all the different types of characters). While on the subject, I just read through the Unicode info for Python 2.7.3. The history was interesting, but the implementation portion was beyond me. I was looking for a way for a Russian 'backward R' to look like a Russian 'backward R' - not for a bunch of \xxx and \uxxxxx stuff. Can someone point me to a page that will clarify the concepts, not just try to show me the Python implementation of what I already don't understand? ;) Thanks Ray From wprins at gmail.com Wed Sep 5 11:57:24 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 5 Sep 2012 10:57:24 +0100 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50471E87.60607@gmail.com> References: <50471E87.60607@gmail.com> Message-ID: Hi Ray, On 5 September 2012 10:42, Ray Jones wrote: > Can someone point me to a page that will clarify the concepts, not just > try to show me the Python implementation of what I already don't > understand? ;) Try the following 2 links which should hopefully help: http://www.joelonsoftware.com/articles/Unicode.html http://nedbatchelder.com/text/unipain.html Cheers, Walter From chigga101 at gmail.com Wed Sep 5 12:04:39 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Wed, 5 Sep 2012 11:04:39 +0100 Subject: [Tutor] help me decide In-Reply-To: <5046A014.6030907@btinternet.com> References: <5046A014.6030907@btinternet.com> Message-ID: Hi Alan thanks so much for your helpful answers. > probably wxPython or GTk > But if you want to get serious about GUIs I'd probably suggest wxPython > instead - it ultimately is more powerful and complete and if you are only > just starting will be easy to learn whereas learning Tkinter and converting > is more difficult (IMHO). > PyQt is powerful too but there are several limitations in its licensing > model that leave me slightly wary. Gtk is another option. Both of these were > originally made popular in the Linux community but both are available cross > platform now. (as are Tkinter and wxPython) After your response ive decided GUI programming is defintely better for me at this stage. I read Pyside is a replica of pyqt, same makers qt but it covers all the licensing that PyQt doesnt, and if you learn 1 the other is almost exactly the same. Would this be a good enough reason to give it and pyqt a try? how does it compare to wxPython? also please could you tell me why you suggest wxPython over GTK? what are the factors you looked at, is it better for beginners to start out with a simpler toolkit and decide later on if its enough for them? would you say out of the GUIs we have mentioned, apart from Tkinter, that wxPython is the easiet to pick up yet a lot more complete than Tkinter? > I'm not a big fan of user interface programming in any shape. I started my > career writing embedded software where the UI was a switch and some LEDs. So > i am more interested in the internals of a program than in its outer > appearance, but from necessity I've done a little bit of GUI work and even > less web work. this has interested me. is embedded programming a different field to the type of programming in Python? it sounds like thats more lower level prgroamming better suited to a language like C? is your work today still related to this area? somewhere down the learn, after i have mastered Python i'd definately like to learn about internals of a program, even though the thought of that really scares me:) From crawlzone at gmail.com Wed Sep 5 12:05:23 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 03:05:23 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <504723E3.5070904@gmail.com> On 09/05/2012 02:57 AM, Walter Prins wrote: > Hi Ray, > > On 5 September 2012 10:42, Ray Jones wrote: >> Can someone point me to a page that will clarify the concepts, not just >> try to show me the Python implementation of what I already don't >> understand? ;) > Try the following 2 links which should hopefully help: > > http://www.joelonsoftware.com/articles/Unicode.html > http://nedbatchelder.com/text/unipain.html > "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" Right up my alley! ;) Thank-you. Ray From __peter__ at web.de Wed Sep 5 12:33:46 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 12:33:46 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> Message-ID: Ray Jones wrote: > I have directory names that contain Russian characters, Romanian > characters, French characters, et al. When I search for a file using > glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the > directory names. I thought simply identifying them as Unicode would > clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. That's the representation which is guaranteed to be all-ascii. Python will automatically apply repr() to a unicode string when it is part of a list >>> files = [u"\u0456\u0439\u043e"] # files = glob.glob(unicode_pattern) >>> print files [u'\u0456\u0439\u043e'] To see the actual characters print the unicode strings individually: >>> for file in files: ... print file ... ??? > These representations of directory names are eventually going to be > passed to Dolphin (my file manager). Will they pass to Dolphin properly? How exactly do you "pass" these names? > Do I need to run a conversion? When you write them to a file you need to pick an encoding. > Can that happen automatically within the > script considering that the various types of characters are all mixed > together in the same directory (i.e. # coding: Latin-1 at the top of the > script is not going to address all the different types of characters). the coding cookie tells python how to interpret the bytes in the files, so # -*- coding: utf-8 -*- s = u"???" and # -*- coding: latin1 -*- s = u"???" contain a different byte sequence on disc, but once imported the two strings are equal (and have the same in-memory layout): >>> import codecs >>> for encoding in "latin-1", "utf-8": ... with codecs.open("tmp_%s.py" % encoding.replace("-", ""), "w", encoding=encoding) as f: f.write(u'# -*- coding: %s\ns = u"???"' % encoding)... >>> for encoding in "latin1", "utf8": ... open("tmp_%s.py" % encoding).read() ... '# -*- coding: latin-1\ns = u"\xe4\xf6\xfc"' '# -*- coding: utf-8\ns = u"\xc3\xa4\xc3\xb6\xc3\xbc"' >>> from tmp_latin1 import s >>> from tmp_utf8 import s as t >>> s == t True > While on the subject, I just read through the Unicode info for Python > 2.7.3. The history was interesting, but the implementation portion was > beyond me. I was looking for a way for a Russian 'backward R' to look > like a Russian 'backward R' - not for a bunch of \xxx and \uxxxxx stuff. >>> ya = u"\N{CYRILLIC CAPITAL LETTER YA}" >>> ya u'\u042f' >>> print ya ? This only works because Python correctly guesses the terminal encoding. If you are piping output to another file it will assume ascii and you will see an encoding error: $ cat tmp.py # -*- coding: utf-8 -*- print u"?" $ python tmp.py ? $ python tmp.py | cat Traceback (most recent call last): File "tmp.py", line 2, in print u"?" UnicodeEncodeError: 'ascii' codec can't encode character u'\u042f' in position 0: ordinal not in range(128) You can work around that by specifying the appropriate encoding explicitly: $ python tmp2.py iso-8859-5 | cat ? $ python tmp2.py latin1 | cat Traceback (most recent call last): File "tmp2.py", line 4, in print u"?".encode(encoding) UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in position 0: ordinal not in range(256) From crawlzone at gmail.com Wed Sep 5 13:05:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 04:05:30 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <504731FA.2040903@gmail.com> On 09/05/2012 03:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > >>> files = [u"\u0456\u0439\u043e"] # files = glob.glob(unicode_pattern) >>> print files > [u'\u0456\u0439\u043e'] > > To see the actual characters print the unicode strings individually: > >>>> for file in files: > ... print file > ... > ??? Aha! That works. >> These representations of directory names are eventually going to be >> passed to Dolphin (my file manager). Will they pass to Dolphin properly? > How exactly do you "pass" these names? I will be calling Dolphin with subprocess.call() and passing the directories as command line arguments. > $ cat tmp.py > # -*- coding: utf-8 -*- > print u"?" > $ python tmp.py > ? > $ python tmp.py | cat > Traceback (most recent call last): > File "tmp.py", line 2, in > print u"?" > UnicodeEncodeError: 'ascii' codec can't encode character u'\u042f' in > position 0: ordinal not in range(128) > > You can work around that by specifying the appropriate encoding explicitly: > > $ python tmp2.py iso-8859-5 | cat > ? > $ python tmp2.py latin1 | cat > Traceback (most recent call last): > File "tmp2.py", line 4, in > print u"?".encode(encoding) > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in > position 0: ordinal not in range(256) > But doesn't that entail knowing in advance which encoding you will be working with? How would you automate the process while reading existing files? Ray From __peter__ at web.de Wed Sep 5 13:52:57 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 13:52:57 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> Message-ID: Ray Jones wrote: >> You can work around that by specifying the appropriate encoding >> explicitly: >> >> $ python tmp2.py iso-8859-5 | cat >> ? >> $ python tmp2.py latin1 | cat >> Traceback (most recent call last): >>File "tmp2.py", line 4, in >>print u"?".encode(encoding) >> UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in >> position 0: ordinal not in range(256) >> > But doesn't that entail knowing in advance which encoding you will be > working with? How would you automate the process while reading existing > files? If you don't *know* the encoding you *have* to guess. For instance you could default to UTF-8 and fall back to Latin-1 if you get an error. While decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will always "succeed" as there is one codepoint associated with every possible byte. The result howerver may not make sense. Think for line in codecs.open("lol_cat.jpg", encoding="latin1"): print line.rstrip() From crawlzone at gmail.com Wed Sep 5 16:04:04 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 07:04:04 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> Message-ID: <50475BD4.7020301@gmail.com> On 09/05/2012 04:52 AM, Peter Otten wrote: > Ray Jones wrote: > >> >> But doesn't that entail knowing in advance which encoding you will be >> working with? How would you automate the process while reading existing >> files? > If you don't *know* the encoding you *have* to guess. For instance you could > default to UTF-8 and fall back to Latin-1 if you get an error. While > decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will > always "succeed" as there is one codepoint associated with every possible > byte. The result howerver may not make sense. Think > > for line in codecs.open("lol_cat.jpg", encoding="latin1"): > print line.rstrip() :)) So when glob reads and returns garbley, non-unicode file names....\xb4\xb9....is it making a guess as to which encoding should be used for that filename? Does Linux store that information when it saves the file name? And (most?) importantly, how can I use that fouled up file name as an argument in calling Dolphin? Ray From eryksun at gmail.com Wed Sep 5 16:31:16 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Sep 2012 10:31:16 -0400 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50471E87.60607@gmail.com> References: <50471E87.60607@gmail.com> Message-ID: On Wed, Sep 5, 2012 at 5:42 AM, Ray Jones wrote: > I have directory names that contain Russian characters, Romanian > characters, French characters, et al. When I search for a file using > glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the > directory names. I thought simply identifying them as Unicode would > clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. This is just an FYI in case you were manually decoding. Since glob calls os.listdir(dirname), you can get Unicode output if you call it with a Unicode arg: >>> t = u"\u0456\u0439\u043e" >>> open(t, 'w').close() >>> import glob >>> glob.glob('*') # UTF-8 output ['\xd1\x96\xd0\xb9\xd0\xbe'] >>> glob.glob(u'*') [u'\u0456\u0439\u043e'] Regarding subprocess.Popen, just use Unicode -- at least on a POSIX system. Popen calls an exec function, such as posix.execv, which handles encoding Unicode arguments to the file system encoding. On Windows, the _subprocess C extension in 2.x is limited to calling CreateProcessA with char* 8-bit strings. So Unicode characters beyond ASCII (the default encoding) trigger an encoding error. From crawlzone at gmail.com Wed Sep 5 16:51:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 07:51:52 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <50476708.4060206@gmail.com> On 09/05/2012 07:31 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 5:42 AM, Ray Jones wrote: >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > This is just an FYI in case you were manually decoding. Since glob > calls os.listdir(dirname), you can get Unicode output if you call it > with a Unicode arg: > > >>> t = u"\u0456\u0439\u043e" > >>> open(t, 'w').close() > > >>> import glob > > >>> glob.glob('*') # UTF-8 output > ['\xd1\x96\xd0\xb9\xd0\xbe'] > > >>> glob.glob(u'*') > [u'\u0456\u0439\u043e'] Yes, I played around with that some....in my lack of misunderstanding, I thought that adding the 'u' would pop the characters out at me the way they should appear. Silly me.... ;) > Regarding subprocess.Popen, just use Unicode -- at least on a POSIX > system. Popen calls an exec function, such as posix.execv, which > handles encoding Unicode arguments to the file system encoding. > > On Windows, the _subprocess C extension in 2.x is limited to calling > CreateProcessA with char* 8-bit strings. So Unicode characters beyond > ASCII (the default encoding) trigger an encoding error. subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) Dolphin's error message: 'The file or folder /my_home/testdir/\u044c\u043e\u0432 does not exist' But if I copy the characters as seen by Bash's shell and paste them into my subprocess.call(), Dolphin recognizes the directory just fine. So is Dolphin unicode-dead, or am I missing something? Ray From crawlzone at gmail.com Wed Sep 5 17:04:50 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 08:04:50 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476A12.1000705@gmail.com> On 09/05/2012 07:51 AM, Ray Jones wrote: > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' > > But if I copy the characters as seen by Bash's shell and paste them into > my subprocess.call(), Dolphin recognizes the directory just fine. > > So is Dolphin unicode-dead, or am I missing something? > > > Ray Answering myself here..... I suspect I'm missing something because once within the folders, Dolphin properly recognizes the characters....even so far as writing Arabic and Hebrew "backward"....I wonder.... Sure enough. If I use the glob.glob() non-unicode characters (\x93\xbe) on the command line, Dolphin understands it just fine. Thanks all. Ray (Still wondering where unicode fits into all this....) From __peter__ at web.de Wed Sep 5 17:09:03 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 17:09:03 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> <50475BD4.7020301@gmail.com> Message-ID: Ray Jones wrote: > On 09/05/2012 04:52 AM, Peter Otten wrote: >> Ray Jones wrote: >> >>> >>> But doesn't that entail knowing in advance which encoding you will be >>> working with? How would you automate the process while reading existing >>> files? >> If you don't *know* the encoding you *have* to guess. For instance you >> could default to UTF-8 and fall back to Latin-1 if you get an error. >> While decoding non-UTF-8 data with an UTF-8 decoder is likely to fail >> Latin-1 will always "succeed" as there is one codepoint associated with >> every possible byte. The result howerver may not make sense. Think >> >> for line in codecs.open("lol_cat.jpg", encoding="latin1"): >> print line.rstrip() > :)) > > So when glob reads and returns garbley, non-unicode file > names....\xb4\xb9....is it making a guess as to which encoding should be > used for that filename? Does Linux store that information when it saves > the file name? And (most?) importantly, how can I use that fouled up > file name as an argument in calling Dolphin? Linux stores filenames as bytes always. If you pass a unicode path to os.listdir() it tries to decode the byte sequence of the resulting names or returns bytes if that fails: >>> import sys >>> sys.getfilesystemencoding() 'UTF-8' >>> import os >>> os.mkdir(u"alpha") >>> odd_name = "".join(map(chr, range(128, 144))) # a byte string! >>> os.mkdir(odd_name) >>> os.listdir(u".") # unicode arg triggers unicode output (where possible) [u'alpha', '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'] (Python 3 takes a slightly different approach) Dolphin (at least the version I have tried) can only cope with filenames that can be decoded into unicode using the file system encoding. Neither Python nor Linux care for the "meaning" of the file names. They can process arbitrary byte sequences just fine. From eryksun at gmail.com Wed Sep 5 17:18:27 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Sep 2012 11:18:27 -0400 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: > > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' "\u" only codes a BMP character in unicode literals, i.e. u"unicode literal". You forgot the 'u'. From steve at pearwood.info Wed Sep 5 17:16:37 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Sep 2012 01:16:37 +1000 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50475BD4.7020301@gmail.com> References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> <50475BD4.7020301@gmail.com> Message-ID: <50476CD5.5030006@pearwood.info> On 06/09/12 00:04, Ray Jones wrote: > On 09/05/2012 04:52 AM, Peter Otten wrote: >> Ray Jones wrote: >> >>> >>> But doesn't that entail knowing in advance which encoding you will be >>> working with? How would you automate the process while reading existing >>> files? >> If you don't *know* the encoding you *have* to guess. For instance you could >> default to UTF-8 and fall back to Latin-1 if you get an error. While >> decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will >> always "succeed" as there is one codepoint associated with every possible >> byte. The result howerver may not make sense. Think >> >> for line in codecs.open("lol_cat.jpg", encoding="latin1"): >> print line.rstrip() > :)) > > So when glob reads and returns garbley, non-unicode file > names....\xb4\xb9....is it making a guess as to which encoding should be > used for that filename? No. It is returning the actual bytes stored by the file system. At least that's what it does under Linux. Windows is different. The most common Linux file systems (ext2 and ext3) store file names as bytes, not Unicode. Your desktop environment (KDE, Gnome, Unity, etc.) *may* try to enforce Unicode names, probably using UTF-8, but the file system is perfectly happy to let you create file names using different encodings, or no encoding at all. (I believe the only invalid characters in ext2 or ext3 files are ASCII NULL and FORWARD SLASH. Even newline \n is valid.) > Does Linux store that information when it saves the file name? No. The file system doesn't care about encodings, it just knows about bytes. Your desktop environment might try to enforce UTF-8 encoded file names, but nothing stops some other program from creating a file using a different encoding. For example, suppose I want to name a file "A???" (just because I can). Assuming that KDE uses UTF-8, as it should, then Dolphin or Konqueror will tell the file system: name this file "\x41\xcf\x80\xd0\xaf\xe2\x80\xa0" (Note that the first byte, \x41, is just the ASCII code for uppercase A.) When another UTF-8 aware program sees that byte-string, it will decode it back to "A???" and I will be happy that my files have cool names. But then some day I use another program, which knows nothing about UTF-8 but thinks I'm running an Apple Mac in Greece back in 1990 or thereabouts. It sees the same sequence of bytes, and decodes it using the MacGreek encoding, which gives "A???????" instead, and I'll be unhappy because my cool file names look like rubbish. But the actual file names (stored as bytes) are the same. > And (most?) importantly, how can I use that fouled up > file name as an argument in calling Dolphin? Just pass it as the file name and hope for the best :) Seriously, I *expect* (but don't know for sure) that just passing the raw bytes to Dolphin will be fine, it will decode them as it sees fit. Try it and see. -- Steven From crawlzone at gmail.com Wed Sep 5 17:23:51 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 08:23:51 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476E87.6020400@gmail.com> On 09/05/2012 08:18 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: >> subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) >> >> Dolphin's error message: 'The file or folder >> /my_home/testdir/\u044c\u043e\u0432 does not exist' > "\u" only codes a BMP character in unicode literals, i.e. u"unicode > literal". You forgot the 'u'. What with all the 'u's floating around in the unicode escape characters, I didn't realize I needed to add yet another one! You're right. It worked. Thank-you everyone. Ray From steve at pearwood.info Wed Sep 5 17:25:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Sep 2012 01:25:51 +1000 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476EFF.7060102@pearwood.info> On 06/09/12 00:51, Ray Jones wrote: > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' That's because you're telling Dolphin to look for a file literally called: BACKSLASH u ZERO FOUR FOUR c BACKSLASH ... Either use the actual unicode string, which you can write like either of these: u'/my_home/testdir/???' u'/my_home/testdir/\u044c\u043e\u0432' (note the leading u' delimiter, not just ') or try using the raw bytes instead: '/my_home/testdir/\xd1\x8c\xd0\xbe\xd0\xb2' (assuming Dolphin is using UTF-8) and hope Dolphin can decode them correctly. (It better.) -- Steven From breamoreboy at yahoo.co.uk Wed Sep 5 18:12:43 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Sep 2012 17:12:43 +0100 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: On 05/09/2012 16:18, eryksun wrote: > On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: >> >> subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) >> >> Dolphin's error message: 'The file or folder >> /my_home/testdir/\u044c\u043e\u0432 does not exist' > > "\u" only codes a BMP character in unicode literals, i.e. u"unicode > literal". You forgot the 'u'. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > For the record the u prefix for literals was taken out of Python 3 but has been reinstated in Python 3.3, see http://docs.python.org/dev/whatsnew/3.3.html#pep-414-explicit-unicode-literals -- Cheers. Mark Lawrence. From ramit.prasad at jpmorgan.com Wed Sep 5 19:22:22 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 5 Sep 2012 17:22:22 +0000 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47416646EA0@SCACMX008.exchad.jpmchase.net> From: Matthew Ngaha [snip] > i feel confident using Python now but im still not > sure which direction i want to go in. I would at some point like to > learn how to use GUIs and a web Framework(Django). But i don't know > which of the 2 to start out with. > > a) IF you happen to have used both, which one fills you with joy and > is more fun for you to program with, GUI programming, or web related / > Framework programming? > > b) which was easier and less complex for you to learn? or should i say > had a lower learning curve? i ask this because the sooner i get an > understanding of one, i can maybe give the other one a go. But if it's > too hard i usually give 100% to it and never try learning anything > else until it computes. [snip] > Before i try to learn either, GUIs or a web Framework, i was looking > into maybe getting a deeper understanding of OOP. my tutorial only > covered it briefly. > > f) would this be a good idea tackling OOP next before the other 2, or > is this a skill you master with more programming experience? > > ok my last question is not so important:) im just curious as i grow > more fond of programming. well i keep reading Python is an all-purpose > general programming language(web frameworks, desktop apps, > science/maths etc..). I notice Java has similar features so should > also be considered an all-purpose general programming language. my > question is: > > g) not a comparison in 1 specific area, but which language is better > or more suited to all around all-purpose quality. > > thanks guys I would second the wxPython framework as a popular and fully featured framework; being popular means it will likely be easier to get help on it. I was *not* a fan of GUI in Java using Swing. Stick with Python, but this list is probably biased. :) The real question is what do you want to *do* with it? The purpose or intent probably matters more than which you pick. If you are learning for the sake of learning I would probably point you in the direction of web frameworks. In my personal opinion there is more opportunity there. Not to mention that the basics you learn in web frameworks will help you design web sites in other languages as well. Whereas desktop applications will probably be a lot more specific to the framework/language and project. That is just my personal observations. Others (including you) may disagree. Ramit From alan.gauld at btinternet.com Wed Sep 5 19:40:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Sep 2012 18:40:20 +0100 Subject: [Tutor] help me decide In-Reply-To: References: <5046A014.6030907@btinternet.com> Message-ID: On 05/09/12 11:04, Matthew Ngaha wrote: > also please could you tell me why you suggest wxPython over GTK? Support, there are probably more beginner friendly resources for wxPython than for GTk, although that is changing. > that wxPython is the easiet to pick up yet a lot more complete than > Tkinter? I can't really comment since Tkinter and wxPython are the only two i've really used. I did a PyQt tutorial a long time back and have never used GTk at all so can't really comment on them. > this has interested me. is embedded programming a different field to > the type of programming in Python? Yes, it is usually done using assembler and C or C++. Some embedded work nowadays is done in Java - a reflection of how cheap memory has become! > is your work today still related to this area? Not really, my company (a big telecomms business) got out of making bespoke hardware and now buys in standard commercial kit. My core job these days is as an "Enterprise Architect" and I do almost no programming now. I determine what IT systems are needed, the interfaces between them and review the high level systems designs. I act as a bridge between the business folks and the IT tech heads... I 'own' around 250 systems and oversee the technical work of around 1000 developers, with about 20 projects running at any one time. Python programming has become more of a hobby and personal productivity tool nowadays. It keeps me sane and connected! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Sep 5 19:49:05 2012 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 05 Sep 2012 10:49:05 -0700 Subject: [Tutor] help me decide In-Reply-To: References: <5046A014.6030907@btinternet.com> Message-ID: <50479091.4030101@alchemy.com> On 05-Sep-12 10:40, Alan Gauld wrote: > On 05/09/12 11:04, Matthew Ngaha wrote: > >> also please could you tell me why you suggest wxPython over GTK? > > Support, there are probably more beginner friendly resources for > wxPython than for GTk, although that is changing. Yeah, and wxPython is a large, comprehensive package that should handle all of your GUI needs and then some. I wrote one tool using wxPython and was quite happy with the results, and pleasantly surprised at the performance of widget updates and refreshes it achieved, even for the bits in pure Python. >> that wxPython is the easiet to pick up yet a lot more complete than >> Tkinter? Not sure about that. I started Tk programming back (way back) in my Tcl/Tk phase years ago, so I'm really used to Tk and that may bias me, but I'd say Tkinter is a lot easier to learn than wxPython, partly because it's smaller with fewer moving parts to tweak. And yet, Tkinter is complete enough to be quite satisfactory for a lot of applications. Even after using wx, I've gone back to Tkinter when it sufficed for my applications, since it's a little easier to use and is a lot easier to distribute, coming for free with Python and all that. >> this has interested me. is embedded programming a different field to >> the type of programming in Python? > > Yes, it is usually done using assembler and C or C++. > Some embedded work nowadays is done in Java - a reflection > of how cheap memory has become! Right. Although Java here doesn't necessarily mean the JVM is running on the embedded machine; it could be Java source code compiled down to something a compact runtime can execute. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From dwightdhutto at gmail.com Wed Sep 5 21:45:40 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 5 Sep 2012 15:45:40 -0400 Subject: [Tutor] help me decide In-Reply-To: <50479091.4030101@alchemy.com> References: <5046A014.6030907@btinternet.com> <50479091.4030101@alchemy.com> Message-ID: No matter what the kit used for GUI, make sure it's well documented, and has plenty of tuts/docs. I used tkinter, and wxpython, and like the widget set/cross OS usages in wxpython better. However, with more experience, now I'm moving toward the Blender Game Engine to give more feel, and a 3-d pop to my apps through it's Python API. So, consider that over time your preferences will change in relation to your knowledge, and the wisdom that comes with the application of this knowledge...experience. Also, don't get hung up on just python. Always take a beginner's guide or two with a well referenced language(all the way down to assembly/machine language) for familiarity. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Wed Sep 5 23:15:25 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Wed, 5 Sep 2012 16:15:25 -0500 (CDT) Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: On Tue, 4 Sep 2012, Matthew Ngaha wrote: > a) IF you happen to have used both, which one fills you with joy and > is more fun for you to program with, GUI programming, or web related / > Framework programming? Honestly - both. It's really a highly subjective question and depends what you want to do (although with modern browsers like Google Chrome and Firefox the line is becoming more and more blurry). If you want to provide an application that requires no interaction with the outside world, a GUI is probably a better fit and has the advantage that you'll probably only be using one language - in this case, Python ;) But if you begin doing web programming then you'll start to learn about HTML, JavaScript, and CSS (all valuable technologies and look like they'll be here to stay!) > b) which was easier and less complex for you to learn? or should i say > had a lower learning curve? i ask this because the sooner i get an > understanding of one, i can maybe give the other one a go. But if it's > too hard i usually give 100% to it and never try learning anything > else until it computes. Honestly, I picked up learning HTML before I learned to actually program. That's what got me interested, was being able to make small changes in the text and see large changes happen in my page. I would say as far as complexity goes, learning basic GUI programming has less "pieces". But again, both directions are perfectly valid and valuable things to learn. > > my tutorial had a small section on tkinter. I have now looked for some > tutorials and noticed Python tutorials on both tkinter and Tk. As i > understand they are not the same thing but tkinter is like the > interface of Tk? my question is: I'm sure someone has addressed this already, but Tkinter is the Python bindings for Tk/Tcl. It allows you to write Python code to do Tk things. > c) which tutorial would be better to study, Tkinter or Tk? and what > exactly is the difference? why do they have separate tutorials? You would definitely want to focus on Tkinter - and there are quite a few good tutorials, including the effbot tutorial. That's a reference I turn to almost any time I'm doing Tkinter. > i looked at some pyQT articles, but its coding looks less organised > than Tkinter. I wouldn't say it's less organized, but there's a *lot* more to Qt than Tkinter. > d) is this true? is Tkinter a lot more straight forward and Python friendly? One thing I noticed about Qt is that you'll be using the Q key a lot. So your left pinky (assuming two hands and a Qwerty keyboard) will get a massive workout. It was super awkward for me while I was learning it. > e) Does pyQT have grids (rows and columns) to place your widgets on > like Tkinter, or do you have to use x and y axis to position widgets > etc..? You can do both... In terms of GUI frameworks, I rank them in this order from least- to most-complex: 1. Tkinter 2. wxPython 3. PyGTK+ 4. PyQt Tkinter is kinda the raw materials. You get a few widgets (though that's really grown in the past few years with ttk and tix), and some building blocks. wxPython gives you some tools to interface with the native UI - so if you set it up right, the same Python application will look like a "real" Windows app, a "real" Gnome(GTK) app, or what have you. PyGTK seems to me like it gives you a bit more than wx. Again, this is largely subjective. I used to do quite a bit with PyGTK. The normal GTK documentation maps quite well, though it can be a little difficult to figure out why something is doing what it's doing. PyQt... well that's everything and the kitchen sink. I mean seriously - there's a timer widget built in! It's quite the powerhouse, but ultimately I didn't like using my left pinky to hit the Q key so much. > Before i try to learn either, GUIs or a web Framework, i was looking > into maybe getting a deeper understanding of OOP. my tutorial only > covered it briefly. > > f) would this be a good idea tackling OOP next before the other 2, or > is this a skill you master with more programming experience? I personally would consider OOP fundamentals essential to learning GUI programming with anything besides Tkinter. It's pretty easy to write procedural-ish Tkinter code. > ok my last question is not so important:) im just curious as i grow > more fond of programming. well i keep reading Python is an all-purpose > general programming language(web frameworks, desktop apps, > science/maths etc..). I notice Java has similar features so should > also be considered an all-purpose general programming language. my > question is: > > g) not a comparison in 1 specific area, but which language is better > or more suited to all around all-purpose quality. I'm sure the other folks have mentioned that Java is an extremely verbose language that (at least to me) is entirely too noisy. I did *not* enjoy the two semesters in college that I had to use it. The term Martin Fowler uses to describe it is a "guiding" language. That means that Java has a certain way to do things and you don't really have a choice if you'd like to do it different. Python is an "enabling" language - which in my words means "it's a language that gets out of your way". My experience is that when I write Python code I can express the solution to a problem the way I want to. If it's easier to express the solution in an OOP way, I can do that. If it's easier to express procedurally, or even functionally, I can do that too. Which meant that it's easier to just get stuff done. I don't have to worry about how I can shoehorn the problem into something that the language can solve - I can just solve it. So I find great joy in writing Python code, and encourage everyone to learn it. My recommendation for you would be to learn some OOP basics, and once you feel comfortable around objects start learning Tkinter. Unless you really want to do some web programming, in which case, do that ;) HTH, Wayne From afowler2 at broncos.uncfsu.edu Thu Sep 6 00:10:35 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 5 Sep 2012 22:10:35 +0000 Subject: [Tutor] Student Class Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> I need help creating a student class. I am suppose to create a student class with there first name, last name, credits and gpa. Can anybody help me get started? Below is what needs to be included. For number one, is the variables suppose to be parameters? for instance, class Student: def __init__(self, name, hours, gpa): self.name = name 1. four instance variables: firstName (a string), lastName (a string), numCredits (an integer), gpa (a float); 2. an accessor method for each instance variable; 3. a mutator method for each instance variable; 4. an __init__ method that sets all the instance variables to values provided by the user; 5. a __str__ method that returns a string that contains all the data of the object in the order: firstName, lastName, numCredits, gpa. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Thu Sep 6 00:42:15 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 5 Sep 2012 18:42:15 -0400 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Wed, Sep 5, 2012 at 6:10 PM, Ashley Fowler wrote: > I need help creating a student class. I am suppose to create a student > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? > > for instance, > class Student: > def __init__(self, name, hours, gpa): > self.name = name > > self.name is bringing a more global variable into the class, so it can > be changed within the class, but remain the same outside of the class > called. > > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); > > Then you need the following in init: def __init__(self, first_name,last_name, numCredits,hours, gpa): self.first_name = first_name self.last_name = last_name self.numCredits = numCredits self.hours = hours self.gpa = gpa def whatever(self.first_name): self.first_name = "Bob" return self.first_name > 2. an accessor method for each instance variable; > > student = Student(first_name,last_name, numCredits,hours, gpa) > student.whatever(): > > > 3. a mutator method for each instance variable; > > Define mutator, is that just to change? > 4. an __init__ method that sets all the instance variables to values > provided by the user; > > look above at the init. > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. > > return : "%s , %s, %i, %i, i%" % (self.first_name, > self.last_name, self.numCredits, > self.hours, self.gpa ) > or something like that. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 01:39:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 00:39:25 +0100 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 05/09/12 23:10, Ashley Fowler wrote: > I need help creating a student class. We don't do your homework for you we will only offer hints. So you need to show us what you are trying and we will try to steer you to something better. > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? Normally yes, you'd make those variables the input parameters to the __init__() method. > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); These would normally be defined inside __init__() > 2. an accessor method for each instance variable; > 3. a mutator method for each instance variable; This is not good Python practice. It smells like Java... In python it's customary to access attributes directly. If you really want to use access methods then you should create a 'property' > 4. an __init__ method that sets all the instance variables to values > provided by the user; > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. These are fairly standard. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From afowler2 at broncos.uncfsu.edu Thu Sep 6 01:43:11 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 5 Sep 2012 23:43:11 +0000 Subject: [Tutor] Student Class In-Reply-To: References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com>, Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> so far i have: class Student: def __init__(self, first_name, last_name, numCredits, gpa): self.first_name = first_name self.last_name = last_name self.numCredits = numCredits self.gpa = gpa def getFirstname(self): return self.first_name def getLastname(self): return self.last_name def getNumCredits(self): return self.numCredits def getGpa(self): return self.gpa def setFirstname(self, first_name): self.first_name = first def setLastname(self, last_name): self.last_name = last def setNumcredits(self, numCredits): self.NumCredits = credit def setGpa(self, gpa): self.gpa = gpa def __str__(self): return (self.first_name, self.last_name, self.numCredits, self.gpa) ________________________________________ From: Tutor [tutor-bounces+afowler2=broncos.uncfsu.edu at python.org] on behalf of Alan Gauld [alan.gauld at btinternet.com] Sent: Wednesday, September 05, 2012 11:39 PM To: tutor at python.org Subject: Re: [Tutor] Student Class On 05/09/12 23:10, Ashley Fowler wrote: > I need help creating a student class. We don't do your homework for you we will only offer hints. So you need to show us what you are trying and we will try to steer you to something better. > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? Normally yes, you'd make those variables the input parameters to the __init__() method. > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); These would normally be defined inside __init__() > 2. an accessor method for each instance variable; > 3. a mutator method for each instance variable; This is not good Python practice. It smells like Java... In python it's customary to access attributes directly. If you really want to use access methods then you should create a 'property' > 4. an __init__ method that sets all the instance variables to values > provided by the user; > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. These are fairly standard. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From me at staticsafe.ca Thu Sep 6 05:00:15 2012 From: me at staticsafe.ca (staticsafe) Date: Wed, 05 Sep 2012 23:00:15 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() Message-ID: <504811BF.2030506@staticsafe.ca> Hello, I am running Python 2.6.6 on a Debian Squeeze system. I am using two modules in this bit of code - datetime and python-tvrage (available on pypy here: http://pypi.python.org/pypi/python-tvrage/). My goal is to find the time remaining until a certain show airs. Here is some code I have written so far: #!/usr/bin/env python from tvrage import quickinfo from datetime import tzinfo, timedelta, datetime showinfo = quickinfo.fetch("Warehouse 13") nextairdate = showinfo['RFC3369'] now = datetime.now().isoformat() Now for my question/problem. In [68]: showinfo['RFC3339'] Out[68]: '2012-09-10T21:00:00-4:00' In [72]: datetime.now().isoformat() Out[72]: '2012-09-05T22:47:46.061688' isoformat() is in a different format than the value returned by the API. My question is how would one format both values so that I can perform a timedelta on them as is the purpose of my code? I hope I have provided the right amount of detail for my question. Thanks, -- staticsafe http://staticsafe.ca From eryksun at gmail.com Thu Sep 6 08:05:34 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 02:05:34 -0400 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Wed, Sep 5, 2012 at 7:43 PM, Ashley Fowler wrote: > > class Student: Are you using Python 3? If not, Student should explicitly inherit from object. > def __init__(self, first_name, last_name, numCredits, gpa): > self.first_name = first_name > self.last_name = last_name > self.numCredits = numCredits > self.gpa = gpa Your requirements specify firstName and lastName, not first_name and last_name. > def getFirstname(self): > return self.first_name All of the function definitions below __init__ need to be dedented one level. You have them defined in __init__. > def setFirstname(self, first_name): > self.first_name = first 'first' isn't defined. You named the parameter "first_name". > def setLastname(self, last_name): > self.last_name = last Neither is 'last' defined. > def setNumcredits(self, numCredits): > self.NumCredits = credit Neither is 'credit' defined. Plus this method creates a new attribute named NumCredits. The name in __init__ is numCredits. > def __str__(self): > return (self.first_name, self.last_name, self.numCredits, self.gpa) The __str__ method absolutely needs to return a string. Use string formatting via 'format' or the old modulo formatting. http://docs.python.org/py3k/library/string.html#format-examples http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations From tokyo.rook at gmail.com Thu Sep 6 09:21:05 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Thu, 6 Sep 2012 03:21:05 -0400 Subject: [Tutor] Hey.need help on time Message-ID: been trying to change this so it wont use my server time. but my actual time here in the us.EST. havent been able to figure it out def sstime(user, body, m): os.environ['TZ'] = 'US/Eastern' tstr1 = time.strftime("%a, %b-%d-%Y", time.tzset()) tstr2 = time.strftime("%I:%M:%S %p", time.tzset()) tstr3 = time.strftime("%Z", time.tzset()) return Html("Today is %s and The current time is %s (%s)" % (tstr1, tstr2, tstr3)) -- ~~Austin From eryksun at gmail.com Thu Sep 6 09:35:54 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 03:35:54 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() In-Reply-To: <504811BF.2030506@staticsafe.ca> References: <504811BF.2030506@staticsafe.ca> Message-ID: On Wed, Sep 5, 2012 at 11:00 PM, staticsafe wrote: > > In [68]: showinfo['RFC3339'] > Out[68]: '2012-09-10T21:00:00-4:00' You can parse the ISO format using the dateutil module: http://labix.org/python-dateutil >>> from dateutil.parser import parse >>> show_time = parse('2012-09-10T21:00:00-4:00') This produces a time-zone aware datetime object. You can pass its tzinfo to datetime.now() to get the current time as an aware datetime object: >>> now = datetime.now(show_time.tzinfo) Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo. It doesn't matter if you're only interested in the timedelta. From __peter__ at web.de Thu Sep 6 09:39:19 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 09:39:19 +0200 Subject: [Tutor] Formatting questions regarding datetime.isoformat() References: <504811BF.2030506@staticsafe.ca> Message-ID: staticsafe wrote: > Hello, > > I am running Python 2.6.6 on a Debian Squeeze system. I am using two > modules in this bit of code - datetime and python-tvrage (available on > pypy here: http://pypi.python.org/pypi/python-tvrage/). > > My goal is to find the time remaining until a certain show airs. Here is > some code I have written so far: > > #!/usr/bin/env python > from tvrage import quickinfo > from datetime import tzinfo, timedelta, datetime > > showinfo = quickinfo.fetch("Warehouse 13") > nextairdate = showinfo['RFC3369'] > now = datetime.now().isoformat() > > Now for my question/problem. > > In [68]: showinfo['RFC3339'] > Out[68]: '2012-09-10T21:00:00-4:00' > > In [72]: datetime.now().isoformat() > Out[72]: '2012-09-05T22:47:46.061688' > > isoformat() is in a different format than the value returned by the API. > My question is how would one format both values so that I can perform a > timedelta on them as is the purpose of my code? > > I hope I have provided the right amount of detail for my question. After some trial and error: import dateutil.parser # python-dateutil import pytz # python-tz import datetime show_start = dateutil.parser.parse("2012-09-10T21:00:00-0400") now = datetime.datetime.now(pytz.timezone("EST")) print "show starts: ", show_start print "current time:", now print "days to go: ", show_start - now (Caveat: I'm using Python 2.7) From eryksun at gmail.com Thu Sep 6 09:51:36 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 03:51:36 -0400 Subject: [Tutor] Hey.need help on time In-Reply-To: References: Message-ID: On Thu, Sep 6, 2012 at 3:21 AM, Keitaro Kaoru wrote: > been trying to change this so it wont use my server time. but my > actual time here in the us.EST. havent been able to figure it out > > def sstime(user, body, m): > os.environ['TZ'] = 'US/Eastern' Now just call time.tzset(), and it should work. > tstr1 = time.strftime("%a, %b-%d-%Y", time.tzset()) I don't know what you're doing here. strftime() uses localtime() if you don't provide a time tuple. time.tzset() just returns None. From ahmetcan196 at gmail.com Thu Sep 6 09:59:37 2012 From: ahmetcan196 at gmail.com (Ahmet Can KEPENEK) Date: Thu, 6 Sep 2012 10:59:37 +0300 Subject: [Tutor] Python Xmpp Received Message Message-ID: I wrote application with xmpp. It sending message from gtalk. I want to print received message. How can i do? My application short code as follows. def process_message(): client = xmpp.Client('gmail.com') client.connect( server=('talk.google.com',5223) ) client.auth(user,passwd, 'botty') to = raw_input("to: "); if client: message = raw_input("message: ") client.send( xmpp.Message( to,message ) ) if __name__ == "__main__": user = raw_input("User: ") passwd = getpass.getpass("Pass: ") process_message() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 10:17:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:17:05 +0100 Subject: [Tutor] Python Xmpp Received Message In-Reply-To: References: Message-ID: On 06/09/12 08:59, Ahmet Can KEPENEK wrote: > I wrote application with xmpp. It sending message from gtalk. I want to > print received message. How can i do? This mailing list is really for people learning Python and its standard library. Your question is mainly about xmpp which I assume is some kind of Google API? Whether you get an answer will depend on how lucky you are as to whether anyone here has used xmpp. You will likely get a better response on an xmpp forum or even on the main Python mailing list/newsgroup: comp.lang.python HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ianodonovan63 at gmail.com Tue Sep 4 21:36:28 2012 From: ianodonovan63 at gmail.com (Ian o donovan) Date: Tue, 4 Sep 2012 20:36:28 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: Hey, I am writing this to you because I want to know could you help. My school is doing enterprise and I want to enter. I really want to make a program that will clean up your desktop E.G put files you haven't used for a while into a folder and delete your trash they are just a few ideas. I am trying to learn programming but I live in Ireland and where I live they is not much access to courses so I have to wait till college to learn programming. I have tried to learn some of python through on-line tutorials but find it hard So what I am asking is could you help me make a program if not I understand as I can imagine ye are very busy people. Thanks for reading this. Ian Lawlor From jacklittlemc at yahoo.com Mon Sep 3 16:39:58 2012 From: jacklittlemc at yahoo.com (Jack Little) Date: Mon, 3 Sep 2012 07:39:58 -0700 (PDT) Subject: [Tutor] Help Message-ID: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> > Ok, I am somewhat new to python, and I am making a text-based RPG. I get a > weird error with this code: > > > #A Python text-RPG > #A Jak Production > #APOC > global ammo > global health > global lives > global exp > global food > ammo=55 > health = 100 > lives=10 > exp = 0 > food = 30 > > def part1(): >? ? print "50 Days After The Outbreak:You are standing outside of the Empire > State Building." >? ? print "Vines, plants, dirt, and grime cover its once-regal surfaces. > Huh." >? ? print "I guess if 80% of the world is dead, more people are concerned > about survival than sightseeing.God." >? ? print "Generally,us survivors tend to band together. Mostly? it is for > good. Not the bandits." >? ? print "? Bandit:'Hey you! What you got in that bag?" >? ? print "I recognized this Bandit as Sam Cabelo. He was the janitor at my > office building. Not the nicest fellow." >? ? answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' > button.") >? ? if answer == "SHOW" or answer == "Show" or answer == "show": >? ? ? ? print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He > says this like a threat, reinforced by that revolver in his hand" >? ? ? ? answer2 = raw_input("Type either Hand it over or flee") >? ? ? ? if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 > == "hand it over": >? ? ? ? ? ? print "Bandit: Good Job.. Go on now" >? ? ? ? ? ? ammo=ammo-15 >? ? ? ? ? ? food=food-10 >? ? ? ? ? ? return answer3 >? ? ? ? if answer2 == "FLEE" or answer2 == "Flee" or answer2 == "flee": >? ? ? ? ? ? print "He shot you" >? ? ? ? ? ? lives=lives-1 >? ? ? ? else: >? ? ? ? ? ? print "TYPE? SOMETHING CORRECTLY" >? ? ? ? ? ? return part1 > >? ? elif answer == "run away" or "Run Away" or "RUN AWAY": >? ? ? ? print "He shot you... hee hee hee" >? ? ? ? print "When the input comes up again, type a differet answer" >? ? else: >? ? ? ? print "You didn't type Show or run away." >? ? ? ? part1() > > part1() > > > Here is my error, if it helps > > Traceback (most recent call last): >? File "C:\Users\Jack\Desktop\game2.py", line 45, in >? ? part1() >? File "C:\Users\Jack\Desktop\game2.py", line 28, in part1 >? ? ammo=ammo-15 > UnboundLocalError: local variable 'ammo' referenced before assignment > > > Thanks, > Jack Little? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 6 10:23:23 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 04:23:23 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() In-Reply-To: <504855DE.4090303@davea.name> References: <504811BF.2030506@staticsafe.ca> <504855DE.4090303@davea.name> Message-ID: On Thu, Sep 6, 2012 at 3:50 AM, Dave Angel wrote: > On 09/06/2012 03:35 AM, eryksun wrote: >> >> Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo. >> It doesn't matter if you're only interested in the timedelta. > > Actually, it can matter. Whenever possible, produce all times as UTC > and do your manipulations (eg. difference) in that space. With local > time, there are times that don't exist and times that are ambiguous, one > in the fall and one in the spring, due to setting the clock forward or back. > > i don't know for sure if it matters here, but I've found it's better to > work that way. These are aware datetime objects. See the datetime docs for supported operations, case 3, timedelta = datetime1 - datetime2: http://docs.python.org/library/datetime#datetime.datetime.tzinfo From jason.j.fremouw at gmail.com Tue Sep 4 20:52:04 2012 From: jason.j.fremouw at gmail.com (Jason Fremouw) Date: Tue, 4 Sep 2012 13:52:04 -0500 Subject: [Tutor] Python 2.7.3, Pygame, and LiveWires Message-ID: Hello, My name is Jason Fremouw. I recently began a Structured Programming course using Python as the tool with which we'll learn. The media packages listed above come as add-ons in my text book but are not compatible with 2.7. Are these now built into the latest build of Python or are they listed as different downloads on Python.org? Any help would be greatly appreciated! Thank you. Best, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From sales at myspcworks.com Thu Sep 6 06:43:43 2012 From: sales at myspcworks.com (Sales) Date: Wed, 5 Sep 2012 21:43:43 -0700 Subject: [Tutor] python wifi Message-ID: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Hello, I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: easy_install python_wifi-0.5.0-py2.5.egg I also tried: sudo easy_install python_wifi-0.5.0-py2.5.egg I pasted the output error below. I'm not familiar with easy_install or python wifi. What am I doing wrong here? thanks! Downloading http://pypi.python.org/packages/any/p/python-wifi/python_wifi-0.5.0-py2.5.egg#md5=d7995ad357387d3c2f8b13bcac5c4e20, Processing python_wifi-0.5.0-py2.5.egg Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_wifi-0.5.0-py2.5.egg Moving python_wifi-0.5.0-py2.5.egg to /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages python-wifi 0.5.0 is already the active version in easy-install.pth Installed /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_wifi-0.5.0-py2.5.egg Processing dependencies for python-wifi==0.5.0 Searching for python-wifi==0.5.0 Reading http://pypi.python.org/simple/python-wifi/ Reading http://pythonwifi.wikispot.org Reading https://developer.berlios.de/projects/pythonwifi/ Reading http://www.romanofski.de/downloads/pywifi No local packages or download links found for python-wifi==0.5.0 Best match: None Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/bin/easy_install", line 8, in load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1712, in main File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1716, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 211, in run File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 422, in easy_install File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 478, in install_item File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 519, in process_distribution File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 563, in resolve File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 799, in best_match File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 811, in obtain File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 434, in easy_install File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/package_index.py", line 475, in fetch_distribution AttributeError: 'NoneType' object has no attribute 'clone' From crawlzone at gmail.com Thu Sep 6 10:25:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 01:25:52 -0700 Subject: [Tutor] Hey.need help on time In-Reply-To: References: Message-ID: <50485E10.3040605@gmail.com> On 09/06/2012 12:51 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 3:21 AM, Keitaro Kaoru wrote: >> been trying to change this so it wont use my server time. but my >> actual time here in the us.EST. havent been able to figure it out >> >> def sstime(user, body, m): >> os.environ['TZ'] = 'US/Eastern' > Now just call time.tzset(), and it should work. Why the additional step of calling time.tzset()? Once os.environ['TZ'] is set, I've found that time.localtime() responds to the new TZ without anything extra. Is that a difference in versions (2.7.3 here)? Ray From breamoreboy at yahoo.co.uk Thu Sep 6 10:27:30 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Sep 2012 09:27:30 +0100 Subject: [Tutor] math description In-Reply-To: References: Message-ID: On 29/08/2012 21:20, damjan kuzmic wrote: > Hello, > i would like to know how to write a formula that in excell looks like this: > > A / EXP(-LN(2) * t) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Start here http://docs.python.org/tutorial/ -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Thu Sep 6 10:29:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:29:19 +0100 Subject: [Tutor] apologies for any duplicate mails coming through Message-ID: I've just been into the admin interface and flushed a heap of messages in the moderators queue. I hadn't logged in for a while and quite a stack had built up - mostly spam... :-( Some were a few weeks old so apologies if some of them have already been seen and dealt with. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 10:35:37 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 01:35:37 -0700 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: <50486059.5080604@gmail.com> On 09/03/2012 07:39 AM, Jack Little wrote: > > Ok, I am somewhat new to python, and I am making a text-based RPG. I get a > > weird error with this code: > > > > > > #A Python text-RPG > > #A Jak Production > > #APOC > > global ammo > > global health > > global lives > > global exp > > global food > > ammo=55 > > health = 100 > > lives=10 > > exp = 0 > > food = 30 > > > > def part1(): > > print "50 Days After The Outbreak:You are standing outside of the Empire > > State Building." > > print "Vines, plants, dirt, and grime cover its once-regal surfaces. > > Huh." > > print "I guess if 80% of the world is dead, more people are concerned > > about survival than sightseeing.God." > > print "Generally,us survivors tend to band together. Mostly it is for > > good. Not the bandits." > > print " Bandit:'Hey you! What you got in that bag?" > > print "I recognized this Bandit as Sam Cabelo. He was the janitor at my > > office building. Not the nicest fellow." > > answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' > > button.") > > if answer == "SHOW" or answer == "Show" or answer == "show": > > print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He > > says this like a threat, reinforced by that revolver in his hand" > > answer2 = raw_input("Type either Hand it over or flee") > > if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 > > == "hand it over": > > print "Bandit: Good Job.. Go on now" > > ammo=ammo-15 > > I'll take a stab at it. You are using attempting to modify a global variable within a procedure. Procedure variables are separate from global variables. Global variables must be passed into a procedure using something on the order of 'part1(ammo)', and then returned back from the procedure with a 'return ' Ray From alan.gauld at btinternet.com Thu Sep 6 10:35:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:35:35 +0100 Subject: [Tutor] math description In-Reply-To: References: Message-ID: On 29/08/12 21:20, damjan kuzmic wrote: > Hello, > i would like to know how to write a formula that in excell looks like this: > > A / EXP(-LN(2) * t) Start by breaking it down from the inside out. LN(2) is log(2) in Python, which is found in the math module so you need import math too. negation ( -LN() ) and multiplication are builtin (* t) EXP() is exp(), also in the math module. division is built in (although I'm not sure if Excel / is integer or 'real' division, given the nature of the values I'll assume its real... So the final expression should look like import math ... value = A/math.exp(-math.log(2) * t) Which isn't too different to Excel. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Thu Sep 6 10:36:59 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 04:36:59 -0400 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On Fri, Aug 17, 2012 at 4:11 PM, Matthew Love wrote: > def inventory(self): > self.inventory = ["torch"] > return self.inventory What is 'self.inventory' before you call inventory(), and what is it afterwards? A quick fix would be to name the list "_inventory" and return self._inventory. From d at davea.name Thu Sep 6 10:51:51 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 04:51:51 -0400 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: <50486427.8020102@davea.name> On 09/03/2012 10:39 AM, Jack Little wrote: >> Ok, I am somewhat new to python, and I am making a text-based RPG. I get a >> weird error with this code: >> >> >> #A Python text-RPG >> #A Jak Production >> #APOC >> global ammo >> global health >> global lives >> global exp >> global food >> ammo=55 >> health = 100 >> lives=10 >> exp = 0 >> food = 30 >> >> def part1(): >> print "50 Days After The Outbreak:You are standing outside of the Empire >> State Building." >> print "Vines, plants, dirt, and grime cover its once-regal surfaces. >> Huh." >> print "I guess if 80% of the world is dead, more people are concerned >> about survival than sightseeing.God." >> print "Generally,us survivors tend to band together. Mostly it is for >> good. Not the bandits." >> print " Bandit:'Hey you! What you got in that bag?" >> print "I recognized this Bandit as Sam Cabelo. He was the janitor at my >> office building. Not the nicest fellow." >> answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' >> button.") >> if answer == "SHOW" or answer == "Show" or answer == "show": >> print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He >> says this like a threat, reinforced by that revolver in his hand" >> answer2 = raw_input("Type either Hand it over or flee") >> if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 >> == "hand it over": >> print "Bandit: Good Job.. Go on now" >> ammo=ammo-15 >> food=food-10 >> return answer3 >> if answer2 == "FLEE" or answer2 == "Flee" or answer2 == "flee": >> print "He shot you" >> lives=lives-1 >> else: >> print "TYPE SOMETHING CORRECTLY" >> return part1 >> >> elif answer == "run away" or "Run Away" or "RUN AWAY": >> print "He shot you... hee hee hee" >> print "When the input comes up again, type a differet answer" >> else: >> print "You didn't type Show or run away." >> part1() >> >> part1() >> >> >> Here is my error, if it helps >> >> Traceback (most recent call last): >> File "C:\Users\Jack\Desktop\game2.py", line 45, in >> part1() >> File "C:\Users\Jack\Desktop\game2.py", line 28, in part1 >> ammo=ammo-15 >> UnboundLocalError: local variable 'ammo' referenced before assignment >> >> >> Thanks, >> Jack Little > > Your global declarations are all at top-level scope, where they are meaningless. All variables defined there are global. What you want for ammo is a global declaration inside the function. By convention, you declare any globals at the top of the function, right after the def and the doc-string. You'll also need global declarations for food and lives, and perhaps others I didn't notice. Other things I notice: You omitted the parentheses in one reference to part1. So it doesn't get called there. You try to use those part1() calls as some form of looping construct. Instead you should use a while loop or similar. That also will avoid the problem you've got now where if a person types nonsense to the second question, he ends up being asked the first question again. Use lower() method on strings to avoid needing multiple comparisons: if answer2.lower() == "flee": -- DaveA From chigga101 at gmail.com Thu Sep 6 10:54:26 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 6 Sep 2012 09:54:26 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: hey guys i just like to thank everyone for their input. Its really helped me in deciding a lot of things. also @ Alan i think? as ive started writing this mail it won;t let me look up previous senders but thanks for your input. Also your field of work sounds very interesting indeed. I can't dare to imagine the amount of hard work that got you there.:) i only hope my dedication can take me half as far:) Best wishes to everyone:x From __peter__ at web.de Thu Sep 6 10:56:15 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 10:56:15 +0200 Subject: [Tutor] math description References: Message-ID: damjan kuzmic wrote: > i would like to know how to write a formula that in excell looks like > this: > > A / EXP(-LN(2) * t) >>> import math >>> A = 1.23 >>> t = 4.56 Literally (math.log is the natural logarithm): >>> A / math.exp(-math.log(2) * t) 29.013618196288864 However, exp(-x) == 1 / exp(x) and exp(ln(a)*x) == a ** x so you better spell it >>> A * 2 ** t 29.013618196288864 From d at davea.name Thu Sep 6 10:59:30 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 04:59:30 -0400 Subject: [Tutor] python 2.7.1 In-Reply-To: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: <504865F2.3070102@davea.name> On 08/20/2012 12:47 AM, john wrote: > print "hello world" #this is just something to say > > > > > >>>> /Users/jonathan/Documents/hello.py > File "", line 1 > /Users/jonathan/Documents/hello.py > ^ > SyntaxError: invalid syntax > > what am i doing wrong? > > > it would help if you showed the actual content of hello.py. Looks to me like the first line looks like: /Users/jonathan/Documents/hello.py Comment that out, and see what happens. -- DaveA From alan.gauld at btinternet.com Thu Sep 6 11:00:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:00:20 +0100 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On 17/08/12 21:11, Matthew Love wrote: > class Player(object): > > def inventory(self): > self.inventory = ["torch"] > return self.inventory Notice that you override the name inventory. Initially self.inventory is the inventory() method. But then you change self.inventory to be a list. So the next time you call player.inventory() you are trying to execute the list hence the error. You need to change the name of the inventory attribute to something like theInventory... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Sep 6 11:02:52 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 05:02:52 -0400 Subject: [Tutor] Python In-Reply-To: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> References: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> Message-ID: <504866BC.6060600@davea.name> On 08/19/2012 04:42 PM, Andrew Rosen wrote: > I have a Windows Computer and I'm trying to make a shortcut on my desktop that will run a program, so I don't have to open up a New Window form Python Shell and use that to run the program. I can't figure out how to do it, can you help me? > This is a Windows question, not a Python one. But I'll take a crack at it, since I used to run Windows. Use right-click on the desktop and choose "create shortcut" from the context menu. Fill in the name of your script. Give the shortcut a useful name. This assumes that you have the usual file associations stored in the registry. They are what tells the Windows system how to run a *.py file -- DaveA From eryksun at gmail.com Thu Sep 6 11:08:18 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 05:08:18 -0400 Subject: [Tutor] Hey.need help on time In-Reply-To: <50485E10.3040605@gmail.com> References: <50485E10.3040605@gmail.com> Message-ID: On Thu, Sep 6, 2012 at 4:25 AM, Ray Jones wrote: > > Why the additional step of calling time.tzset()? Once os.environ['TZ'] > is set, I've found that time.localtime() responds to the new TZ without > anything extra. Is that a difference in versions (2.7.3 here)? It shouldn't strictly be necessary using glibc. I checked the source. glibc localtime calls __tz_convert() on each call, which calls tzset_internal() to update the TZ setting. However, I don't think that's guaranteed in all C runtimes. As the Python docs say, "[c]hanging the TZ environment variable without calling tzset *may* change the local timezone used by methods such as localtime, but this behaviour should not be relied on." From __peter__ at web.de Thu Sep 6 11:10:01 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 11:10:01 +0200 Subject: [Tutor] python 2.7.1 References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: john wrote: > print "hello world" #this is just something to say >>>> /Users/jonathan/Documents/hello.py > File "", line 1 > /Users/jonathan/Documents/hello.py > ^ > SyntaxError: invalid syntax > > what am i doing wrong? The >>> prompt indicates that you have already started the interactive interpreter by typing $ python This is a great way to test Python statements interactively -- type and explore Python's response. However, to run a script you have to provide the script name on the commandline $ python /Users/jonathan/Documents/hello.py From d at davea.name Thu Sep 6 11:13:40 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 05:13:40 -0400 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> Message-ID: <50486944.8030100@davea.name> On 08/18/2012 09:17 PM, vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input, but the print statement adds a newline. If it were adding to each > individual element, I could solve it easily, but it is adding one at the end > of the array. Is there another way to print an array besides > > print arrayname > > If it were a string, I have a whole host of options, but I need it to be > output as an array. Each element is a url. I call it from a browser, and it > works except for the added newline. > > Here are the relevant lines: > > ================= > /* code that connects to cloudfiles omitted */ > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html\n\n"; > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > try: > del wholelist[int(sys.argv[1]):] > while i < int(sys.argv[1]): > newlist.append("http://example.com/"+wholelist[i].rstrip()) > i = i+1 > except IndexError, e: > del newlist[5] > print newlist > ============== > > The output I am seeing is as follows: > > ['http://example.com/wet-longhaireddachshund.jpg', > 'http://example.com/dachshund2.jpg', > 'http://example.com/dachshundingrass.jpg'] > > Any tips on better coding practices are welcome, but please don't beat me up > > Thanks, > vickistan > > > I don't see any arrays in that code, just lists. i also don't see how that program could produce exactly that ouput, as it also prints "Content-type: text/html\n\n"; But if you literally mean that only the final newline is a problem, then just end the print statement with a comma: print newlist, If you want more flexibility, instead of printing the list as a single entity, you can just loop through it. that way, you can choose which newlines you want, if any. for item in newlist: print repr(item), #or many other variants. But you probably want some delimeter at least. it's not clear what your other program is expecting for stdin, since there is no single standard for "takes an array for input." it's also unclear why a trailing linefeed should hurt you. But I hope this will help some. -- DaveA From alan.gauld at btinternet.com Thu Sep 6 11:15:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:15:19 +0100 Subject: [Tutor] Help In-Reply-To: <50486059.5080604@gmail.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> <50486059.5080604@gmail.com> Message-ID: On 06/09/12 09:35, Ray Jones wrote: >>> #A Python text-RPG >>> #A Jak Production >>> #APOC >>> global ammo You use global inside a function not outside. All variables declared at the module level are global by definition. >>> ammo=55 This sets the global ammo value >>> def part1(): >>> if answer == "SHOW" or answer == "Show" or answer == "show": >>> answer2 = raw_input("Type either Hand it over or flee") >>> if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 >>> == "hand it over": >>> print "Bandit: Good Job.. Go on now" >>> ammo=ammo-15 Here you try to create a local variable in the function butuse that variable in its definition. What you really wanted was to use the global ammo. To do that you need to tell the function that any reference to ammo will use the global value, like this def part1(): global ammo at the top of the function. Ray added: > I'll take a stab at it. You are using attempting to modify a global > variable within a procedure. Procedure variables are separate from > global variables. Global variables must be passed into a procedure using > something on the order of 'part1(ammo)', and then returned back from the > procedure with a 'return ' That's not strictly true, as explained above. However, it is generally considered good programming practice not to rely on globals but to pass values in as parameters as you do in your example here. So good practice says part1() should be defined as: def part1(theAmmo, theFood, theLives): # as is code... Notice I changed the names to distinguish them from the global variables. and you call it using the global variables as: part1(ammo,food,lives) The other thing to note is that at one point you use return part1 That returns the function itself which is almost certainly not what you want. You also return answer3 which doesn't seem to be defined anywhere. Returning lots of different values from the same function will make it very hard to use. You should think about breaking this down into the code that gets the user responses and separate code that returns the required values, one value per function. And finally at the end you call part() from within part(), that's a technique called recursion and can get you into all sorts of problems if you don't know what you are doing with it. What you really want is a loop that repeats the input code until you get valid values. A while loop is probably best in this case. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 6 11:18:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:18:26 +0100 Subject: [Tutor] Python 2.7.3, Pygame, and LiveWires In-Reply-To: References: Message-ID: On 04/09/12 19:52, Jason Fremouw wrote: > packages listed above come as add-ons in my text book but are not > compatible with 2.7. Are these now built into the latest build of Python > or are they listed as different downloads on Python.org? No, the livewires and pygame packages are not part of core python. You will either need to find more recent versions of the packages that are compatible or downgrade python to a version that is compatible with the packages! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 11:23:45 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 02:23:45 -0700 Subject: [Tutor] Hey.need help on time In-Reply-To: References: <50485E10.3040605@gmail.com> Message-ID: <50486BA1.1020904@gmail.com> On 09/06/2012 02:08 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 4:25 AM, Ray Jones wrote: >> Why the additional step of calling time.tzset()? Once os.environ['TZ'] >> is set, I've found that time.localtime() responds to the new TZ without >> anything extra. Is that a difference in versions (2.7.3 here)? > It shouldn't strictly be necessary using glibc. I checked the source. > glibc localtime calls __tz_convert() on each call, which calls > tzset_internal() to update the TZ setting. However, I don't think > that's guaranteed in all C runtimes. As the Python docs say, > "[c]hanging the TZ environment variable without calling tzset *may* > change the local timezone used by methods such as localtime, but this > behaviour should not be relied on." Got ya. I'll remember that. Ray From alan.gauld at btinternet.com Thu Sep 6 11:21:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:21:06 +0100 Subject: [Tutor] Python In-Reply-To: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> References: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> Message-ID: On 19/08/12 21:42, Andrew Rosen wrote: > I have a Windows Computer and I'm trying to make a shortcut on my > desktop that will run a program, so I don't have to open up a New Window > form Python Shell and use that to run the program. I can't figure out > how to do it, can you help me? Create a shortcut to the python script in Windows explorer and drag that to your desktop. If python is installed properly you should be able to double click it and python will run it. If it's a console program you might need to add a line at the end like raw_input('hit enter to quit') # python v2.x input('hit enter to quit') # python v3.x To prevent the program closing before you can see it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From omar.aboumrad at gmail.com Thu Sep 6 11:28:17 2012 From: omar.aboumrad at gmail.com (Omar Abou Mrad) Date: Thu, 6 Sep 2012 12:28:17 +0300 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On Fri, Aug 17, 2012 at 11:11 PM, Matthew Love wrote: > > This is the error: > > Traceback (most recent call last): > File "C:\Users\Matthew\Desktop\test.py", line 16, in > print(player.inventory()) > TypeError: 'list' object is not callable > > The python debugger can also give you a hint of how player.inventory changed: misc $ pdb test.py -> class Player(object): (Pdb) n -> player = Player() (Pdb) n Player created. -> player.inventory() (Pdb) whatis player.inventory *Function inventory* (Pdb) n -> player.inventory() (Pdb) whatis player.inventory ** -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 11:24:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:24:09 +0100 Subject: [Tutor] python 2.7.1 In-Reply-To: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: On 20/08/12 05:47, john wrote: > print"hello world"#this is just something to say > > > >>> /Users/jonathan/Documents/hello.py You don;t run Python scripts from the python prompt. You only type Python co0mmands there. You could import your file which wiull run it but the effect is slightly different. Its better to run scripts from the OS prompt $ python /Users/jonathan/Documents/hello.py -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 6 11:31:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:31:20 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> Message-ID: On 19/08/12 02:17, vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input You are printing a list. You are not passing an 'array' to anything. What exavctly does the other program expect to see. An array object - as defined in what language? or a list of strings? or something else. > the print statement adds a newline. It also prints the string representation of your list. If you want to print the contents of the list use a loop: for item in arrayname: print item That will give you the items each on a separate line but without the [] If you want it on a single line add a comma: for item in arrayname: print item, # python 2, python 3 is different And if you don't want spaces use join(): print ''.join(arrayname) > of the array. Is there another way to print an array besides > > print arrayname See above. but without knowing what your other program expect an 'array' to look like we can't say what is best. > output as an array. Each element is a url. I call it from a browser, and it > works except for the added newline. That suggests that you might actually want to create an html document? If you need a file its best to create a file rather than rely on print statements. IMHO... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Thu Sep 6 11:39:11 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 6 Sep 2012 10:39:11 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: Hi Ian, On 4 September 2012 20:36, Ian o donovan wrote: > Hey, I am writing this to you because I want to know could you help. > My school is doing enterprise and I want to enter. What do you mean your school is "doing enterprise"? Is it some competition or something? > I really want to > make a program that will clean up your desktop E.G put files you > haven't used for a while into a folder and delete your trash they are > just a few ideas. I am trying to learn programming but I live in > Ireland and where I live they is not much access to courses so I have > to wait till college to learn programming. I have tried to learn some > of python through on-line tutorials but find it hard So what I am > asking is > could you help me make a program if not I understand as I can imagine > ye are very busy people. You're at the right place to ask beginner Python questions. Feel free to try stuff and ask questions when you run into problems. Be sure to post complete error messages, what you've tried, what happened and what you expected to happen instead. As for courses, you may want to look into the following free educational offerings where you can learn basic programming in a structured manner: https://www.coursera.org/course/interactivepython http://www.udacity.com/overview/Course/cs101/CourseRev/apr2012 http://www.khanacademy.org/science/computer-science https://www.edx.org/courses/HarvardX/CS50x/2012/about Be sure to browse around the sites, most of the sites have multiple courses available. HTH Walter From oscar.j.benjamin at gmail.com Thu Sep 6 11:44:42 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 06 Sep 2012 10:44:42 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> <1345339036049-4985646.post@n6.nabble.com> Message-ID: On Sat, 18 Aug 2012 18:17:16 -0700 (PDT), vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input, but the print statement adds a newline. If it were adding to each > individual element, I could solve it easily, but it is adding one at the end > of the array. Is there another way to print an array besides > print arrayname Yes. You can use: print arrayname, Note the trailing comma ',' character at the end of the print statement. In python 2 this is the normal way to stop print from adding a newline. It's a silly syntax that has been fixed in python 3. If your using python 3 then it looks like print(arrayname, end='') which makes a bit more sense to me. By the way what your calling an array, python calls a list. In python the word array is usually used to refer to a number of other things. As a more general comment: are you the author of both programs? If so then you can choose a different format for outputting your data. My default choice would be to print out each url on a separate line, without the square brackets or commas. You can do that with: for url in arrayname: print url Note that I want print to add the newlines. This is a common way of working with text files and this is the reason that print adds a newline. Oscar From bgailer at gmail.com Thu Sep 6 15:44:46 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Sep 2012 09:44:46 -0400 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: References: Message-ID: <5048A8CE.3040009@gmail.com> On 8/18/2012 10:12 AM, ??? wrote: > > I need to find some way how i can get mac address of windows 7 in python. Windows 7 does not have a MAC address. It is an operating system. Ethernet adapters have MAC addresses. Your computer will have one or more Ethernet adapter. From a command prompt enter ipconfig /all You will see something like (this is from MY computer, Windows 2008 Server, similar to Win 7): Windows IP Configuration Host Name . . . . . . . . . . . . : xxx Primary Dns Suffix . . . . . . . : xxx Node Type . . . . . . . . . . . . : Hybrid IP Routing Enabled. . . . . . . . : Yes WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : xxx Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : Description . . . . . . . . . . . : Intel(R) 82579LM Gigabit Network Connecti on Physical Address. . . . . . . . . : 44-37-E6-63-86-B9 DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::e102:17d6:8b9d:43be%10(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.0.190(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.0.1 DHCPv6 IAID . . . . . . . . . . . : 172242918 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-16-8E-75-AE-44-37-E6-63-86-B9 DNS Servers . . . . . . . . . . . : ::1 127.0.0.1 NetBIOS over Tcpip. . . . . . . . : Enabled Ethernet adapter VMware Network Adapter VMnet1: Connection-specific DNS Suffix . : Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet 1 Physical Address. . . . . . . . . : 00-50-56-C0-00-01 DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::7c33:3774:7709:c50d%15(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.29.1(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : DHCPv6 IAID . . . . . . . . . . . : 419450966 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-16-8E-75-AE-44-37-E6-63-86-B9 DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1 fec0:0:0:ffff::2%1 fec0:0:0:ffff::3%1 NetBIOS over Tcpip. . . . . . . . : Enabled etc. Each Ethernet adapter has a Physical Address (MAC Address). When you run ipconfig /all - if you see only one Physical Address, then that is the one you want. If you see more than one then you must decide which Ethernet adapter you want. Then you use Popen (in subprocess module) to run ipconfig /all, capture the output and parse it for the desired Ethernet adapter, then parse that section for the Physical Address. There may be another (better?, easier?) way but this will work. -- Bob Gailer 919-636-4239 Chapel Hill NC From crawlzone at gmail.com Thu Sep 6 15:56:17 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 06:56:17 -0700 Subject: [Tutor] Making big 'uns into little 'uns Message-ID: <5048AB81.7050905@gmail.com> I have a multiple 'if' expression that I need to drastically reduce in size, both for readability and to keep errors from creeping in. For example, I would like to have the variable 'test' point to the a location 'grid[rcount-1][ccount-1]' so that everywhere I would use 'grid.....', I could replace it with 'test' How would I accomplish that? Thanks. Ray From d at davea.name Thu Sep 6 16:10:13 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:10:13 -0400 Subject: [Tutor] how to print array without adding newline In-Reply-To: <20120906134954.22610.qmail@server308.com> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> <20120906134954.22610.qmail@server308.com> Message-ID: <5048AEC5.8020504@davea.name> On 09/06/2012 09:49 AM, vicki at thepenguin.org wrote: > Thank you for your reply. I understand that it is odd, but my program is being called from a hubot and returning data to it as well. I have figured out how to make the changes to get it to output the correct data in the correct format, but now I am getting a "Premature end of script headers" error. I have the correct #! line and the output from the command line shows no errors that would be interfering. Is there a way to make sure it is showing me all the errors? To increase error logging? > ------ > !/usr/bin/env python You top-posted, so I have to clip both the earlier messages out. On this forum, we put responses immediately AFTER the part we quoted. I don't see how I can possibly help further, without buying a hubot of my own. I don't know what operating system you're running this on, nor what the command lines look like. I have no idea how the stdout of your script migrates over to the hubot's processor. Nor why it only gets some of the stdout. You could give us more environmental data (OS version, command line, any messages, ...), or tell what the hubot's docs say you should use as a format. > import cloudfiles > import random > import sys > import array > > conn = cloudfiles.get_connection('username', 'key') > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html"; Perhaps you need a blank line to be output here. One way is just print by itself. > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > #newlist=wholelist[:] > try: > # print sys.argv[1] > if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") > # print sys.argv[1] > del wholelist[int(sys.argv[1]):] > while i < int(sys.argv[1]): > newlist.append("http://example.com/"+wholelist[i].rstrip()) > i = i+1 > except IndexError, e: Where do you alert the user about this exception? > del newlist[5] > except Exception, err: > print 'Caught an exception' You should probably send this and any other error messages to stderr, as stdout is presumably being consumed by the robot. > print newlist, > ------- -- DaveA From d at davea.name Thu Sep 6 16:15:42 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:15:42 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: <5048B00E.2020301@davea.name> On 09/06/2012 09:56 AM, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? > > Thanks. > > Easiest way: switch to C++ There is no preprocessor in Python, and no addresses. There are some places you could fake such stuff, but not the expression you have. If I HAD to do something like this for Python, I'd write a preprocessor. But one reason I came to Python is its elegance, and a preprocessor isn't elegant. -- DaveA From crawlzone at gmail.com Thu Sep 6 16:15:53 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:15:53 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B00E.2020301@davea.name> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> Message-ID: <5048B019.5010709@gmail.com> On 09/06/2012 07:15 AM, Dave Angel wrote: > On 09/06/2012 09:56 AM, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? >> >> Thanks. >> >> > Easiest way: switch to C++ > > There is no preprocessor in Python, and no addresses. There are some > places you could fake such stuff, but not the expression you have. > > If I HAD to do something like this for Python, I'd write a > preprocessor. But one reason I came to Python is its elegance, and a > preprocessor isn't elegant. Well, of all the..... a REAL programming language..... I mean, even Bash.... ;;)) Anyway, it was a shot. Thanks. Ray > From __peter__ at web.de Thu Sep 6 16:33:53 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 16:33:53 +0200 Subject: [Tutor] Making big 'uns into little 'uns References: <5048AB81.7050905@gmail.com> Message-ID: Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? >>> class Grid(object): ... def __init__(self, rows): ... self.rows = rows ... def __getitem__(self, index): ... return self.rows[index] ... @property ... def test(self): ... return self[-1][-1] ... >>> grid = Grid([[1,2,3], [4,5,6], [7,8,9], [10,11,12]]) >>> grid[1] [4, 5, 6] >>> grid[1][2] 6 >>> grid.test 12 From malaclypse2 at gmail.com Thu Sep 6 16:35:24 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 6 Sep 2012 10:35:24 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B019.5010709@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: On Thu, Sep 6, 2012 at 10:15 AM, Ray Jones wrote: > Well, of all the..... a REAL programming language..... I mean, even > Bash.... ;;)) > > Anyway, it was a shot. Thanks. There's almost certainly a way to accomplish your goal of simplifying your giant nested if statements. It just doesn't involve pointers. Perhaps if you mocked up a representative example for us to look at and play with, someone could come up with a suggestion. For instance, if your set of if statements is emulating what would be done with a case statement in other languages, dictionary based dispatch may be a cleaner way to do the same thing in python. -- Jerry From crawlzone at gmail.com Thu Sep 6 16:34:04 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:34:04 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> Message-ID: <5048B45C.9050105@gmail.com> On 09/06/2012 07:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? >>>> class Grid(object): > ... def __init__(self, rows): > ... self.rows = rows > ... def __getitem__(self, index): > ... return self.rows[index] > ... @property > ... def test(self): > ... return self[-1][-1] > ... Excellent! Now I am going to save this message for the time when I've advanced to classes and objects! Thanks, Peter. Ray From d at davea.name Thu Sep 6 16:48:45 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:48:45 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B019.5010709@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: <5048B7CD.4090403@davea.name> On 09/06/2012 10:15 AM, Ray Jones wrote: > On 09/06/2012 07:15 AM, Dave Angel wrote: >> On 09/06/2012 09:56 AM, Ray Jones wrote: >>> I have a multiple 'if' expression that I need to drastically reduce in >>> size, both for readability and to keep errors from creeping in. >>> >>> For example, I would like to have the variable 'test' point to the a >>> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >>> 'grid.....', I could replace it with 'test' How would I accomplish that? >>> >>> Thanks. >>> >>> >> Easiest way: switch to C++ >> >> There is no preprocessor in Python, and no addresses. There are some >> places you could fake such stuff, but not the expression you have. >> >> If I HAD to do something like this for Python, I'd write a >> preprocessor. But one reason I came to Python is its elegance, and a >> preprocessor isn't elegant. > Well, of all the..... a REAL programming language..... I mean, even > Bash.... ;;)) > > Anyway, it was a shot. Thanks. > > I don't know your use-case. For that matter, I don't even know what semantics you mean by the grid[xx][yy] expression. For example, are grid, rcount, and ccount globals? Or are you constraining 'test' to only be used in the context where they are all visible? Or are you defining this location as the offset within grid where rcount and ccount happen to point to right now? I can see maybe a dozen "reasonable" meanings, each requiring a different sets of constructs in the language or its preprocessor. One thing you can do in Python, but not in any other language I've used, is to define a class instance property. For example, if you were willing to use q.test instead of test, you could do something like: class Q(object): @property def test(self): return grid[rcount-1][ccount-1] That would give you readonly access to an object defined by 3 variables that have to be visible to the Q code. And you could make the expression more complex if grid is defined elsewhere, for example. Now once you do q = Q(), you can use q.test instead of the larger expression. Lots of other possibilities in Python. But not with exactly your original syntax. Using this one as is would be ugly code, as is your original example. So presumably you have an actual use-case where this makes sense, other than saving typing. -- DaveA From crawlzone at gmail.com Thu Sep 6 16:50:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:50:30 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: <5048B836.4030002@gmail.com> On 09/06/2012 07:35 AM, Jerry Hill wrote: > On Thu, Sep 6, 2012 at 10:15 AM, Ray Jones wrote: >> Well, of all the..... a REAL programming language..... I mean, even >> Bash.... ;;)) >> >> Anyway, it was a shot. Thanks. > There's almost certainly a way to accomplish your goal of simplifying > your giant nested if statements. It just doesn't involve pointers. > Perhaps if you mocked up a representative example for us to look at > and play with, someone could come up with a suggestion. > > For instance, if your set of if statements is emulating what would be > done with a case statement in other languages, dictionary based > dispatch may be a cleaner way to do the same thing in python. > Thanks for the reply, Jerry. I actually can do it relatively easily with just a few nested 'if' statements.....I was trying multiple tests within the same 'if' statement. I'm simplifying it by changing into a 0-based loop rather than a 1-based loop (don't have to worry about the '-1' stuff). I'm not certain where I'm going with it yet - it's a udacity assignment that I'm still trying to work out in my head. Ray From crawlzone at gmail.com Thu Sep 6 16:59:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:59:52 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B7CD.4090403@davea.name> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> Message-ID: <5048BA68.5090400@gmail.com> On 09/06/2012 07:48 AM, Dave Angel wrote: >>> On 09/06/2012 09:56 AM, Ray Jones wrote: >>>> I have a multiple 'if' expression that I need to drastically reduce in >>>> size, both for readability and to keep errors from creeping in. >>>> >>>> For example, I would like to have the variable 'test' point to the a >>>> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >>>> 'grid.....', I could replace it with 'test' How would I accomplish that? >>>> >>>> Thanks. >>>> >>>> >>> > I don't know your use-case. For that matter, I don't even know what > semantics you mean by the grid[xx][yy] expression. For example, are > grid, rcount, and ccount globals? Or are you constraining 'test' to > only be used in the context where they are all visible? Or are you > defining this location as the offset within grid where rcount and ccount > happen to point to right now? I can see maybe a dozen "reasonable" > meanings, each requiring a different sets of constructs in the language > or its preprocessor. > > One thing you can do in Python, but not in any other language I've used, > is to define a class instance property. For example, if you were > willing to use q.test instead of test, you could do something like: > > class Q(object): > @property > def test(self): > return grid[rcount-1][ccount-1] > > That would give you readonly access to an object defined by 3 variables > that have to be visible to the Q code. And you could make the > expression more complex if grid is defined elsewhere, for example. > > Now once you do q = Q(), you can use > q.test instead of the larger expression. > > Lots of other possibilities in Python. But not with exactly your > original syntax. Using this one as is would be ugly code, as is your > original example. So presumably you have an actual use-case where this > makes sense, other than saving typing. > Basically it's as simple as ensuring that an array consists of integers, and that those integers fall within a certain range. Rather than using multiple 'if' statements, I was (am, at this point) using multiple tests within a single 'if' statement. Nothing earth-shatteringly difficult, but I was simply looking for a way to shorten the overall test expression with a recursive(? is that the term) variable. No problem though. Thanks. Ray From wprins at gmail.com Thu Sep 6 17:29:08 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 6 Sep 2012 16:29:08 +0100 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048BA68.5090400@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: Hi Ray, On 6 September 2012 15:59, Ray Jones wrote: > Basically it's as simple as ensuring that an array consists of integers, > and that those integers fall within a certain range. Rather than using > multiple 'if' statements, I was (am, at this point) using multiple tests > within a single 'if' statement. Nothing earth-shatteringly difficult, > but I was simply looking for a way to shorten the overall test > expression with a recursive(? is that the term) variable. No problem though. By array I suppose you mean "list of lists of items"? Anyway, if you have such a structure, and you want to "visit" each in turn to check it, you can do this: for sublist in grid: for item in sublist: # code to check if "item" is in range goes here The above obviously doesn't actually track the "row" or "column" you're checking. If you'd like to keep track of what "row"/"column" you're on, you can for example do: for row, sublist in enumerate(grid): for col, item in enumerate(sublist): # code to check if "item" is in range goes here HTH, Walter From oscar.j.benjamin at gmail.com Thu Sep 6 17:34:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 6 Sep 2012 15:34:06 +0000 (UTC) Subject: [Tutor] Making big 'uns into little 'uns References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: On 2012-09-06, Ray Jones wrote: > > Basically it's as simple as ensuring that an array consists of integers, > and that those integers fall within a certain range. Rather than using > multiple 'if' statements, I was (am, at this point) using multiple tests > within a single 'if' statement. Nothing earth-shatteringly difficult, > but I was simply looking for a way to shorten the overall test > expression with a recursive(? is that the term) variable. No problem though. > > Thanks. How about using a generator expression with all()? For example: >>> def isint(n): ... return int(n) == n ... >>> def isinrange(n, a, b): ... return a <= n <= b ... >>> numbers = [11, 12, 14, 15] >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) True >>> numbers[0] = 9 >>> numbers [9, 12, 14, 15] >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) False >>> numbers[0] = 14.5 >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) False Oscar From crawlzone at gmail.com Thu Sep 6 17:33:57 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 08:33:57 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: <5048C265.7080902@gmail.com> On 09/06/2012 08:29 AM, Walter Prins wrote: > Hi Ray, > > On 6 September 2012 15:59, Ray Jones wrote: >> Basically it's as simple as ensuring that an array consists of integers, >> and that those integers fall within a certain range. Rather than using >> multiple 'if' statements, I was (am, at this point) using multiple tests >> within a single 'if' statement. Nothing earth-shatteringly difficult, >> but I was simply looking for a way to shorten the overall test >> expression with a recursive(? is that the term) variable. No problem though. > By array I suppose you mean "list of lists of items"? Yes. > Anyway, if you have such a structure, and you want to "visit" each in > turn to check it, you can do this: > > for sublist in grid: > for item in sublist: > # code to check if "item" is in range goes here > > The above obviously doesn't actually track the "row" or "column" > you're checking. If you'd like to keep track of what "row"/"column" > you're on, you can for example do: > > for row, sublist in enumerate(grid): > for col, item in enumerate(sublist): > # code to check if "item" is in range goes here Our homework "monitor" complains if we use code that hasn't been discussed in session yet. We haven't even progressed to 'range' in the for loops yet - I don't think 'enumerate' would be appreciated. lol Technically, any variable pointer that I had managed to drum up here would have been frowned upon, but I didn't figure it would have been a serious breach. I've got a pretty good handle on doing it the "hard way". I'm swatting bugs right now... :)) Ray From emile at fenx.com Thu Sep 6 18:36:05 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Sep 2012 09:36:05 -0700 Subject: [Tutor] python wifi In-Reply-To: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> References: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Message-ID: On 9/5/2012 9:43 PM Sales said... > Hello, > I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: > > easy_install python_wifi-0.5.0-py2.5.egg > > I also tried: > > sudo easy_install python_wifi-0.5.0-py2.5.egg Now try the "[sudo ]easy_install python_wifi" variants. IIRC, the py2.5 in the egg name indicated compatibility for python .25 and you've said you've got 2.7 installed so let'd first try to let it pick the compatible version and see what we get. Emile From alan.gauld at btinternet.com Thu Sep 6 19:00:37 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 18:00:37 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <5048AEC5.8020504@davea.name> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> <20120906134954.22610.qmail@server308.com> <5048AEC5.8020504@davea.name> Message-ID: On 06/09/12 15:10, Dave Angel wrote: >> except Exception, err: >> print 'Caught an exception' > > You should probably send this and any other error messages to stderr, as > stdout is presumably being consumed by the robot. And you probably shouldn't use such a bland error message for every possible error. At the very least print the error type but better still store the error data in a log file if you can't just print it out. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From malaclypse2 at gmail.com Thu Sep 6 19:06:17 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 6 Sep 2012 13:06:17 -0400 Subject: [Tutor] python wifi In-Reply-To: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> References: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Message-ID: On Thu, Sep 6, 2012 at 12:43 AM, Sales wrote: > Hello, > I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: > > easy_install python_wifi-0.5.0-py2.5.egg The "py2.5" in the file name suggests that you're trying to install a version of this code that was compiled for python 2.5. If you're using python 2.7, as you say, that isn't going to work. Also, the project's homepage on the cheeseshop says "Python WiFi is a Python module that provides read and write access to a wireless network card's capabilities using the Linux Wireless Extensions". Does Mac OS X support the Linux Wireless Extensions? If not, I don't think this package is going to be of any help to you at all. -- Jerry From alan.gauld at btinternet.com Thu Sep 6 19:05:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 18:05:25 +0100 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: On 06/09/12 14:56, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? I may have missed some messages but this is context free. What are these multiple if statements? Why would "reducing" them improve readability? It might make them shorter but more cryptic. As to the other question, is test = grid[rcount-1][ccount-1] too obvious? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 19:22:23 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 10:22:23 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> Message-ID: <5048DBCF.8050700@gmail.com> On 09/06/2012 10:05 AM, Alan Gauld wrote: > On 06/09/12 14:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? > > > I may have missed some messages but this is context free. > What are these multiple if statements? > Why would "reducing" them improve readability? It might make them > shorter but more cryptic. > > As to the other question, is > > test = grid[rcount-1][ccount-1] > > too obvious? > I went out to the kitchen for a bit to eat an hour or so ago and suddenly did a face-palm! Duh! I'm going to have to quit dog-sitting for my niece - these all-nighters are killing my thinking ability! Ray From breamoreboy at yahoo.co.uk Thu Sep 6 19:32:54 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Sep 2012 18:32:54 +0100 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: On 03/09/2012 15:39, Jack Little wrote: >> Ok, I am somewhat new to python, and I am making a text-based RPG. I get a >> weird error with this code: [snip] > >> >> Thanks, >> Jack Little > Further to the sound advice you've already been given a rather more informative subject line would have been helpful :) My apologies if someone has already said this and I've missed it. -- Cheers. Mark Lawrence. From steve at pearwood.info Fri Sep 7 02:31:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:31:31 +1000 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: <50494063.5040703@pearwood.info> On 06/09/12 23:56, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? Um, am I missing something blindingly obvious here? What about this? test = grid[rcount-1][ccount-1] # I can never think of good names... if test < 1: process(test) elif test == 1: do_something_different(test, 2, 3, 4) elif 1 < test <= 100: do_another_thing(test, "ham", "cheese") # and so on... -- Steven From steve at pearwood.info Fri Sep 7 02:34:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:34:22 +1000 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048C265.7080902@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> <5048C265.7080902@gmail.com> Message-ID: <5049410E.20607@pearwood.info> On 07/09/12 01:33, Ray Jones wrote: > Our homework "monitor" complains if we use code that hasn't been > discussed in session yet. The good old "teaching by enforced ignorance" method. -- Steven From steve at pearwood.info Fri Sep 7 02:37:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:37:22 +1000 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: <5048A8CE.3040009@gmail.com> References: <5048A8CE.3040009@gmail.com> Message-ID: <504941C2.9070907@pearwood.info> On 06/09/12 23:44, bob gailer wrote: > On 8/18/2012 10:12 AM, ??? wrote: >> >> I need to find some way how i can get mac address of windows 7 in python. > Windows 7 does not have a MAC address. It is an operating system. > > Ethernet adapters have MAC addresses. Your computer will have one or more >Ethernet adapter. Just to be pedantic, your computer will have ZERO or more Ethernet adapters. Although if you are receiving email and getting on the Internet on your computer, it must have at least one. -- Steven From crawlzone at gmail.com Fri Sep 7 04:07:27 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 19:07:27 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <50494063.5040703@pearwood.info> References: <5048AB81.7050905@gmail.com> <50494063.5040703@pearwood.info> Message-ID: <504956DF.5010101@gmail.com> On 09/06/2012 05:31 PM, Steven D'Aprano wrote: > On 06/09/12 23:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? > > Um, am I missing something blindingly obvious here? > > What about this? > > test = grid[rcount-1][ccount-1] # I can never think of good names... > if test < 1: > process(test) > elif test == 1: > do_something_different(test, 2, 3, 4) > elif 1 < test <= 100: > do_another_thing(test, "ham", "cheese") > # and so on... > No, you're not missing something blindingly obvious - I was! Ray From crawlzone at gmail.com Fri Sep 7 04:14:32 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 19:14:32 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5049410E.20607@pearwood.info> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> <5048C265.7080902@gmail.com> <5049410E.20607@pearwood.info> Message-ID: <50495888.2090805@gmail.com> On 09/06/2012 05:34 PM, Steven D'Aprano wrote: > On 07/09/12 01:33, Ray Jones wrote: > >> Our homework "monitor" complains if we use code that hasn't been >> discussed in session yet. > > The good old "teaching by enforced ignorance" method. > Actually I like what they're doing. First of all, this is a CS101 class - not a Python class. I've done some (relatively - from my viewpoint) advanced programming by knowing what I wanted to accomplish and finding a (in the past) Bash tool to accomplish it. In fact, as I've been converting my Bash scripts to Python, I've been doing pretty much the same thing (which is why I subscribed to this list ;) ). But somewhere along the line I will be trying to do something that a specific tool won't accomplish: I'll have to use my brain! I've never known what I could and could not accomplish without another, stronger, tool, so I never really tried. Now I'm learning to apply my mind to problems that I KNOW can be accomplished with basic code and applying my mind to solving the problems. ;) Ray From alan.gauld at btinternet.com Fri Sep 7 09:26:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Sep 2012 08:26:21 +0100 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: <504941C2.9070907@pearwood.info> References: <5048A8CE.3040009@gmail.com> <504941C2.9070907@pearwood.info> Message-ID: On 07/09/12 01:37, Steven D'Aprano wrote: > On 06/09/12 23:44, bob gailer wrote: >> On 8/18/2012 10:12 AM, ??? wrote: >>> >>> I need to find some way how i can get mac address of windows 7 >> Ethernet adapters have MAC addresses. Your computer will have one or more >> Ethernet adapter. > > Just to be pedantic, your computer will have ZERO or more Ethernet > adapters. > Although if you are receiving email and getting on the Internet on your > computer, it must have at least one. Unless you are using dial-up... :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Fri Sep 7 17:16:41 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 07 Sep 2012 08:16:41 -0700 Subject: [Tutor] urllib2.urlopen(....., timeout=) Message-ID: <504A0FD9.6010500@gmail.com> 2.7.3 According to the docs, urlopen has a timeout capability. But it says that the timeout = '' I've tried integers as the timeout value, I've tried floats....it doesn't complain about my values, but neither does it timeout. Can anyone point me to the solution to getting the urlopen to timeout if the target system isn't responding for some reason? What kind of objects is it expecting? Ray From d at davea.name Fri Sep 7 17:32:41 2012 From: d at davea.name (Dave Angel) Date: Fri, 07 Sep 2012 11:32:41 -0400 Subject: [Tutor] urllib2.urlopen(....., timeout=) In-Reply-To: <504A0FD9.6010500@gmail.com> References: <504A0FD9.6010500@gmail.com> Message-ID: <504A1399.7010904@davea.name> On 09/07/2012 11:16 AM, Ray Jones wrote: > 2.7.3 > According to the docs, urlopen has a timeout capability. But it says > that the timeout = '' > > I've tried integers as the timeout value, I've tried floats....it > doesn't complain about my values, but neither does it timeout. Can > anyone point me to the solution to getting the urlopen to timeout if the > target system isn't responding for some reason? What kind of objects is > it expecting? > I'm curious why the docstring says ... timeout = but have no clues for you. See http://docs.python.org/library/urllib2.html which says: The optional /timeout/ parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. So I'd figure it wants an int, or maybe a float, as you've tried. is it possible that you're opening something which is neither HTTP, HTTPS nor FTP? What parameters exactly are you passing to urlopen ? I hope somebody can help more. -- DaveA From steve at pearwood.info Fri Sep 7 17:33:58 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Sep 2012 01:33:58 +1000 Subject: [Tutor] urllib2.urlopen(....., timeout=) In-Reply-To: <504A0FD9.6010500@gmail.com> References: <504A0FD9.6010500@gmail.com> Message-ID: <504A13E6.8090706@pearwood.info> On 08/09/12 01:16, Ray Jones wrote: > 2.7.3 > According to the docs, urlopen has a timeout capability. But it says > that the timeout = '' Which docs are those? According to these docs: http://docs.python.org/library/urllib2.html "The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections." > I've tried integers as the timeout value, I've tried floats....it > doesn't complain about my values, but neither does it timeout. Can you give an actual working example of what you have tried, what you expect to happen, and what actually happens? -- Steven From crawlzone at gmail.com Fri Sep 7 17:56:43 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 07 Sep 2012 08:56:43 -0700 Subject: [Tutor] urllib2.urlopen(....., timeout=) In-Reply-To: <504A1399.7010904@davea.name> References: <504A0FD9.6010500@gmail.com> <504A1399.7010904@davea.name> Message-ID: <504A193B.1070506@gmail.com> On 09/07/2012 08:32 AM, Dave Angel wrote: > On 09/07/2012 11:16 AM, Ray Jones wrote: >> 2.7.3 >> According to the docs, urlopen has a timeout capability. But it says >> that the timeout = '' >> >> I've tried integers as the timeout value, I've tried floats....it >> doesn't complain about my values, but neither does it timeout. Can >> anyone point me to the solution to getting the urlopen to timeout if the >> target system isn't responding for some reason? What kind of objects is >> it expecting? >> > I'm curious why the docstring says ... timeout = > but have no clues for you. > > See http://docs.python.org/library/urllib2.html > > which says: > > The optional /timeout/ parameter specifies a timeout in seconds for > blocking operations like the connection attempt (if not specified, the > global default timeout setting will be used). This actually only works > for HTTP, HTTPS and FTP connections. > > So I'd figure it wants an int, or maybe a float, as you've tried. is it > possible that you're opening something which is neither HTTP, HTTPS nor > FTP? What parameters exactly are you passing to urlopen ? My urlopen string is the following: urllib2.urlopen('http://%s:%s' % (ip, port), 'timeout = 2') Aha! See my problem? I just noticed it. I've been treating the 'timeout' portion as though I'm passing it as a command line parameter or something. I removed the quotes and all is swell! Y'all are awesome. Even when you don't have enough information to know the solution you help me! :) Ray From crawlzone at gmail.com Fri Sep 7 17:58:50 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 07 Sep 2012 08:58:50 -0700 Subject: [Tutor] urllib2.urlopen(....., timeout=) In-Reply-To: <504A13E6.8090706@pearwood.info> References: <504A0FD9.6010500@gmail.com> <504A13E6.8090706@pearwood.info> Message-ID: <504A19BA.4000702@gmail.com> On 09/07/2012 08:33 AM, Steven D'Aprano wrote: > On 08/09/12 01:16, Ray Jones wrote: >> 2.7.3 >> According to the docs, urlopen has a timeout capability. But it says >> that the timeout = '' > > Which docs are those? According to these docs: > > http://docs.python.org/library/urllib2.html > > "The optional timeout parameter specifies a timeout in seconds for > blocking operations like the connection attempt (if not specified, > the global default timeout setting will be used). This actually > only works for HTTP, HTTPS and FTP connections." > I was looking at the doc strings(?) in iPython's help system. > Can you give an actual working example of what you have tried, what > you expect to happen, and what actually happens? > See my response to Dave Angel, and thanks for the reply. Ray From eryksun at gmail.com Sat Sep 8 03:34:10 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 7 Sep 2012 21:34:10 -0400 Subject: [Tutor] urllib2.urlopen(....., timeout=) In-Reply-To: <504A1399.7010904@davea.name> References: <504A0FD9.6010500@gmail.com> <504A1399.7010904@davea.name> Message-ID: On Fri, Sep 7, 2012 at 11:32 AM, Dave Angel wrote: > > I'm curious why the docstring says ... timeout = > but have no clues for you. socket._GLOBAL_DEFAULT_TIMEOUT is an object(). In other words, it's an "object object". Also, that's not from the docstring but the call signature. The function doesn't have a docstring. From questions.anon at gmail.com Sat Sep 8 06:47:01 2012 From: questions.anon at gmail.com (questions anon) Date: Sat, 8 Sep 2012 14:47:01 +1000 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: Hello All, it has been a few months since I have used this and I have only just realised I am having problems with leap years. each time I get to February of a leap year my program stops, therefore I have attributed it to my code not accounting for leap years. Is there a simple way to fix my code (below) to account for leap years? Thanks stop_month = datetime(2011, 12, 31) month = datetime(2011, 01, 01) while month < stop_month: accumulate_month(month.year, month.month) month += timedelta(days=32) month = month.replace(day=01) On Wed, Apr 11, 2012 at 2:09 PM, questions anon wrote: > Thank you for this response it was a tremedous help. > It still took me awhile to work it all out and thought I would post what > worked for me. > Thanks again > > GLOBTEMPLATE = r"e:/rainfall-{year}/r{year}{month:02}??.txt" > > > def accumulate_month(year, month): > files = glob.glob(GLOBTEMPLATE.format(year=year, month=month)) > monthlyrain=[] > for ifile in files: > f=np.genfromtxt(ifile,skip_header=6) > monthlyrain.append(f) > print "year-month: ",year,"-",month, ", maximum: ", > np.max(monthlyrain), "minimum: ", np.min(monthlyrain), "mean: ", > np.mean(monthlyrain) > > stop_month = datetime(2011, 12, 31) > month = datetime(2011, 01, 01) > > while month < stop_month: > accumulate_month(month.year, month.month) > month += timedelta(days=32) > month = month.replace(day=01) > > > > > On Thu, Apr 5, 2012 at 4:57 PM, Peter Otten <__peter__ at web.de> wrote: > >> questions anon wrote: >> >> > I have been able to write up what I want to do (using glob) but I am not >> > sure how to loop it or simplify it to make the script more efficient. >> > I am currently: >> > -grouping the same months in a year using glob >> > -opening the files in a group and combining the data using a list >> > -finding max, min etc for the list and printing it >> > >> > I need to do this for many years and therefore many months so really >> need >> > a way to make this more efficient. >> > Any feedback will be greatly appreciated >> > >> > MainFolder=r"E:/rainfall-2011/" >> > OutputFolder=r"E:/test_out/" >> > r201101=glob.glob(MainFolder+"r201101??.txt") >> > r201102=glob.glob(MainFolder+"r201102??.txt") >> > r201103=glob.glob(MainFolder+"r201103??.txt") >> > >> > rain201101=[] >> > rain201102=[] >> > rain201103=[] >> > monthlyrainfall=[] >> > >> > for ifile in r201101: >> > f=np.genfromtxt(ifile, skip_header=6) >> > rain201101.append(f) >> > >> > for ifile in r201102: >> > f=np.genfromtxt(ifile, skip_header=6) >> > rain201102.append(f) >> > >> > for ifile in r201103: >> > f=np.genfromtxt(ifile, skip_header=6) >> > rain201103.append(f) >> > >> > print "jan", np.max(rain201101), np.min(rain201101), >> np.mean(rain201101), >> > np.median(rain201101), np.std(rain201101) >> > print "feb", np.max(rain201102), np.min(rain201102), >> np.mean(rain201102), >> > np.median(rain201102), np.std(rain201102) >> > print "mar", np.max(rain201103), np.min(rain201103), >> np.mean(rain201103), >> > np.median(rain201103), np.std(rain201103) >> >> Strip the code down to one month >> >> > r201103=glob.glob(MainFolder+"r201103??.txt") >> > rain201101=[] >> > for ifile in r201101: >> > f=np.genfromtxt(ifile, skip_header=6) >> > rain201101.append(f) >> >> >> then turn it into a function, roughly >> >> GLOBTEMPLATE = "e:/rainfall-{year}/r{year}{month:02}??.txt" >> def accumulate_month(year, month): >> files = glob.glob(GLOBTEMPLATE.format(year=year, month=month)) >> # read files, caculate and write stats >> >> and finally put it into a loop: >> >> from datetime import date, timedelta >> stop_month = date(2012, 4, 1) >> month = datetime(2011, 1, 1) >> while month < stop_month: >> accumulate_month(month.year, month.month) >> month += timedelta(days=32) >> month = month.replace(day=1) >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Sep 8 08:03:00 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Sep 2012 08:03 +0200 Subject: [Tutor] group txt files by month References: Message-ID: questions anon wrote: > Hello All, it has been a few months since I have used this and I have only > just realised I am having problems with leap years. each time I get to > February of a leap year my program stops, Does it throw an exception (if so, post the traceback) or does it just terminate? > therefore I have attributed it > to my code not accounting for leap years. Is there a simple way to fix my > code (below) to account for leap years? > stop_month = datetime(2011, 12, 31) > month = datetime(2011, 01, 01) Hm, 2011 is not a leap year. > while month < stop_month: > accumulate_month(month.year, month.month) > month += timedelta(days=32) > month = month.replace(day=01) Anyway, this piece of code should work the same for leap years and non-leap years. The problem must be in the code you are not posting (or in your data). PS: > month = datetime(2011, 01, 01) Stylistic note: numbers starting with 0 are interpreted as octals. It doesn't matter here, but don't get into the habit: >>> 010 == 10 False From breamoreboy at yahoo.co.uk Sat Sep 8 09:20:08 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Sep 2012 08:20:08 +0100 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: On 08/09/2012 05:47, questions anon wrote: > Hello All, it has been a few months since I have used this and I have only > just realised I am having problems with leap years. each time I get to > February of a leap year my program stops, therefore I have attributed it to > my code not accounting for leap years. Is there a simple way to fix my code > (below) to account for leap years? > > Thanks > > > stop_month = datetime(2011, 12, 31) > month = datetime(2011, 01, 01) > > while month < stop_month: > accumulate_month(month.year, month.month) > month += timedelta(days=32) > month = month.replace(day=01) > How about this as an alternative, noting that dateutil is a third party library and not in the standard library? from dateutil.relativedelta import relativedelta as rd def incrMonth(date): return date + rd(months = 1) The same pattern can be used for days, years etc. -- Cheers. Mark Lawrence. From questions.anon at gmail.com Sat Sep 8 12:12:02 2012 From: questions.anon at gmail.com (questions anon) Date: Sat, 8 Sep 2012 20:12:02 +1000 Subject: [Tutor] group txt files by month In-Reply-To: References: Message-ID: hmmm thank you, I obviously need to put some more thought in first. Thanks for the responses. On Sat, Sep 8, 2012 at 4:03 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > Hello All, it has been a few months since I have used this and I have > only > > just realised I am having problems with leap years. each time I get to > > February of a leap year my program stops, > > Does it throw an exception (if so, post the traceback) or does it just > terminate? > > > therefore I have attributed it > > to my code not accounting for leap years. Is there a simple way to fix my > > code (below) to account for leap years? > > > > stop_month = datetime(2011, 12, 31) > > month = datetime(2011, 01, 01) > > Hm, 2011 is not a leap year. > > > while month < stop_month: > > accumulate_month(month.year, month.month) > > month += timedelta(days=32) > > month = month.replace(day=01) > > Anyway, this piece of code should work the same for leap years and non-leap > years. The problem must be in the code you are not posting (or in your > data). > > PS: > > > month = datetime(2011, 01, 01) > > Stylistic note: numbers starting with 0 are interpreted as octals. It > doesn't matter here, but don't get into the habit: > > >>> 010 == 10 > False > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From finsolut2003 at yahoo.com Sat Sep 8 18:24:34 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Sat, 8 Sep 2012 09:24:34 -0700 (PDT) Subject: [Tutor] I need Help Message-ID: <1347121474.39781.YahooMailNeo@web162303.mail.bf1.yahoo.com> Hi, I am a new beginner/learner of Python. My first challenge is that I am unable to install the Python IDLE after downloading it from Python website. When I hit on the 'run' button, i got the error message below: "This installation package could not be opened. Contact the application vendor to verify that this a valid Window Installer Package." Furthermore, I read from the 'python for absolute beginners' text book that I need to add some code to the end of path in my computer property. Could this really be the solution to my problem? If it is, then I don't know how get such code to add. I don't know what to do. I use Windows 7 OS. Could someone help provide me a guide? Regards to all. Tayo.? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Sep 8 18:44:33 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Sep 2012 02:44:33 +1000 Subject: [Tutor] I need Help In-Reply-To: <1347121474.39781.YahooMailNeo@web162303.mail.bf1.yahoo.com> References: <1347121474.39781.YahooMailNeo@web162303.mail.bf1.yahoo.com> Message-ID: <504B75F1.9070105@pearwood.info> Hi Tavo, My responses are interleaved between your comments, shown with > markers. On 09/09/12 02:24, tayo rotimi wrote: > Hi, > > > I am a new beginner/learner of Python. Welcome and good luck! > My first challenge is that I am unable to install the Python IDLE after > downloading it from Python website. When I hit on the 'run' button, i >got the error message below: > > "This installation package could not be opened. Contact the application >vendor to verify that this a valid Window Installer Package." What are you downloading? As far as I can see, there is no installer for IDLE on the Python website. IDLE comes automatically with the rest of the Python installer. Please tell us: * what page you go to on the Python website to find this installer * which installer link you click on * the exact name of the installer file you download * whether your version of Windows is 32-bit or 64-bit > Furthermore, I read from the 'python for absolute beginners' text book >that I need to add some code to the end of path in my computer property. Really? Does it say what code to add, or will any old code do? Without knowing exactly what the book says, and the context, I have no idea what that means. -- Steven From chigga101 at gmail.com Sat Sep 8 20:06:17 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 8 Sep 2012 19:06:17 +0100 Subject: [Tutor] I need Help In-Reply-To: <504B75F1.9070105@pearwood.info> References: <1347121474.39781.YahooMailNeo@web162303.mail.bf1.yahoo.com> <504B75F1.9070105@pearwood.info> Message-ID: this is the same book i bought a few months ago to get me started. the instructions i remember where clear for windows. if there is a problem with the download files on the site, the author has the files on his own site also: http://www.programgames.com/page4.html save or run the file, once installed go to your start menu, choose All Programs, choose Python 3.1, then choose IDLE(Python GUI) From aaronpil at gmail.com Sun Sep 9 13:27:54 2012 From: aaronpil at gmail.com (Aaron Pilgrim) Date: Sun, 9 Sep 2012 04:27:54 -0700 Subject: [Tutor] Beginner Q: What does the double underscore mean __ ? Message-ID: Hi, I was trying to teach myself some python from a book and I have seen double underscores used. What does the __ mean and how do I know when to use it? for example: __name__==?__main__? (source) Pilgrim, Mark (2009-10-23). Dive Into Python 3 (Books for Professionals by Professionals) (Kindle Locations 480-481). Apress. Kindle Edition. From d at davea.name Sun Sep 9 14:09:21 2012 From: d at davea.name (Dave Angel) Date: Sun, 09 Sep 2012 08:09:21 -0400 Subject: [Tutor] Beginner Q: What does the double underscore mean __ ? In-Reply-To: References: Message-ID: <504C86F1.7050907@davea.name> On 09/09/2012 07:27 AM, Aaron Pilgrim wrote: > Hi, > I was trying to teach myself some python from a book and I have seen > double underscores used. > What does the __ mean and how do I know when to use it? > > for example: > > __name__==?__main__? > > (source) > Pilgrim, Mark (2009-10-23). Dive Into Python 3 (Books for > Professionals by Professionals) (Kindle Locations 480-481). Apress. > Kindle Edition. > _______________________________________________ > Two places I know of where both leading and trailing underscores are used in Python. One is for special attributes like __name__ and __doc__ and the other is for special methods like __len__ and __str__ __name__ and __file__ are attributes of a module, which let you find out things about what source file was imported to get that modjule. The name "__main__" is used to flag the SCRIPT that you started; nobody imports that file, that's how you started this program running. __doc__ is filled in by the compiler when it detects what's called a docstring: a literal string immediately following a def statement, a class statement. The module docstring would have to be the first executable line in the module, following the shebang and the encoding line. The special methods are defined in a class to give it special behavior. For example, if a class acts like a collection, it'd be convenient to define what the len() function does, so that it shows how many elements are in the instance. So, under the covers, the built-in len() function calls the objects __len__() method. A second example you use many times without noticing is that when you call str() on an object, it looks for a __str__() method. If found, that's how the object is displayed. If not, you get the generic <__main__.X instance at 0x267da70> format (differs by Python version). Incidentally when you print an arbitrary object, print calls str(), which may call __str__(). There are very few times you actually use such attributes or call such methods; __name__ is the only common one. For example, you should use str(), not __str__(). And you should use a[4], not __getitem__ See http://docs.python.org/reference/datamodel.html, and search on that page for "special methods" -- DaveA From breamoreboy at yahoo.co.uk Sun Sep 9 14:15:31 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Sep 2012 13:15:31 +0100 Subject: [Tutor] Beginner Q: What does the double underscore mean __ ? In-Reply-To: References: Message-ID: On 09/09/2012 12:27, Aaron Pilgrim wrote: > Hi, > I was trying to teach myself some python from a book and I have seen > double underscores used. > What does the __ mean and how do I know when to use it? > > for example: > > __name__==?__main__? > > (source) > Pilgrim, Mark (2009-10-23). Dive Into Python 3 (Books for > Professionals by Professionals) (Kindle Locations 480-481). Apress. > Kindle Edition. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Start here http://docs.python.org/reference/datamodel.html#specialnames Any questions please feel to ask as we don't bite :) -- Cheers. Mark Lawrence. From d at davea.name Sun Sep 9 14:38:55 2012 From: d at davea.name (Dave Angel) Date: Sun, 09 Sep 2012 08:38:55 -0400 Subject: [Tutor] Beginner Q: What does the double underscore mean __ ? In-Reply-To: References: <504C86F1.7050907@davea.name> Message-ID: <504C8DDF.40405@davea.name> On 09/09/2012 08:16 AM, Aaron Pilgrim wrote: > Thank you for the response! > You're welcome. A couple points of order: please don't top-post. There is a standard here, which makes much more sense than the Microsoft-imposed "put everything backwards" approach. Put your new text AFTER whatever you're quoting. Or don't bother quoting. Second: it's impolite to post a second copy of a question 20 minutes after a first, especially on two closely related forums like comp.lang.python and tutor. Wait till you're sure you won't get a response (on these forums, that might be 24 hours). By posting twice, you get two separate threads, and lots of duplicate information. > It makes much more sense to me. I read the python documentation and > was a little confused. I was gathering it was for operator > overloading-that there was already a main and already a name function > and these were special cases. > Now you're asking specifically about the __name__ attribute. That exists in all modules, and is simply the file name that was imported (without path and such). And it's filled in for the script as well, but given a unique value, regardless of the script's filename. The PURPOSE, however, is to let programs tell whether a particular source file was loaded as a script, or imported as a module. It's a common paradigm for modules to do self-testing when the source is loaded as a script. But you don't want that self-test code to be live when some other program uses the module. So you wrap it in the if statement: if __name__ == "__main__": if myfunc("abc") != 3: error("myfunc is busted" etc. -- DaveA From leamhall at gmail.com Sun Sep 9 17:42:18 2012 From: leamhall at gmail.com (leam hall) Date: Sun, 9 Sep 2012 10:42:18 -0500 Subject: [Tutor] Help with class in class Message-ID: I'm in the O'Reilly Python 2 class, so pointers to learning would be better than just answers, please. My brain is a bit slow but needs to go forward. Line 16 calls line 31. Rather, it is supposed to. I'm trying to figure out why I get File "./ch8_project.py", line 31, in change_text_color self.text.tag_configure('highlightline', foreground=fg_color) AttributeError: 'ch8_Project' object has no attribute 'text' If line 31 starts with "self." and File "./ch8_project.py", line 31, in change_text_color text.tag_configure('highlightline', foreground=fg_color) NameError: global name 'text' is not defined If Line 31 does not start with "self.". I understand the second problem but not the first. What am I missing? Thanks! Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Sun Sep 9 17:43:26 2012 From: leamhall at gmail.com (leam hall) Date: Sun, 9 Sep 2012 10:43:26 -0500 Subject: [Tutor] Help with class in class In-Reply-To: References: Message-ID: Of course, showing the code might help... http://bpaste.net/show/44593/ Thanks! Leam On Sun, Sep 9, 2012 at 10:42 AM, leam hall wrote: > I'm in the O'Reilly Python 2 class, so pointers to learning would be > better than just answers, please. My brain is a bit slow but needs to go > forward. > > Line 16 calls line 31. Rather, it is supposed to. I'm trying to figure out > why I get > > File "./ch8_project.py", line 31, in change_text_color > self.text.tag_configure('highlightline', foreground=fg_color) > AttributeError: 'ch8_Project' object has no attribute 'text' > > If line 31 starts with "self." and > > File "./ch8_project.py", line 31, in change_text_color > text.tag_configure('highlightline', foreground=fg_color) > NameError: global name 'text' is not defined > > > If Line 31 does not start with "self.". I understand the second problem > but not the first. > > What am I missing? > > Thanks! > > Leam > > > -- > Mind on a Mission > > -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Sep 9 18:57:35 2012 From: kwpolska at gmail.com (Kwpolska) Date: Sun, 9 Sep 2012 18:57:35 +0200 Subject: [Tutor] Help with class in class In-Reply-To: References: Message-ID: On Sun, Sep 9, 2012 at 5:43 PM, leam hall wrote: > Of course, showing the code might help... > > http://bpaste.net/show/44593/ > > Thanks! > > Leam > > > On Sun, Sep 9, 2012 at 10:42 AM, leam hall wrote: >> >> I'm in the O'Reilly Python 2 class, so pointers to learning would be >> better than just answers, please. My brain is a bit slow but needs to go >> forward. >> >> Line 16 calls line 31. Rather, it is supposed to. I'm trying to figure out >> why I get >> >> File "./ch8_project.py", line 31, in change_text_color >> self.text.tag_configure('highlightline', foreground=fg_color) >> AttributeError: 'ch8_Project' object has no attribute 'text' >> >> If line 31 starts with "self." and >> >> File "./ch8_project.py", line 31, in change_text_color >> text.tag_configure('highlightline', foreground=fg_color) >> NameError: global name 'text' is not defined >> >> >> If Line 31 does not start with "self.". I understand the second problem >> but not the first. >> >> What am I missing? >> >> Thanks! >> >> Leam >> >> >> -- >> Mind on a Mission >> > > > > -- > Mind on a Mission > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please do not top post. --- And the problem is: add_text_widget() defines a local (function-wide) `text` object rather than a class-wide one. Just prepend the `text` object with `self.` and it will be solved. Also, if you are planning to use more than one of those, you will need to do it in another way. Bonus question: why py3k? -- Kwpolska stop html mail | always bottom-post www.asciiribbon.org | www.netmeister.org/news/learn2quote.html GPG KEY: 5EAAEA16 From __peter__ at web.de Sun Sep 9 19:12:03 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Sep 2012 19:12:03 +0200 Subject: [Tutor] Help with class in class References: Message-ID: leam hall wrote: > I'm in the O'Reilly Python 2 class, so pointers to learning would be > better than just answers, please. My brain is a bit slow but needs to go > forward. > > Line 16 calls line 31. Rather, it is supposed to. I'm trying to figure out > why I get > > File "./ch8_project.py", line 31, in change_text_color > self.text.tag_configure('highlightline', foreground=fg_color) > AttributeError: 'ch8_Project' object has no attribute 'text' > > If line 31 starts with "self." and > > File "./ch8_project.py", line 31, in change_text_color > text.tag_configure('highlightline', foreground=fg_color) > NameError: global name 'text' is not defined > > > If Line 31 does not start with "self.". I understand the second problem > but not the first. > > What am I missing? When inside a method you assign to self.whatever = ... you are setting an attribute of the class. If you assign to a name whatever = ... you are setting a local variable. So > #!/usr/bin/env python3 > > from tkinter import * > > SIDE = W+E > ALL = N+E+W+S > > class ch8_Project(Frame): > > def __init__(self, master=None): > Frame.__init__(self, master) > self.file_open("./fred") > fg_color = "Red" > self.pack() > self.add_text_widget( fg_color, self.out_text) > self.green = Button(root, text="Green", command=self.change_text_color("green")) > self.green.pack(side=TOP) > > def add_text_widget(self, fg_color, out_text): > text = Text(root) in the above line you are making a local variable which will be forgotten when the method terminates. Change the line to self.text = Text(root) do the same for the following lines, and > text.insert(INSERT, out_text) > text.tag_configure('highlightline', foreground='red') > text.tag_add('highlightline', '1.0', 'end') > text.pack() > > def file_open(self, file_name): > file = open(file_name, "r") > self.out_text = file.read() > > def change_text_color(self, fg_color): > self.text.tag_configure('highlightline', foreground=fg_color) the above will no longer complain about a missing attribute. > root = Tk() > project = ch8_Project(master=root) > project.mainloop() Another problem that caught my attention: > self.green = Button(root, text="Green", command=self.change_text_color("green")) The command argument is supposed to be a function; you are instead assigning the result of a method call (which is None in this case, but as a side effect will set the color to green immediately. The simplest fix is to define a helper function that takes no arguments ... def change_to_green(): self.change_text_color("green") self.green = Button(root, text="Green", command=change_to_green) ... If you already know about lambda you can try to rewrite this using that. From finsolut2003 at yahoo.com Sun Sep 9 20:03:29 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Sun, 9 Sep 2012 11:03:29 -0700 (PDT) Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: References: Message-ID: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> Hi Steven, Please see my answers (bold, and in blue) after each of your questions below. Hope you would be able to help, with these further notes I have provided. Regards. Tayo Message: 3 Date: Sun, 09 Sep 2012 02:44:33 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] I need Help Message-ID: <504B75F1.9070105 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed Hi Tavo, My responses are interleaved between your comments, shown with > markers. On 09/09/12 02:24, tayo rotimi wrote: > Hi, > > > I am a new beginner/learner of Python. Welcome and good luck! > My first challenge is that I am unable to install the Python IDLE after > downloading it from Python website. When I hit on the 'run' button, i >got the error message below: > > "This installation package could not be opened. Contact the application >vendor to verify that this a valid Window Installer Package." What are you downloading? As far as I can see, there is no installer for IDLE on the Python website. IDLE comes automatically with the rest of the Python installer. Please tell us:? Please go to:? http://www.python.org/download/? * what page you go to on the Python website to find this installer - Please click on:http://www.python.org/download/ * which installer link you click on - on the page look for and click on the following:Python 2.7.3 Windows X86-64 Installer(Windows AMD64 / Intel 64 / X86-64 binary [1]-- does not include source) * the exact name of the installer file you download - exact name is: Python 2.7.3 Windows X86-64 Installer(Windows AMD64 / Intel 64 / X86-64 binary [1]-- does not include source) * whether your version of Windows is 32-bit or 64-bit -my version is 64-bit Windows 7 > Furthermore, I read from the 'python for absolute beginners' text book >that I need to add some code to the end of path in my computer property. Really? Does it say what code to add, or will any old code do? Without knowing exactly what the book says, and the context, I have no idea what that means. Below is the context, verbatim: "If you have a trouble running the IDLE, you may have to modify the your Windows System Path - a list of the directories where your system looks to find program files. you 'll want to add the following to the end of the Path: ;C:\Python27;C:\Program Files\Tcl;C:\Program Files\Tcl\bin. The process of modifying your Path is different for each version of windows, so check your Windows Help documentation for Environment Variable (since the Path is one of your Environment Variables)." -- Steven ------------------------------ Message: 4 Date: Sat, 8 Sep 2012 19:06:17 +0100 From: Matthew Ngaha To: tutor at python.org Subject: Re: [Tutor] I need Help Message-ID: ??? Content-Type: text/plain; charset=ISO-8859-1 this is the same book i bought a few months ago to get me started. the instructions i remember where clear for windows. if there is a problem with the download files on the site, the author has the files on his own site also: http://www.programgames.com/page4.html save or run the file, once installed go to your start menu, choose All Programs, choose Python 3.1, then choose IDLE(Python GUI) ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 103, Issue 37 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Sun Sep 9 21:12:48 2012 From: leamhall at gmail.com (leam hall) Date: Sun, 9 Sep 2012 14:12:48 -0500 Subject: [Tutor] Help with class in class In-Reply-To: References: Message-ID: On Sun, Sep 9, 2012 at 12:12 PM, Peter Otten <__peter__ at web.de> wrote: > the above will no longer complain about a missing attribute. > > > root = Tk() > > project = ch8_Project(master=root) > > project.mainloop() > > > Another problem that caught my attention: > > > self.green = Button(root, text="Green", > command=self.change_text_color("green")) > > > The command argument is supposed to be a function; you are instead > assigning > the result of a method call (which is None in this case, but as a side > effect will set the color to green immediately. The simplest fix is to > define a helper function that takes no arguments > ... > def change_to_green(): > self.change_text_color("green") > self.green = Button(root, text="Green", command=change_to_green) > ... > > If you already know about lambda you can try to rewrite this using that. > > Peter, thank you for helping me understand the scope issue I was missing! I knew it was something like that but forget that omitting "this." meant the variables were limited in scope to that method. I have seen lamba but do not understand it. The project requires four buttons, each one turns the same text a different color. The class is also Python 3 based. :) Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Sun Sep 9 21:20:19 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 9 Sep 2012 20:20:19 +0100 Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: References: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> Message-ID: SORRY i wrote to you not the mailing list:( im a beginner myself, and those instructions seem very complicated for me. But i did install Python and everything included with no problem. You need at least Python 3.1 for this book we have. its what the author recommended. version 2.7 as you have shown in the link is too old as it has different syntax. Try downloading Python from the link i included, you will have no trouble installing IDLE with this link. From chigga101 at gmail.com Sun Sep 9 21:41:24 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 9 Sep 2012 20:41:24 +0100 Subject: [Tutor] web frameworks Message-ID: Hi all, i had a recent post about learning about guis and web applications. i decided to try guis 1st, but i also decided that maybe a very very very simple web framework would not be too much work for me to study once in while. I decided on Flask because i read it's the simpliest framework out of all the others i've researched, only to find out it's not supported on Python 3:(.. i wondered if someone with experience can tell me, in their opinion a framework with a similar learning curve to Flask that a beginner can easily understand and is supported on Python 3. i thought cherrypy, but was told it's not nearly as simple as Flask, and since my main focus is learning GUIs, a simple web framework will be ideal only to understand how they work. i understand Javascript only a little, but html and css a bit better etc.. also is mod_python similar to a framework? does it perform the same tasks and also make good web applications? would this be a better option? From steve at pearwood.info Sun Sep 9 22:29:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Sep 2012 06:29:50 +1000 Subject: [Tutor] web frameworks In-Reply-To: References: Message-ID: <504CFC3E.2040701@pearwood.info> On 10/09/12 05:41, Matthew Ngaha wrote: > [...] i thought cherrypy, but was told it's not > nearly as simple as Flask, and since my main focus is learning GUIs, a > simple web framework will be ideal only to understand how they work. Understanding *how they work* is not going to be simple. Web frameworks are big, complex pieces of software. Being *able to use them* can be simple. Here's the "Hello world" example for Cherrypy: import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) I doubt Flask is simpler than that. -- Steven From leamhall at gmail.com Sun Sep 9 22:56:26 2012 From: leamhall at gmail.com (leam hall) Date: Sun, 9 Sep 2012 15:56:26 -0500 Subject: [Tutor] Help with class in class In-Reply-To: References: Message-ID: self.blue = Button(root, text="Blue", command=self.change_text_color("blue")) self.blue.pack(side=LEFT) self.green = Button(root, text="Green", command=self.change_text_color("green")) self.green.pack(side=LEFT) To follow up, I've added a second button. Of course, it doesn't work, the text comes out as the color of the last button. It is running the commands in the Button line without the buttons being clicked. More research... -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Sun Sep 9 23:07:30 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 9 Sep 2012 22:07:30 +0100 Subject: [Tutor] web frameworks In-Reply-To: References: <504CFC3E.2040701@pearwood.info> Message-ID: sorry steven i keep replying to sender and not tutor:( From d at davea.name Sun Sep 9 23:13:37 2012 From: d at davea.name (Dave Angel) Date: Sun, 09 Sep 2012 17:13:37 -0400 Subject: [Tutor] Help with class in class In-Reply-To: References: Message-ID: <504D0681.6060208@davea.name> On 09/09/2012 04:56 PM, leam hall wrote: > self.blue = Button(root, text="Blue", > command=self.change_text_color("blue")) > self.blue.pack(side=LEFT) > self.green = Button(root, text="Green", > command=self.change_text_color("green")) > self.green.pack(side=LEFT) > > To follow up, I've added a second button. Of course, it doesn't work, the > text comes out as the color of the last button. It is running the commands > in the Button line without the buttons being clicked. > > More research... > > Please reread Peter's message, starting with "Another problem..." He identifies the problem, and mentions one way to fix it. In your response, you mentioned to lambda, so you must have seen it. In particular, the Button() function takes a function object as its command= parameter. You call the function yourself, and pass the return value, which of course is not what's wanted. You don't want the function called till someone presses the button. So you want something equivalent to = Button(root, text="Blue", command=change_to_green) Notice that there are NO parentheses on that change_to_green. You want the function object, you do NOT want to call the function. -- DaveA From finsolut2003 at yahoo.com Sun Sep 9 23:34:46 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Sun, 9 Sep 2012 14:34:46 -0700 (PDT) Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: <1347226486.68870.YahooMailNeo@web162301.mail.bf1.yahoo.com> Hi Matthew, The link you provided, http://www.programgames.com/page4.html, leads to where I can only download the book but not the software. I will appreciate if you could click on it to check again and provide me with further guide. Regards. Tayo. SORRY i wrote to you not the mailing list:( im a beginner myself, and those instructions seem very complicated for me. But i did install Python and everything included with no problem. You need at least Python 3.1 for this book we have. its what the author recommended. version 2.7 as you have shown in the link is too old as it has different syntax. Try downloading Python from the link i included, you will have no trouble installing IDLE with this link. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gollumgreg407366 at gmail.com Sun Sep 9 23:58:27 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Sun, 9 Sep 2012 16:58:27 -0500 Subject: [Tutor] Pygame and TkInter Message-ID: Hello Tutor, Quick question. Working on a new game and want to build in a GUI. TkInter seems to fit the bill except for one small item. Both Pygame and TkInter create windows. (Screen in Pygame, and the Root widget in TkInter) Is there a way to combined these two so I can use all my Pygame sprites and objects and any TkInter bars and buttons all in one screen? My best guess would be something along this line. screen = pygame.display.set_mode((640, 420)) root = Tk(screen) or maybe this... screen = Tk(pygame.display.set_mode((640, 420)) I really just need Tkinter for some easy buttons and stuff, everything else I can do in Pygame. Any thoughts? Thanks for the assist. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 10 00:02:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Sep 2012 23:02:28 +0100 Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> References: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> Message-ID: On 09/09/12 19:03, tayo rotimi wrote: > * which installer link you click on - on the page look for and click on > the following:Python 2.7.3 Windows X86-64 Installer > (Windows > AMD64 / Intel 64 / X86-64 binary [1] > -- does not include source) > > * the exact name of the installer file you download - exact name is: > Python 2.7.3 Windows X86-64 Installer > (Windows > AMD64 / Intel 64 / X86-64 binary [1] > -- does not include source) > > * whether your version of Windows is 32-bit or 64-bit -my version is > 64-bit Windows 7 OK, it should work just fine. One thing to note is that you are NOT installing Python IDLE, you are installing Python. IDLE is just one small component part. However, that doesn't change how you install it and it should just work. Given that it doesn't I'd recommend two other things to try: 1) Go to ActiveState.com and download their installer. I always recommend the ActiveState version for Windows users because they bundle a bunch of useful goodies that you don't get from python.org And it uses a different installer... 2) Try downloading and installing 32bit Python. 64bit windows can run the 32 bit version too and it might install more successfully. But I'd try ActiveState first - its free but ISTR you need to register. > idea what that means. Below is the context, verbatim: > > "If you have a trouble running the IDLE, you may have to modify the your > Windows System Path This is hogwash. You shouldn't need to change your path to run IDLE. You may need to change it to run Python but once Python is recognised IDLE should work with no further changes. And the installer should get Python recognised as part of its setup. There were some PATH issues in older versions but I think the recent ones work OK. I've heard good things about this book but frankly its not looking too promising so far! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From finsolut2003 at yahoo.com Mon Sep 10 00:11:37 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Sun, 9 Sep 2012 15:11:37 -0700 (PDT) Subject: [Tutor] I Need Help - thank you all, its now done In-Reply-To: <1347226486.68870.YahooMailNeo@web162301.mail.bf1.yahoo.com> References: <1347226486.68870.YahooMailNeo@web162301.mail.bf1.yahoo.com> Message-ID: <1347228697.63903.YahooMailNeo@web162302.mail.bf1.yahoo.com> Thank you, Matthew and all, I have just installed the Python IDLE. Now I an ready to begin learning how to write programs. That means you may see more questions from me as I am ready to leverage on your experiences. I appreciate everyone who has helped and guided me in one way or the other. Regards to all. Tayo. ________________________________ From: tayo rotimi To: "tutor at python.org" Sent: Sunday, September 9, 2012 10:34 PM Subject: Re: I Need Help Hi Matthew, The link you provided, http://www.programgames.com/page4.html, leads to where I can only download the book but not the software. I will appreciate if you could click on it to check again and provide me with further guide. Regards. Tayo. SORRY i wrote to you not the mailing list:( im a beginner myself, and those instructions seem very complicated for me. But i did install Python and everything included with no problem. You need at least Python 3.1 for this book we have. its what the author recommended. version 2.7 as you have shown in the link is too old as it has different syntax. Try downloading Python from the link i included, you will have no trouble installing IDLE with this link. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 10 00:11:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Sep 2012 23:11:49 +0100 Subject: [Tutor] web frameworks In-Reply-To: References: Message-ID: On 09/09/12 20:41, Matthew Ngaha wrote: > a very very very simple web framework would not be too much work for > me to study once in while. I decided on Flask because i read it's the > simpliest framework They nearly all claim that :-) > supported on Python 3. i thought cherrypy, but was told it's not > nearly as simple as Flask, I've never used Flask but CherryPy is very easy to use if you understand the basics of OOP. > simple web framework will be ideal only to understand how they work. Web Frameworks are big and complex and designed to stop you from needing to know how they work. They are easy to use but hard to understand. If you want to know how web programming (what's behind all Frameworks) take a look at the cgi module and it's documentation and write a very simple web app. A form that you enter your name and hit submit. The app responds with a page that says "Welcome Matthew". It doesn't get much simpler but it's the basis of how all Web Frameworks operate. Once you do that you can reproduce it in the Framework of choice and be amazed how much easier it is! :-). > understand Javascript only a little, but html and css a bit better > etc.. You only need JavaScript when you get into real web UI design, for basic experiments HTML (and CSS only if you must) are ample. > also is mod_python similar to a framework? does it perform the same > tasks and also make good web applications? No, mod_python is completely different. Most web frameworks will use mod_python under the covers but you largely don't need to know about it. mod_python is basically a technology that works with the web server to make launching python applications much faster. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Sep 10 00:14:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Sep 2012 23:14:28 +0100 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On 09/09/12 22:58, Greg Nielsen wrote: > TkInter) Is there a way to combined these two so I can use all my Pygame > sprites and objects and any TkInter bars and buttons all in one screen? This is a bit off the beaten track for the tutor list, although you may get lucky. But I'd recommend asking on the PyGame mailing list/forum (or maybe the Tkinter one but I suspect PyGame will be a better bet) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Sep 10 00:17:26 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Sep 2012 08:17:26 +1000 Subject: [Tutor] web frameworks In-Reply-To: References: <504CFC3E.2040701@pearwood.info> Message-ID: <20120909221726.GA20551@ando> On Sun, Sep 09, 2012 at 10:07:30PM +0100, Matthew Ngaha wrote: > sorry steven i keep replying to sender and not tutor:( That's fine, but there's no point apologising publically if you don't resend your question to the tutor list. You asked: [quote] oh? is cherrypy compaitable with Python 3? > index.exposed = True is that line with exposed making the return statement visible? sorry to ask:( just interested to know what is being set to True [end quote] Yes, Cherrypy is compatible with Python 3. See the CherryPy website: http://www.cherrypy.org/ "Runs on Python 2.5+, 3.1+, Jython and Android." For security, CherryPy defaults to *not* exposing anything on the Internet. So the line "index.exposed = True" tells CherryPy that it is okay to expose the "hello world" application to the Internet. http://docs.cherrypy.org/stable/concepts/basics.html -- Steven From wprins at gmail.com Mon Sep 10 00:25:51 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 9 Sep 2012 23:25:51 +0100 Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: References: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> Message-ID: Hi, On 9 September 2012 23:02, Alan Gauld wrote: > 2) Try downloading and installing 32bit Python. 64bit windows can run the 32 > bit version too and it might install more successfully. But I'd try > ActiveState first - its free but ISTR you need to register. Just to +1 this, and to confirm that you don't actually need to register. This is the download page: http://www.activestate.com/activepython/downloads Clicking one of the download links on that page actually starts the download, and then redirects you to the registration page, which you can ignore if you so choose. Walter From steve at pearwood.info Mon Sep 10 00:28:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Sep 2012 08:28:07 +1000 Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: References: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> Message-ID: <20120909222807.GB20551@ando> On Sun, Sep 09, 2012 at 08:20:19PM +0100, Matthew Ngaha wrote: > SORRY i wrote to you not the mailing list:( > > im a beginner myself, and those instructions seem very complicated for > me. What instructions are you talking about? I'm sure that was very clear in your head when you wrote that, but think about how it looks to us. We could be reading your email hours, days, even months later. We see your comment about complicated instructions, but all context is lost and we have no idea what instructions you mean. You could be taking about anything. > But i did install Python and everything included with no problem. > You need at least Python 3.1 for this book we have. its what the > author recommended. version 2.7 as you have shown in the link is too > old as it has different syntax. Try downloading Python from the link i > included, you will have no trouble installing IDLE with this link. I'm not sure who you are talking to here. Most of us already have Python installed. As a matter of fact, I have at least ten different versions of Python installed: Python 1.5, 2.4, 2.5, 2.6, 2.7, 3.2, 3.3, Jython, IronPython and even an ancient copy of Python 0.9, and let me tell you that is *really* different. What I don't have is a crystal ball to tell what you are talking about -- Steven From chigga101 at gmail.com Mon Sep 10 00:47:12 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 9 Sep 2012 23:47:12 +0100 Subject: [Tutor] I Need Help - further details now provided. In-Reply-To: <20120909222807.GB20551@ando> References: <1347213809.96804.YahooMailNeo@web162303.mail.bf1.yahoo.com> <20120909222807.GB20551@ando> Message-ID: > What instructions are you talking about? > > I'm sure that was very clear in your head when you wrote that, but think > about how it looks to us. We could be reading your email hours, days, > even months later. We see your comment about complicated instructions, > but all context is lost and we have no idea what instructions you mean. > You could be taking about anything. > sorry i havent gotten a hand of how the emails work. i thought the original question from the sender and all corresponding emails would still be visible for all to see, so i tried to shorten my mail. I was trying to help someone having problems with IDLE. He showed a set of instructions that didnt make sense to me as i didnt have to go through that when installing IDLE. Hi Alan Gauld. the book 'Python for the absolute beginner' is the best thing to ever happen to me. The instructions that the original sender provided is not from this book, i honestly do not know where the text is from, but the book was very clear on how to install Python, providing a direct link also. Im sure this beginner book will be of no use to you:) but its an exciting read. From finsolut2003 at yahoo.com Mon Sep 10 00:56:22 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Sun, 9 Sep 2012 15:56:22 -0700 (PDT) Subject: [Tutor] Help - My First Program Fails In-Reply-To: References: Message-ID: <1347231382.78537.YahooMailNeo@web162304.mail.bf1.yahoo.com> My first exercise: print "Game Over" does not run! Where have I missed it? The error message is as follows: ?File "", line 1 ?? print "Game Over" ??? ??? ??? ??? ??? ^ ?SyntaxError: invalid syntax I am still surprised at this error. I 'll appreciate your help. Regards. Tayo ________________________________ From: "tutor-request at python.org" To: tutor at python.org Sent: Sunday, September 9, 2012 10:14 PM Subject: Tutor Digest, Vol 103, Issue 40 Send Tutor mailing list submissions to ??? tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit ??? http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to ??? tutor-request at python.org You can reach the person managing the list at ??? tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: ? 1. Re: Help with class in class (leam hall) ? 2. Re: I Need Help - further details now provided. (Matthew Ngaha) ? 3. web frameworks (Matthew Ngaha) ? 4. Re: web frameworks (Steven D'Aprano) ? 5. Re: Help with class in class (leam hall) ? 6. Re: web frameworks (Matthew Ngaha) ? 7. Re: Help with class in class (Dave Angel) ---------------------------------------------------------------------- Message: 1 Date: Sun, 9 Sep 2012 14:12:48 -0500 From: leam hall To: tutor Subject: Re: [Tutor] Help with class in class Message-ID: ??? Content-Type: text/plain; charset="utf-8" On Sun, Sep 9, 2012 at 12:12 PM, Peter Otten <__peter__ at web.de> wrote: > the above will no longer complain about a missing attribute. > > > root = Tk() > > project = ch8_Project(master=root) > > project.mainloop() > > > Another problem that caught my attention: > > >? ? self.green = Button(root, text="Green", > command=self.change_text_color("green")) > > > The command argument is supposed to be a function; you are instead > assigning > the result of a method call (which is None in this case, but as a side > effect will set the color to green immediately. The simplest fix is to > define a helper function that takes no arguments >? ? ? ... >? ? ? def change_to_green(): >? ? ? ? ? self.change_text_color("green") >? ? ? self.green = Button(root, text="Green", command=change_to_green) >? ? ? ... > > If you already know about lambda you can try to rewrite this using that. > > Peter, thank you for helping me understand the scope issue I was missing! I knew it was something like that but forget that omitting "this." meant the variables were limited in scope to that method. I have seen lamba but do not understand it. The project requires four buttons, each one turns the same text a different color. The class is also Python 3 based.? :) Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sun, 9 Sep 2012 20:20:19 +0100 From: Matthew Ngaha To: tutor at python.org Subject: Re: [Tutor] I Need Help - further details now provided. Message-ID: ??? Content-Type: text/plain; charset=ISO-8859-1 SORRY i wrote to you not the mailing list:( im a beginner myself, and those instructions seem very complicated for me. But i did install Python and everything included with no problem. You need at least Python 3.1 for this book we have. its what the author recommended. version 2.7 as you have shown in the link is too old as it has different syntax. Try downloading Python from the link i included, you will have no trouble installing IDLE with this link. ------------------------------ Message: 3 Date: Sun, 9 Sep 2012 20:41:24 +0100 From: Matthew Ngaha To: tutor at python.org Subject: [Tutor] web frameworks Message-ID: ??? Content-Type: text/plain; charset=ISO-8859-1 Hi all, i had a recent post about learning about guis and web applications. i decided to try guis 1st, but i also decided that maybe a very very very simple web framework would not be too much work for me to study once in? while. I decided on Flask because i read it's the simpliest framework out of all the others i've researched, only to find out it's not supported on Python 3:(.. i wondered if someone with experience can tell me, in their opinion a framework with a similar learning curve to Flask that a beginner can easily understand and is supported on Python 3. i thought cherrypy, but was told it's not nearly as simple as Flask, and since my main focus is learning GUIs, a simple web framework will be ideal only to understand how they work. i understand Javascript? only a little, but html and css a bit better etc.. also is mod_python similar to a framework? does it perform the same tasks and also make good web applications? would this be a better option? ------------------------------ Message: 4 Date: Mon, 10 Sep 2012 06:29:50 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] web frameworks Message-ID: <504CFC3E.2040701 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed On 10/09/12 05:41, Matthew Ngaha wrote: > [...] i thought cherrypy, but was told it's not > nearly as simple as Flask, and since my main focus is learning GUIs, a > simple web framework will be ideal only to understand how they work. Understanding *how they work* is not going to be simple. Web frameworks are big, complex pieces of software. Being *able to use them* can be simple. Here's the "Hello world" example for Cherrypy: import cherrypy class HelloWorld(object): ? ? def index(self): ? ? ? ? return "Hello World!" ? ? index.exposed = True cherrypy.quickstart(HelloWorld()) I doubt Flask is simpler than that. -- Steven ------------------------------ Message: 5 Date: Sun, 9 Sep 2012 15:56:26 -0500 From: leam hall To: tutor Subject: Re: [Tutor] Help with class in class Message-ID: ??? Content-Type: text/plain; charset="utf-8" ? ? self.blue = Button(root, text="Blue", command=self.change_text_color("blue")) ? ? self.blue.pack(side=LEFT) ? ? self.green = Button(root, text="Green", command=self.change_text_color("green")) ? ? self.green.pack(side=LEFT) To follow up, I've added a second button. Of course, it doesn't work, the text comes out as the color of the last button. It is running the commands in the Button line without the buttons being clicked. More research... -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 6 Date: Sun, 9 Sep 2012 22:07:30 +0100 From: Matthew Ngaha To: tutor at python.org Subject: Re: [Tutor] web frameworks Message-ID: ??? Content-Type: text/plain; charset=ISO-8859-1 sorry steven i keep replying to sender and not tutor:( ------------------------------ Message: 7 Date: Sun, 09 Sep 2012 17:13:37 -0400 From: Dave Angel To: leam hall Cc: tutor Subject: Re: [Tutor] Help with class in class Message-ID: <504D0681.6060208 at davea.name> Content-Type: text/plain; charset=ISO-8859-1 On 09/09/2012 04:56 PM, leam hall wrote: >? ? self.blue = Button(root, text="Blue", > command=self.change_text_color("blue")) >? ? self.blue.pack(side=LEFT) >? ? self.green = Button(root, text="Green", > command=self.change_text_color("green")) >? ? self.green.pack(side=LEFT) > > To follow up, I've added a second button. Of course, it doesn't work, the > text comes out as the color of the last button. It is running the commands > in the Button line without the buttons being clicked. > > More research... > > Please reread Peter's message, starting with "Another problem..." He identifies the problem, and mentions one way to fix it.? In your response, you mentioned to lambda, so you must have seen it. In particular, the Button() function takes a function object as its command= parameter.? You call the function yourself, and pass the return value, which of course is not what's wanted.? You don't want the function called till someone presses the button.? So you want something equivalent to ? ? ? = Button(root, text="Blue", command=change_to_green) Notice that there are NO parentheses on that change_to_green.? You want the function object, you do NOT want to call the function. -- DaveA ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 103, Issue 40 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Mon Sep 10 01:05:24 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 10 Sep 2012 00:05:24 +0100 Subject: [Tutor] web frameworks In-Reply-To: References: <504CFC3E.2040701@pearwood.info> <20120909221726.GA20551@ando> Message-ID: thanks for all the help guys. Cherrypy it is. i will take a look at some cgi tutorials first, as Alan suggested, to get a good understanding of how things work. From steve at pearwood.info Mon Sep 10 01:36:00 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Sep 2012 09:36:00 +1000 Subject: [Tutor] Help - My First Program Fails In-Reply-To: <1347231382.78537.YahooMailNeo@web162304.mail.bf1.yahoo.com> References: <1347231382.78537.YahooMailNeo@web162304.mail.bf1.yahoo.com> Message-ID: <20120909233600.GE20551@ando> Please, please, PLEASE do not reply to a digest without deleting the irrelevant text from your email! We don't need to read HUNDREDS of lines of text we've already seen before. When you want to start a *new* question, ALWAYS start a fresh, blank email, set the "To" address to tutor at python.org, and DO NOT reply to a digest. Thank you. My answer to your question appears below: On Sun, Sep 09, 2012 at 03:56:22PM -0700, tayo rotimi wrote: > My first exercise: print "Game Over" does not run! Where have I missed it? The error message is as follows: > > ?File "", line 1 > ?? print "Game Over" > ??? ??? ??? ??? ??? ^ > ?SyntaxError: invalid syntax Are you using Python 3 instead of Python 2? One of the changes between the 2.x versions and the 3.x versions is that print is no longer a statement, but is now a function. That means you have to write it using round brackets (parentheses for Americans): # version 2.x print "Game Over" # version 3.x print("Game Over") For simple printing, there's not much advantage either way, but for more advanced printing, the function form is much better. -- Steven From eryksun at gmail.com Mon Sep 10 03:45:42 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 9 Sep 2012 21:45:42 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On Sun, Sep 9, 2012 at 5:58 PM, Greg Nielsen wrote: > Hello Tutor, > > Quick question. Working on a new game and want to build in a GUI. > TkInter seems to fit the bill except for one small item. Both Pygame and > TkInter create windows. (Screen in Pygame, and the Root widget in TkInter) > Is there a way to combined these two so I can use all my Pygame sprites and > objects and any TkInter bars and buttons all in one screen? My best guess > would be something along this line. I found this answer on Stack Overflow: http://stackoverflow.com/questions/8584272/using-pygame-features-in-tkinter It depends on initializing the SDL engine to use the window ID from a Tk frame, based on the 'SDL_WINDOWID' environment variable. I added a check of sys.platform == "win32" for the suggested use of 'SDL_VIDEODRIVER' on Windows, but I haven't verified that this is required or that it works. Instead of a while loop that manually pumps both SDL and Tk, I switched to using the Tk mainloop. The frame's "after" method is used to run pygame_loop every 5 ms, which updates the screen. You'll have to experiment with how this affects pygame's ability to grab keyboard/click events. You might have to use Tk for input instead. Just to show the event loop in action, I added two buttons to increment/decrement the current step size, tied to the incr_step method. import sys import os import Tkinter as tkinter import pygame class Game(object): def __init__(self, root, w, h): self.root = root self.width = w self.height = h # Tk init self.frame = tkinter.Frame(root, width=w, height=h) self.frame.grid(row=0, columnspan=2) self.button1 = tkinter.Button( root, text='-', command=lambda: self.incr_step(-1)) self.button1.grid(row=1, column=0) self.button2 = tkinter.Button( root, text='+', command=lambda: self.incr_step(1)) self.button2.grid(row=1, column=1) root.update() # pygame init os.environ['SDL_WINDOWID'] = str(self.frame.winfo_id()) if sys.platform == "win32": os.environ['SDL_VIDEODRIVER'] = 'windib' pygame.display.init() self.screen = pygame.display.set_mode((w, h)) self.bg_color = pygame.Color(0,0,0) self.fg_color = pygame.Color(255,255,255) self.position = 0 self.step = 1 self.game_loop() def game_loop(self): self.screen.fill(self.bg_color) self.position = (self.position + self.step) % self.width coord = self.position, self.height // 2 pygame.draw.circle(self.screen, self.fg_color, coord, 20) pygame.display.flip() self.frame.after(5, self.game_loop) def incr_step(self, inc): self.step += inc if __name__ == "__main__": root = tkinter.Tk() game = Game(root, 200, 200) root.mainloop() From gollumgreg407366 at gmail.com Mon Sep 10 03:59:14 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Sun, 9 Sep 2012 20:59:14 -0500 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: Eryksun, That there is some classy code work. I actually found that same answer and was about to try it when I saw your reply. It's going to take some time to figure out everything you did there and how to apply it to my project, but this is exactly what I needed. Thanks for the assist! Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 10 07:18:48 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 10 Sep 2012 01:18:48 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: Please beieve me when I say use Blender, and it's Python API. It's a 3-D app, and you can code python with it. The game engine will make it muche easier for you to do 'new age' gaming. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Sep 10 09:08:04 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Sep 2012 08:08:04 +0100 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On 10/09/2012 06:18, Dwight Hutto wrote: > Please beieve me when I say use Blender, and it's Python API. It's a 3-D > app, and you can code python with it. > > The game engine will make it muche easier for you to do 'new age' gaming. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > When replying can you please quote the context, without that the above is meaningless. Note to self, avoid http://www.hitwebdevelopment.com like the plague as the CEO has poor communication skills :) -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Mon Sep 10 10:37:11 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 10 Sep 2012 04:37:11 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On Mon, Sep 10, 2012 at 3:08 AM, Mark Lawrence wrote: > On 10/09/2012 06:18, Dwight Hutto wrote: > >> Please believe me when I say use Blender, and it's Python API. It's a 3-D >> app, and you can code python with it. >> >> The game engine will make it muche easier for you to do 'new age' gaming. >> >> And I quote: Hello Tutor, Quick question. Working on a new game and want to build in a GUI. My response:: Please believe me when I say use Blender, and it's Python API. It's a 3-D app, and you can code python with it. > >> When replying can you please quote the context, without that the above is > meaningless. > > Note to self, avoid http://www.hitwebdevelopment.**comlike the plague as the CEO has poor communication skills :) > > > Note to yourself: > Never respond with a meaningless critique, unless you can back it up. I believe I gave the OP advice he needed to utilize python, and have an GDK with is worth learning, just as easily as pygame, with much more features. P..S. The plague(virus) had great communication skills, which is why it was a plague. Do a wiki search on google. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 10 10:47:15 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 10 Sep 2012 04:47:15 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: ;) -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 10 10:55:18 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 10 Sep 2012 04:55:18 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: > Note to self, avoid http://www.hitwebdevelopment.com like the plague as > the CEO has poor communication skills :) > > Mark Lawrence. > > Point out the poor communication skills then ...Mark. Don't just use > useless propaganda. > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From finsolut2003 at yahoo.com Mon Sep 10 11:40:14 2012 From: finsolut2003 at yahoo.com (tayo rotimi) Date: Mon, 10 Sep 2012 02:40:14 -0700 (PDT) Subject: [Tutor] Help - My First Program Fails In-Reply-To: References: Message-ID: <1347270014.44482.YahooMailNeo@web162301.mail.bf1.yahoo.com> Hi Steven. Thank you for your answer below. The program now runs, using print("Game Over"). I use Python 3..; but the book - python for absolute beginner - that I have is an old (2003) edition. I don't know how this combination may affect my learning, going forward. Could you please suggest how I can something current. Regards. Tayo. My answer to your question appears below: On Sun, Sep 09, 2012 at 03:56:22PM -0700, tayo rotimi wrote: > My first exercise: print "Game Over" does not run! Where have I missed it? The error message is as follows: > > ?File "", line 1 > ?? print "Game Over" > ??? ??? ??? ??? ??? ^ > ?SyntaxError: invalid syntax Are you using Python 3 instead of Python 2? One of the changes between the 2.x versions and the 3.x versions is that print is no longer a statement, but is now a function. That means you have to write it using round brackets (parentheses for Americans): # version 2.x print "Game Over" # version 3.x print("Game Over") For simple printing, there's not much advantage either way, but for more advanced printing, the function form is much better. -- Steven -------------- next part -------------- An HTML attachment was scrubbed... URL: From gollumgreg407366 at gmail.com Mon Sep 10 15:31:36 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 10 Sep 2012 08:31:36 -0500 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: Ok kids, settle down. Quick question to Dwight; why Blender? Im not going for "new age" like that. (Personally when you spend that much time making a game look nice, the core mechinics suffer.) However, it does look rather shiny and powerful. All I really need though are some GUI components to add to my game. I could write them myself, but if someone else already did the work, why bother. Have any other recomendations or related info on Blender? Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Sep 10 15:51:28 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Sep 2012 23:51:28 +1000 Subject: [Tutor] Help - My First Program Fails In-Reply-To: <1347270014.44482.YahooMailNeo@web162301.mail.bf1.yahoo.com> References: <1347270014.44482.YahooMailNeo@web162301.mail.bf1.yahoo.com> Message-ID: <504DF060.50309@pearwood.info> On 10/09/12 19:40, tayo rotimi wrote: > Hi Steven. > > > Thank you for your answer below. The program now runs, >using print("Game Over"). > > I use Python 3..; but the book - python for absolute >beginner - that I have is an old (2003) edition. I don't >know how this combination may affect my learning, going >forward. Could you please suggest how I can something >current. You could buy a more current book that covers Python 3 :) E.g. http://www.apress.com/9781430216322 (This is not a recommendation, just the first one I stumbled across.) But honestly, there aren't that many differences between Python 2 and 3. print is the main one. There are a few others, but they are mostly advanced functionality. In my opinion, with a little bit of care and attention to detail, if you are prepared to check the notes in the Fine Manual and if necessarily ask for help here, you can learn Python 3 from a Python 2 book. It won't be *as* convenient, of course, but it will be doable. -- Steven From malaclypse2 at gmail.com Mon Sep 10 17:00:50 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 10 Sep 2012 11:00:50 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On Mon, Sep 10, 2012 at 1:18 AM, Dwight Hutto wrote: > Please beieve me when I say use Blender, and it's Python API. It's a 3-D > app, and you can code python with it. > > The game engine will make it muche easier for you to do 'new age' gaming. I don't understand how this relates to the question in the original post. Blender is used to create 3D assets for a game. It's not a game engine of its own though, is it? I thought the original question was about how to write the game engine, particularly how to have both Tk widgets and a PyGame Screen both display, so that he can take advantage of pre-built Tk widgets like buttons and list boxes, and use PyGame to render his in-game playing field. I agree that blender looks like a great way to create 3D assets for a game, but since the OP was talking about sprites, I don't think Blender is going to be of any help to him. Jerry From wprins at gmail.com Mon Sep 10 17:57:57 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 10 Sep 2012 16:57:57 +0100 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: Hi Jerry, On 10 September 2012 16:00, Jerry Hill wrote: > On Mon, Sep 10, 2012 at 1:18 AM, Dwight Hutto wrote: >> Please beieve me when I say use Blender, and it's Python API. It's a 3-D >> app, and you can code python with it. >> >> The game engine will make it muche easier for you to do 'new age' gaming. > > I don't understand how this relates to the question in the original > post. Blender is used to create 3D assets for a game. It's not a > game engine of its own though, is it? Actually it is (a game engine), and a pretty decent one at that by the looks of things, with decent Python bindings, so certainly worth mentioning to the OP. Some links: http://www.blender.org/education-help/tutorials/game-engine/ http://www.tutorialsforblender3d.com/ http://bgame.anicator.com/games/game.php?id=61 http://blenderartists.org/forum/showthread.php?256650-Quality-Blender-Games-LINKS Walter From gollumgreg407366 at gmail.com Mon Sep 10 18:34:13 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 10 Sep 2012 11:34:13 -0500 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: I will admit that the whole Blender project is cool, but Jerry has a point. All I wanted to know was how to get Pygame and TkInter to work together, and I got a solid answer about 12 hours ago. (Check out Eryksun's code, it's beyond cool, past awsome, and close to sexy.) As such, I am considering this post closed. Thank you all for your help. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Mon Sep 10 19:15:13 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 10 Sep 2012 18:15:13 +0100 Subject: [Tutor] simon says Message-ID: hi guy my book has set me an assignment of a simon says game but i don't really understand what it's asking me to do. here's the text: write a version of the simon says game where a player has to repeat an ever-growing, random sequence of colours and sounds using the keyboard. Anyone understand the task? From bgailer at gmail.com Mon Sep 10 21:23:30 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Sep 2012 15:23:30 -0400 Subject: [Tutor] simon says In-Reply-To: References: Message-ID: <504E3E32.90907@gmail.com> On 9/10/2012 1:15 PM, Matthew Ngaha wrote: > hi guy my book has set me an assignment of a simon says game but i > don't really understand what it's asking me to do. here's the text: > > write a version of the simon says game where a player has to repeat an > ever-growing, random sequence of colours and sounds using the > keyboard. > > Anyone understand the task? the best I could to is make guesses. that does not help us. what is "your book"? what have you learned so far that might give you a clue as to what is asked for? are you familiar with the "simon says game"? if not see http://en.wikipedia.org/wiki/Simon_says -- Bob Gailer 919-636-4239 Chapel Hill NC From chigga101 at gmail.com Mon Sep 10 21:24:08 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 10 Sep 2012 20:24:08 +0100 Subject: [Tutor] simon says In-Reply-To: <-8146762953963382264@unknownmsgid> References: <-8146762953963382264@unknownmsgid> Message-ID: > You should read up on the Simon Says rules and such. It's an > established, old game. Once you get that, then work on replicating it > through software. > thanks for your input. i understand Simon Says. I'm just struggling to see the connection with the assignment. a sequence of colours and sounds using the keyboard. I 'm trying to understand how this relates to the game From chigga101 at gmail.com Mon Sep 10 21:29:04 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 10 Sep 2012 20:29:04 +0100 Subject: [Tutor] simon says In-Reply-To: <504E3E32.90907@gmail.com> References: <504E3E32.90907@gmail.com> Message-ID: >> hi guy my book has set me an assignment of a simon says game but i >> don't really understand what it's asking me to do. here's the text: It's the last chapter of Python Prgogramming for the absolute beginner. they have covered all the basics. Even simple tkinter apps and Pygame games. If i understand what the task was asking me to do, im confident , even though i might struggle, that in the end i could do it. But i simply don't understand what this task is asking for. It doesn't sound similar to Simon Says From tokyo.rook at gmail.com Mon Sep 10 21:37:39 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Mon, 10 Sep 2012 15:37:39 -0400 Subject: [Tutor] Hey. trying to set a data base. Message-ID: my imports are import json import time from tools import Arguments @Arguments(mincount = 0, maxcount = 2) def rank(mgr, room, user, msg, params): if mgr.isRoomLocked(room) and not user.name == "mr": return if len(params) < 2: if len(params) == 0: name = user.name else: name = params[0] tg = ch.User(name) tgrank = mgr.getRank(tg) data = shared_db.get("level:" + tg.name) data == json.loads(data) if data[1] == "level": mgr.sendObject(room, Html("%s's rank is %s (%i), set %s ago by %s.", tg.name.title(), mgr.getRankName(tgrank).title(), tgrank, tdelta(data[3]), data[2].title())) else: if mgr.getRank(user) < 2: return name, level = params try: level = int(level) except ValueError: try: level = mgr.rankNames[level.lower()] except KeyError: return Error("Invalid rank name.") srcrank = mgr.getRank(user) tg = ch.User(name) tgrank = mgr.getRank(tg) if user == tg: return Error("You're not allowed to set your own rank, silly goose. :3") if srcrank == level: return Error("You're not allowed to set people to a higher or equal rank than you.") if tgrank == srcrank: return Error("Did you really think that would work :|. wow people are dummer than i thought.") mgr.setRank(tg, level) shared_db.set("level:" + tg.name, json.dumps([room.name, "level", user.name, time.time()])) return Html("%s's rank set to %s (%i).", tg.name.title(), mgr.getRankName(level).title(), level) thats my db.. trying to set ranks for people.and make a db so i can see how long ago i did it. and by who did it. Kawaii: [mrvjj] [error] /usr/lib/python3.2/json/decoder.py: 345: TypeError(expected string or buffer) i get that error... -- ~~Austin From swiftone at swiftone.org Mon Sep 10 21:40:49 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 10 Sep 2012 12:40:49 -0700 Subject: [Tutor] simon says In-Reply-To: References: <-8146762953963382264@unknownmsgid> Message-ID: On Mon, Sep 10, 2012 at 12:24 PM, Matthew Ngaha wrote: > thanks for your input. i understand Simon Says. I'm just struggling to > see the connection with the assignment. a sequence of colours and > sounds using the keyboard. I 'm trying to understand how this relates > to the game This seems less about "simon says" the social game, and more about "simon", the 1980s electronic toy. That toy had four colored buttons that would light up in a sequence, playing a tone for each color. The player would then have to press the buttons in the same sequence. The game would then replay the sequence and add an additional step. Player would have to enter the longer sequence in. Continue until player loses (and game made an angry buzz). It was quite addictive. -- Brett Ritter / SwiftOne swiftone at swiftone.org From emile at fenx.com Mon Sep 10 21:45:30 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Sep 2012 12:45:30 -0700 Subject: [Tutor] simon says In-Reply-To: References: <-8146762953963382264@unknownmsgid> Message-ID: On 9/10/2012 12:40 PM Brett Ritter said... > On Mon, Sep 10, 2012 at 12:24 PM, Matthew Ngaha wrote: >> thanks for your input. i understand Simon Says. I'm just struggling to >> see the connection with the assignment. a sequence of colours and >> sounds using the keyboard. I 'm trying to understand how this relates >> to the game > > This seems less about "simon says" the social game, and more about > "simon", the 1980s electronic toy. > > That toy had four colored buttons that would light up in a sequence, > playing a tone for each color. The player would then have to press > the buttons in the same sequence. The game would then replay the > sequence and add an additional step. Player would have to enter the > longer sequence in. Continue until player loses (and game made an > angry buzz). > > It was quite addictive. > Good call -- that sounds like what they're at. See http://en.wikipedia.org/wiki/Simon_%28game%29 Emile From chigga101 at gmail.com Mon Sep 10 22:19:31 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 10 Sep 2012 21:19:31 +0100 Subject: [Tutor] simon says In-Reply-To: References: <-8146762953963382264@unknownmsgid> Message-ID: > This seems less about "simon says" the social game, and more about > "simon", the 1980s electronic toy. > > That toy had four colored buttons that would light up in a sequence, > playing a tone for each color. The player would then have to press > the buttons in the same sequence. The game would then replay the > sequence and add an additional step. Player would have to enter the > longer sequence in. Continue until player loses (and game made an > angry buzz). > > It was quite addictive. this sounds like a lot of fun! time to think about how i will go about this:) Thanks for making it clear. Also @ Emile, thanks for the link. From ikit123 at hotmail.com Mon Sep 10 22:49:16 2012 From: ikit123 at hotmail.com (C.L. Shetline) Date: Mon, 10 Sep 2012 16:49:16 -0400 Subject: [Tutor] Python in Vertica Message-ID: Python 2.4.3 with Vertica Database on Linux. We are migrating from an Informix database to Vertica. We have C code and a lot of SQL Stored procedures in our Informix db that are not viable in Vertica. We are trying to convert them to Python. My first questions is: I am using pyodbc to connect to the Vertica database. When I do a select on count and print the result it displays as (for example) 4L (which is the row count plus the data type). If I try to use the variable in a conditional it does not work. I have no idea how to have data value simply be 4 ! cursor.execute("SELECT COUNT(*) from cv_gls_wkly_misc") result = cursor.fetchone() number_of_rows = result[0] print `number_of_rows The data display is the (select count(*)) and a selected row. 4L [(5185L, 93L, Decimal("42.50"), Decimal("50.36"), Decimal("3406.35"), Decimal("0"), Decimal("78.00"), Decimal("0"), Decimal("66.00"), Decimal("0"), Decimal("12.73"), Decimal("0"), Decimal("0"), Decimal("311.00"))] Regards, CVez -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Sep 10 23:20:18 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Sep 2012 14:20:18 -0700 Subject: [Tutor] Python in Vertica In-Reply-To: References: Message-ID: On 9/10/2012 1:49 PM C.L. Shetline said... > Python 2.4.3 with Vertica Database on Linux. > > We are migrating from an Informix database to Vertica. We have C code > and a lot of > SQL Stored procedures in our Informix db that are not viable in Vertica. > We are trying > to convert them to Python. > > My first questions is: > > I am using pyodbc to connect to the Vertica database. When I do a select > on count and > print the result it displays as (for example) 4L (which is the row count > plus the > data type). If I try to use the variable in a conditional Please show us this conditional and how you build it... > it does not work. ... and include the traceback so that we see both your input and the error that's output. Emile > I have no idea how to have data value simply be 4 ! > > cursor.execute("SELECT COUNT(*) from cv_gls_wkly_misc") > result = cursor.fetchone() > number_of_rows = result[0] > print `number_of_rows > > > The data display is the (select count(*)) and a selected row. > 4L > [(5185L, 93L, Decimal("42.50"), Decimal("50.36"), Decimal("3406.35"), > Decimal("0"), Decimal("78.00"), Decimal("0"), Decimal("66.00"), > Decimal("0"), Decimal("12.73"), Decimal("0"), Decimal("0"), > Decimal("311.00"))] > > Regards, > CVez > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From d at davea.name Tue Sep 11 02:24:11 2012 From: d at davea.name (Dave Angel) Date: Mon, 10 Sep 2012 20:24:11 -0400 Subject: [Tutor] Python in Vertica In-Reply-To: References: Message-ID: <504E84AB.1070103@davea.name> On 09/10/2012 04:49 PM, C.L. Shetline wrote: > > > Python 2.4.3 with Vertica Database on Linux. > > We are migrating from an Informix database to Vertica. We have C code and a lot of > SQL Stored procedures in our Informix db that are not viable in Vertica. We are trying > to convert them to Python. > > My first questions is: > > I am using pyodbc to connect to the Vertica database. When I do a select on count and > print the result it displays as (for example) 4L (which is the row count plus the > data type). If I try to use the variable in a conditional it does not work. I have no idea how > to have data value simply be 4 ! Have you tried printing type(number_of_rows) ? > cursor.execute("SELECT COUNT(*) from cv_gls_wkly_misc") > result = cursor.fetchone() > number_of_rows = result[0] > print `number_of_rows Please copy/paste the code and other messages. That last line has a syntax error. > > The data display is the (select count(*)) and a selected row. And who printed that line out? > 4L If you're claiming that's coming from the above print statement (after fixing the syntax error), then the variable number_of_rows is NOT a long or an int. Perhaps it's a string. Without knowing that, we can't tell you the best way to fix it. Perhaps you're not printing it at all, but just entering number_of_rows in the interactive interpreter. In that case, the variable might be a long object of value 4. IF that's the case, then you can convert it back to an int by something like number_of_rows = int(number_of_rows) > [(5185L, 93L, Decimal("42.50"), Decimal("50.36"), Decimal("3406.35"), Decimal("0"), Decimal("78.00"), Decimal("0"), Decimal("66.00"), Decimal("0"), Decimal("12.73"), Decimal("0"), Decimal("0"), Decimal("311.00"))] And what's that supposed to represent? And displayed by what means? -- DaveA From eryksun at gmail.com Tue Sep 11 02:33:49 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 10 Sep 2012 20:33:49 -0400 Subject: [Tutor] Pygame and TkInter In-Reply-To: References: Message-ID: On Mon, Sep 10, 2012 at 12:34 PM, Greg Nielsen wrote: > I will admit that the whole Blender project is cool, but Jerry has a point. > All I wanted to know was how to get Pygame and TkInter to work together, and > I got a solid answer about 12 hours ago. (Check out Eryksun's code, it's > beyond cool, past awsome, and close to sexy.) As such, I am considering this > post closed. Thank you all for your help. The credit goes to the answer on Stack Overflow. I just modified it a bit. Another option would be to use a pygame GUI toolkit, especially if you want full screen mode. The pygame wiki discusses two that I suppose are the most popular: http://www.pygame.org/wiki/gui From wrw at mac.com Tue Sep 11 02:26:27 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Mon, 10 Sep 2012 20:26:27 -0400 Subject: [Tutor] simon says In-Reply-To: References: Message-ID: On Sep 10, 2012, at 1:15 PM, Matthew Ngaha wrote: > hi guy my book has set me an assignment of a simon says game but i > don't really understand what it's asking me to do. here's the text: > > write a version of the simon says game where a player has to repeat an > ever-growing, random sequence of colours and sounds using the > keyboard. > > Anyone understand the task? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Sounds as though what is wanted in a Pythonic version of an early electronic game "Simon" that was marketed back in the late 70's. It was roughly Frisbee shaped although slightly larger. The top was divided into four quadrant-shaped paddles each of a different color. The game consisted of Simon generating longer and longer sequences of random color-sound flashes (each element in the sequence consisted of a momentary sound accompanied by the appropriate quadrant lighting up). After Simon had generated a sequence, the player had to duplicate it by pressing the paddles. A successful recreation of a sequence was rewarded by Simon generating a longer one, until the player finally screwed up. At that point Simon made an electronic rude noise and the device was handed on to the next player if there were multiple players. The player who succeeded in matching the longest sequence was the winner of that round. I'll bet ebay still has them for sale, and Google would get you a description that would be better than mine. -Bill From crawlzone at gmail.com Tue Sep 11 10:29:48 2012 From: crawlzone at gmail.com (Ray Jones) Date: Tue, 11 Sep 2012 01:29:48 -0700 Subject: [Tutor] Seeing response from authorization page with urllib2 Message-ID: <504EF67C.1090808@gmail.com> If I open a web page in my browser, I get a pop-up window that informs me that I need to provide authorization information. But often, in addition, that little pop-up window will give me some additional information supplied by the page itself. For example, the chromium browser pop-up might say, "The server requires a username and password. The server says: xxxxxxxxx" But when I attempt to get any part of an authorization-required page using urllib2.urlopen(), I immediately receive the 401 error. Even the intended object variable is left in an undefined state, so using info() doesn't seem to work. How can I get that information from the server? Ray From chigga101 at gmail.com Tue Sep 11 10:31:17 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 11 Sep 2012 09:31:17 +0100 Subject: [Tutor] simon says In-Reply-To: References: Message-ID: > Sounds as though what is wanted in a Pythonic version of an early electronic game "Simon" that was marketed back in the late 70's. It was roughly Frisbee shaped although slightly larger. The top was divided into four quadrant-shaped paddles each of a different color. The game consisted of Simon generating longer and longer sequences of random color-sound flashes (each element in the sequence consisted of a momentary sound accompanied by the appropriate quadrant lighting up). After Simon had generated a sequence, the player had to duplicate it by pressing the paddles. A successful recreation of a sequence was rewarded by Simon generating a longer one, until the player finally screwed up. At that point Simon made an electronic rude noise and the device was handed on to the next player if there were multiple players. The player who succeeded in matching the longest sequence was the winner of that round. > > I'll bet ebay still has them for sale, and Google would get you a description that would be better than mine. > > -Bill Thanks Bill. I did some more searching and managed to find a few new versions on youtube with altered gameplay i guess. Here's the closest to what has been described here: http://www.youtube.com/watch?v=agUABjGAJww thanks to everyone From eryksun at gmail.com Tue Sep 11 11:58:35 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Sep 2012 05:58:35 -0400 Subject: [Tutor] Seeing response from authorization page with urllib2 In-Reply-To: <504EF67C.1090808@gmail.com> References: <504EF67C.1090808@gmail.com> Message-ID: On Tue, Sep 11, 2012 at 4:29 AM, Ray Jones wrote: > > But when I attempt to get any part of an authorization-required page > using urllib2.urlopen(), I immediately receive the 401 error. Even the > intended object variable is left in an undefined state, so using info() > doesn't seem to work. How can I get that information from the server? The HTTPError object has the information you want: url, code, reason, headers -- along with the methods info, read, readline, and readlines. http://docs.python.org/library/urllib2#urllib2.HTTPError For example, if you catch the error as e, then you can look at e.headers['www-authenticate'] to find the realm. Basic HTTP Authentication: http://docs.python.org/library/urllib2#examples You can also use an HTTPPasswordMgrWithDefaultRealm with a catch-all realm (realm=None): pass_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() auth_handler = urllib2.HTTPBasicAuthHandler(pass_mgr) auth_handler.add_password( realm=None, uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib2.build_opener(auth_handler) Optionally, install the opener: urllib2.install_opener(opener) Or just use opener.open(). From afowler2 at broncos.uncfsu.edu Tue Sep 11 18:08:11 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Tue, 11 Sep 2012 16:08:11 +0000 Subject: [Tutor] Question Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F391BA5@BL2PRD0710MB363.namprd07.prod.outlook.com> I have a question. In a assignment it asks for me to do the following below... if "peek" then print the Student object at the beginning of the list (using __str__) but don't remove it from the list; Could you explain what it means? This is what I have so far, elif ask == "peek": print("First Name In List =", names[0]) How would you make it a string? I know have a example of it but I'm not sure how to apply it to my code...The example is below. def __str__(self): return self.sides + "\t" + self.value Also below is part of the assignment and my whole code is in the attachment. A "main" function which does the following: (1) create an empty list; (2) ask the user if he/she wants to perform a list operation. if "yes": (a) prompt the user for the operation: "test", "peek", "add", or "remove"; (b) perform the operation: (i) if "test" then print whether the list is empty or not; (ii) if "peek" then print the Student object at the beginning of the list (using __str__) but don't remove it from the list; (iii) if "add", then prompt the user for student info, make a Student object containing that info, and add that Student object to the end of the list; (iv) if "remove", then delete the Student object at the beginning of the list and print it using __str__; repeat step (2) until the user enters "no"; (3) neatly print the entire list from beginning to end. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: StudentTester.py Type: application/octet-stream Size: 960 bytes Desc: StudentTester.py URL: From mylesbroomes at hotmail.co.uk Tue Sep 11 18:51:21 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Tue, 11 Sep 2012 16:51:21 +0000 Subject: [Tutor] Tkinter GUI Message-ID: I'm coding a GUI program which presents the user with a resteraunt menu, and allows them to choose how much of each item they want to purchase before ordering. Here is my code: #Order up GUI program #User is presented with a simple resturaunt menu #They then select the items they want to order and then they are presented with the total billfrom tkinter import *class Application(Frame): """Based on the frame class, the application widget holds all other widgets. """ def __init__(self,master): """Initialise the frame. """ super(Application,self).__init__(master) self.grid() self.create_widgets() self.total=0 self.spag_ent_check=True self.tater_ent_check=True self.soup_ent_check=True self.fish_ent_check=True self.spag_cost=5.15 self.tater_cost=4.70 self.soup_cost=4.20 self.fish_cost=5.95 def create_widgets(self): """Create all of the widgets in the program. """ Label(self,text="Select the items you want to order:").grid(row=0,column=0,sticky=W) Label(self,text="Quantity:").grid(row=0,column=0,sticky=E) Label(self,text="Spaghetti Bolognese (5.15)").grid(row=1,column=0,sticky=W) self.spag_ent=Entry(self) self.spag_ent.grid(row=1,column=0,sticky=E) Label(self,text="Potato Salad (4.70)").grid(row=2,column=0,sticky=W) self.tater_ent=Entry(self) self.tater_ent.grid(row=2,column=0,sticky=E) Label(self,text="Chicken Soup (4.20)").grid(row=3,column=0,sticky=W) self.soup_ent=Entry(self) self.soup_ent.grid(row=3,column=0,sticky=E) Label(self,text="Smoked Salmon (5.95)").grid(row=4,column=0,sticky=W) self.fish_ent=Entry(self) self.fish_ent.grid(row=4,column=0,sticky=E) Label(self,text="Total Bill:").grid(row=7,column=0,sticky=W) self.bill_txt=Text(self,height=10,wrap=WORD) self.bill_txt.grid(row=8,column=0,sticky=W) Button(self,text="Order Up!",command=self.calc_total).grid(row=5,column=0,sticky=W) def calc_total(self): """Update the text widget if they order Spaghetti Bolognese. """ try: int(spag_ent.get()) except: message="You have to enter a number in the quantity box. \n" self.bill_txt.delete(0.0,END) self.bill_txt.insert(0.0,message) self.spag_ent_check=False # set to False if user enters anything other than an integer in the entry widget if self.spag_ent_check: spag_quant=self.spag_ent.get() spag_total=self.spag_cost*spag_quant self.total+=spag_total try: int(tater_ent.get()) except: message="You have to enter a number in the quantity box. \n" self.bill_txt.delete(0.0,END) self.bill_txt.insert(0.0,message) self.tater_ent_check=False # set to False if user enters anything other than an integer in the entry widget if self.tater_ent_check: tater_quant=self.tater_ent.get() tater_total=self.tater_cost*tater_quant self.total+=tater_total try: int(soup_ent.get()) except: message="You have to enter a number in the quantity box. \n" self.bill_txt.delete(0.0,END) self.bill_txt.insert(0.0,message) self.soup_ent_check=False # set to False if user enters anything other than an integer in the entry widget if self.soup_ent_check: soup_quant=self.soup_ent.get() soup_total=self.soup_cost*soup_quant self.total+=soup_total try: int(fish_ent.get()) except: message="You have to enter a number in the quantity box. \n" self.bill_txt.delete(0.0,END) self.bill_txt.insert(0.0,message) self.fish_ent_check=False # set to False if user enters anything other than an integer in the entry widget if self.fish_ent_check: fish_quant=self.fish_ent.get() fish_total=self.fish_cost*fish_quant self.total+=fish_total self.bill_txt.delete(0.0,END) self.bill_txt.insert(0.0,self.total)#main root=Tk() root.title("Order Up!") app=Application(root) root.mainloop() The 'calc_total' function is supposed to calculate the users bill and then display it in the text widget, but every time I try it, it comes up as 0. Can anyone help me? Thanks in advance,Myles Broomes -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Sep 11 21:10:43 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Sep 2012 12:10:43 -0700 (PDT) Subject: [Tutor] Tkinter GUI In-Reply-To: References: Message-ID: <1347390643.74018.YahooMailNeo@web110706.mail.gq1.yahoo.com> >??? def calc_total(self): >??????? """Update the text widget if they order Spaghetti Bolognese. """ >??????? try: >??????????? int(spag_ent.get()) >??????? except: >??????????? message="You have to enter a number in the quantity box. \n" >??????? >The 'calc_total' function is supposed to calculate the users bill and then display it in the text widget, but every time I try it, it comes up as 0. Can anyone help me? >? It struck me that you're not assigning int(spag_ent.get()) to any variable: spaghettiAmount = int(spag_ent.get()) Moreover, I'd try to create the program in such a way that it doesn't become a headache to change the menu (for instance, to add a new pasta). Perhaps by using a dctionary as a parameter: menu = {"spaghetti": 4.50, "macaroni": 2.10, "calzone": 6.00} Your example reminds me of one chapter of Head First Design Patterns (O'Reilly). Would be interesting to compare your approach with the one in the book. Albert-Jan From ascheel at gmail.com Tue Sep 11 21:34:08 2012 From: ascheel at gmail.com (Art Scheel) Date: Tue, 11 Sep 2012 13:34:08 -0600 Subject: [Tutor] 'class' for someone with no object oriented programming experience Message-ID: I can vaguely follow object oriented code. I can handle the basic stuff like string manipulation and functions just fine for the most part. Classes elude me almost entirely. I've followed the tutorials at http://bit.ly/MCAhYx and http://goo.gl/c170V but in neither one do classes click. I can't progress past that because it's such a core element to python, it's like building a car from the ground up but never learning how to add oil. For instance... exercises 40-43 make no sense to me: http://learnpythonthehardway.org/book/ex40.html I simply can't understand it. I'm not a fool, I've been able to handle a few other programming languages. I can handle SQL. I can build entire servers. I just can't handle classes in python. As an example, I am going to reference this: http://stackoverflow.com/questions/6671620/list-users-in-irc-channel-using-twisted-python-irc-framework I know what it's referencing in the twisted library at this link: http://twistedmatrix.com/trac/browser/trunk/twisted/words/im/ircsupport.py#L160 I've also tried implementing it myself, but I don't understand what it's doing so I fail and I throw errors. Are there any better resources for learning classes for someone who's never touched object oriented programming in the past besides basic interpretation for debugging purposes? -- Molon Labe "Come and take them" "The Marines I have seen around the world have the cleanest bodies, the filthiest minds, the highest morale, and the lowest morals of any group of animals I have ever seen. Thank God for the United States Marine Corps!" -Eleanor Roosevelt -------------- next part -------------- An HTML attachment was scrubbed... URL: From terrence.brannon at bankofamerica.com Tue Sep 11 22:00:45 2012 From: terrence.brannon at bankofamerica.com (Brannon, Terrence) Date: Tue, 11 Sep 2012 16:00:45 -0400 Subject: [Tutor] 'class' for someone with no object oriented programming experience In-Reply-To: References: Message-ID: <7F78496735D9004BA98D1FDC256C9C71B15B9D@smtp_mail.bankofamerica.com> From: Tutor [mailto:tutor-bounces+terrence.brannon=bankofamerica.com at python.org] On Behalf Of Art Scheel Sent: Tuesday, September 11, 2012 3:34 PM To: tutor at python.org Subject: [Tutor] 'class' for someone with no object oriented programming experience Are there any better resources for learning classes for someone who's never touched object oriented programming in the past besides basic interpretation for debugging purposes? [Terrence Brannon] Why don't you read this http://docs.python.org/tutorial/classes.html and write to this list regarding the first thing you don't understand. ---------------------------------------------------------------------- This message w/attachments (message) is intended solely for the use of the intended recipient(s) and may contain information that is privileged, confidential or proprietary. If you are not an intended recipient, please notify the sender, and then please delete and destroy all copies and attachments, and be advised that any review or dissemination of, or the taking of any action in reliance on, the information contained in or attached to this message is prohibited. Unless specifically indicated, this message is not an offer to sell or a solicitation of any investment products or other financial product or service, an official confirmation of any transaction, or an official statement of Sender. Subject to applicable law, Sender may intercept, monitor, review and retain e-communications (EC) traveling through its networks/systems and may produce any such EC to regulators, law enforcement, in litigation and as required by law. The laws of the country of each sender/recipient may impact the handling of EC, and EC may be archived, supervised and produced in countries other than the country in which you are located. This message cannot be guaranteed to be secure or free of errors or viruses. References to "Sender" are references to any subsidiary of Bank of America Corporation. Securities and Insurance Products: * Are Not FDIC Insured * Are Not Bank Guaranteed * May Lose Value * Are Not a Bank Deposit * Are Not a Condition to Any Banking Service or Activity * Are Not Insured by Any Federal Government Agency. Attachments that are part of this EC may have additional important disclosures and disclaimers, which you should read. This message is subject to terms available at the following link: http://www.bankofamerica.com/emaildisclaimer. By messaging with Sender you consent to the foregoing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From terrence.brannon at bankofamerica.com Tue Sep 11 21:57:17 2012 From: terrence.brannon at bankofamerica.com (Brannon, Terrence) Date: Tue, 11 Sep 2012 15:57:17 -0400 Subject: [Tutor] Question In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F391BA5@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F391BA5@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <7F78496735D9004BA98D1FDC256C9C71B15B9B@smtp_mail.bankofamerica.com> From: Tutor [mailto:tutor-bounces+terrence.brannon=bankofamerica.com at python.org] On Behalf Of Ashley Fowler Sent: Tuesday, September 11, 2012 12:08 PM To: tutor at python.org Subject: [Tutor] Question I have a question. In a assignment it asks for me to do the following below... if "peek" then print the Student object at the beginning of the list (using __str__) but don't remove it from the list; Could you explain what it means? This is what I have so far, elif ask == "peek": print("First Name In List =", names[0]) How would you make it a string? [Terrence Brannon] print("First name in List ={0}".format(names[0])) ---------------------------------------------------------------------- This message w/attachments (message) is intended solely for the use of the intended recipient(s) and may contain information that is privileged, confidential or proprietary. If you are not an intended recipient, please notify the sender, and then please delete and destroy all copies and attachments, and be advised that any review or dissemination of, or the taking of any action in reliance on, the information contained in or attached to this message is prohibited. Unless specifically indicated, this message is not an offer to sell or a solicitation of any investment products or other financial product or service, an official confirmation of any transaction, or an official statement of Sender. Subject to applicable law, Sender may intercept, monitor, review and retain e-communications (EC) traveling through its networks/systems and may produce any such EC to regulators, law enforcement, in litigation and as required by law. The laws of the country of each sender/recipient may impact the handling of EC, and EC may be archived, supervised and produced in countries other than the country in which you are located. This message cannot be guaranteed to be secure or free of errors or viruses. References to "Sender" are references to any subsidiary of Bank of America Corporation. Securities and Insurance Products: * Are Not FDIC Insured * Are Not Bank Guaranteed * May Lose Value * Are Not a Bank Deposit * Are Not a Condition to Any Banking Service or Activity * Are Not Insured by Any Federal Government Agency. Attachments that are part of this EC may have additional important disclosures and disclaimers, which you should read. This message is subject to terms available at the following link: http://www.bankofamerica.com/emaildisclaimer. By messaging with Sender you consent to the foregoing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 11 23:09:54 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Sep 2012 17:09:54 -0400 Subject: [Tutor] Question In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F391BA5@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F391BA5@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Tue, Sep 11, 2012 at 12:08 PM, Ashley Fowler wrote: > > I have a question. In a assignment it asks for me to do the following > below... > > if "peek" then print the Student object at the beginning > of the list (using __str__) but don't remove it from > the list; > > > Could you explain what it means? The __str__ special method of an object will be called when passed to the built-in str() constructor. This method is required to return a string. For example, here's a class with an __str__ method that prints "calling __str__" to the screen in addition to returning the string "eggs". This demonstrates some of the ways __str__ is implicitly called. class Spam: def __str__(self): print("calling __str__") return "eggs" >>> s = Spam() >>> str(s) calling __str__ 'eggs' >>> "spam and {}".format(s) calling __str__ 'spam and eggs' >>> print(s) calling __str__ eggs Make sure __str__ returns a suitable string representation of the student. The assignment should specify the string formatting of Student objects. From ashish.makani at gmail.com Tue Sep 11 23:19:23 2012 From: ashish.makani at gmail.com (ashish makani) Date: Wed, 12 Sep 2012 02:49:23 +0530 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked Message-ID: Hi Python Tutor folks I am stuck with an issue, so am coming to the Pythonistas who rescue me everytime :) I am trying to send out email programmatically, from a gmail a/c, using smtplib, using the following chunk of code (b/w [ & ] below) [ import smtplib from email.mime.text import MIMEText #uname, pwd are username & password of gmail a/c i am trying to send from server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() # get response(220, '2.0.0 Ready to start TLS') server.login(uname,pwd) # get response(235, '2.7.0 Accepted') toaddrs = ['x at gmail.com', 'y at gmail.com' ] # list of To email addresses msg = MIMEText('email body') msg['Subject'] = 'email subject' server.sendmail(fromaddr, toaddrs, msg.as_string()) ] The code above works perfectly fine on my local machine, but fails on the production server at the university where i work( all ports other than port 80 are blocked) :( So , when i try to run the 2 py statements (in bold below) on a python prompt from the production server, which has port 587 blocked, i get the following error { *>>> import smtplib* *>>> server = smtplib.SMTP('smtp.gmail.com:587')* Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.6/smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "/usr/lib/python2.6/socket.py", line 514, in create_connection raise error, msg socket.error: [Errno 101] Network is unreachable } 1. How can i overcome this ? A friend suggested , that i could use something called smtp relay, which would solve my problem, but would be time-consuming & a pain to set up. I did some cursory googling & searching on stackoverflow but could not find any good, well explained results. I dont know anything about SMTP. Anybody has any recommendations on a good explanation on smtp relay & how to set it up for sending email from a gmail a/c using a python script ? 2. Also, is there a more elegant/cleaner/graceful solution to my problem than using an smtp relay ? Any & all explanations/links/code snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor community would be greatly appreciated. Thanks a ton cheers ashish email : ashish.makani domain:gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Sep 11 23:26:50 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Sep 2012 14:26:50 -0700 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: On 9/11/2012 2:19 PM ashish makani said... > Hi Python Tutor folks > > I am stuck with an issue, so am coming to the Pythonistas who rescue me > everytime :) > > I am trying to send out email programmatically, from a gmail a/c, using > smtplib, using the following chunk of code (b/w [ & ] below) > > [ > > import smtplib > from email.mime.text import MIMEText > > #uname, pwd are username & password of gmail a/c i am trying to send from > > server = smtplib.SMTP('smtp.gmail.com:587 ') > server.starttls() # get response(220, '2.0.0 Ready to start TLS') > server.login(uname,pwd) # get response(235, '2.7.0 Accepted') > > toaddrs = ['x at gmail.com ', 'y at gmail.com > ' ] # list of To email addresses > msg = MIMEText('email body') > msg['Subject'] = 'email subject' > server.sendmail(fromaddr, toaddrs, msg.as_string()) > > > ] > > The code above works perfectly fine on my local machine, but fails on > the production server at the university where i work( all ports other > than port 80 are blocked) :( Good -- the university is taking steps to block spam. You should send mail using the university mail system and not smtp.gmail.com. Emile From ashish.makani at gmail.com Tue Sep 11 23:44:08 2012 From: ashish.makani at gmail.com (ashish makani) Date: Wed, 12 Sep 2012 03:14:08 +0530 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: Folks, some more context so people presume we are spammers :) These emails are automated diagnostic emails sent to a group of a few admins, so we get notified when a python heartbeat script, detects a failure in things like n/w connectivity, router status, etc. We dont use university email, we use gmail. Emile, Please don't presume people's intentions (that we are sending spam) & judge people without knowing anything about them. We are a tiny startup trying to connect rural communities using voice & ivr systems - http://gramvaani.org/ Best, ashish On Wed, Sep 12, 2012 at 2:56 AM, Emile van Sebille wrote: > On 9/11/2012 2:19 PM ashish makani said... > >> Hi Python Tutor folks >> >> I am stuck with an issue, so am coming to the Pythonistas who rescue me >> everytime :) >> >> I am trying to send out email programmatically, from a gmail a/c, using >> smtplib, using the following chunk of code (b/w [ & ] below) >> >> [ >> >> import smtplib >> from email.mime.text import MIMEText >> >> #uname, pwd are username & password of gmail a/c i am trying to send from >> >> server = smtplib.SMTP('smtp.gmail.com:**587 < >> http://smtp.gmail.com:587/>') >> >> server.starttls() # get response(220, '2.0.0 Ready to start TLS') >> server.login(uname,pwd) # get response(235, '2.7.0 Accepted') >> >> toaddrs = ['x at gmail.com ', 'y at gmail.com >> ' ] # list of To email addresses >> >> msg = MIMEText('email body') >> msg['Subject'] = 'email subject' >> server.sendmail(fromaddr, toaddrs, msg.as_string()) >> >> >> ] >> >> The code above works perfectly fine on my local machine, but fails on >> the production server at the university where i work( all ports other >> than port 80 are blocked) :( >> > > Good -- the university is taking steps to block spam. > > You should send mail using the university mail system and not > smtp.gmail.com. > > Emile > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Sep 11 23:58:09 2012 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 11 Sep 2012 14:58:09 -0700 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: On Tue, Sep 11, 2012 at 2:44 PM, ashish makani wrote: > Folks, > > some more context so people presume we are spammers :) > > These emails are automated diagnostic emails sent to a group of a few > admins, so we get notified when a python heartbeat script, detects a > failure in things like n/w connectivity, router status, etc. > We dont use university email, we use gmail. > > Emile, > Please don't presume people's intentions (that we are sending spam) & > judge people without knowing anything about them. > We are a tiny startup trying to connect rural communities using voice & > ivr systems - http://gramvaani.org/ > > I think you might have been presuming Emile's intention too... Blocking port 587 is a standard, prudent, and correct action for the university (ANY network that allows guest access, actually) to take to help prevent spam. The problem is that you (and I do, truly, presume that your intentions are honorable) would not be the only person/system that could use port 587 if it were unblocked. Sure, we trust YOU - but what about everybody else? So there are several ways to go about this: - the standard way, which would be to use the university's SMTP server - which can require a username/password before sending; not perfect but better than nothing - you can work with the university's network admin to grant you or your app an exception to the firewall rule - IF their firewall, and their policies, allow such an exception - you could establish a VPN tunnel to some server outside of the university's network and send from port 587 on THAT machine. Complicated, weird, and not horribly secure. But doable. > Best, > ashish > > > On Wed, Sep 12, 2012 at 2:56 AM, Emile van Sebille wrote: > >> On 9/11/2012 2:19 PM ashish makani said... >> >>> Hi Python Tutor folks >>> >>> I am stuck with an issue, so am coming to the Pythonistas who rescue me >>> everytime :) >>> >>> I am trying to send out email programmatically, from a gmail a/c, using >>> smtplib, using the following chunk of code (b/w [ & ] below) >>> >>> [ >>> >>> import smtplib >>> from email.mime.text import MIMEText >>> >>> #uname, pwd are username & password of gmail a/c i am trying to send from >>> >>> server = smtplib.SMTP('smtp.gmail.com:**587 < >>> http://smtp.gmail.com:587/>') >>> >>> server.starttls() # get response(220, '2.0.0 Ready to start TLS') >>> server.login(uname,pwd) # get response(235, '2.7.0 Accepted') >>> >>> toaddrs = ['x at gmail.com ', 'y at gmail.com >>> ' ] # list of To email addresses >>> >>> msg = MIMEText('email body') >>> msg['Subject'] = 'email subject' >>> server.sendmail(fromaddr, toaddrs, msg.as_string()) >>> >>> >>> ] >>> >>> The code above works perfectly fine on my local machine, but fails on >>> the production server at the university where i work( all ports other >>> than port 80 are blocked) :( >>> >> >> Good -- the university is taking steps to block spam. >> >> You should send mail using the university mail system and not >> smtp.gmail.com. >> >> Emile >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Sep 11 23:59:13 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 11 Sep 2012 22:59:13 +0100 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: Hi Ashish, On 11 September 2012 22:44, ashish makani wrote: > These emails are automated diagnostic emails sent to a group of a few > admins, so we get notified when a python heartbeat script, detects a failure > in things like n/w connectivity, router status, etc. > We dont use university email, we use gmail. > > Emile, > Please don't presume people's intentions (that we are sending spam) & judge > people without knowing anything about them. > We are a tiny startup trying to connect rural communities using voice & ivr > systems - http://gramvaani.org/ OK, well I'm sure you can see how an apparent newbie asking to get out of a university network without any explanation can be seem um, suspect, so I think Emile's response was reasonable. I must further note that I can't actually see how/where your request actually fits under the projects listed by that site. So, colour me still a bit sceptical, but I'll give you the benefit of the doubt. So then, given that you can only get out on port 80, your only real option the way I see it is to write a small web service, maybe a SOAP or preferably ReST service, to run on e.g. Google APP engine that will do the emailing for you. Of course, you'll have to consider whether to implement some security yourself if you use port 80 as the data going over the wire will be sent unencrypted. It may not be a problem but then again it may. Note, alternatively you can perhaps also use https (port 443), if that's also open as that will give you end-to-end encryption for free. (But I have no idea and suspect that this may also introduce a boatload of other complications...) Walter From ashish.makani at gmail.com Wed Sep 12 00:27:04 2012 From: ashish.makani at gmail.com (ashish makani) Date: Wed, 12 Sep 2012 03:57:04 +0530 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: Walter, Marc, Thanks for your helpful suggestions & super quick replies. As a noobie, i often run into brick walls, thinking something(problem i am stuck at) is not possible to do in python. I love struggling against that problem & figuring a way out. I have posted to the tutor mailing list in the past & the community here has always been amazingly welcoming & super helpful, so as a n00b, i was just a little taken aback &surprised at Emil's not particularly helpful , yet completely accurate response :) Marc, your 3rd point, > you could establish a VPN tunnel to some server outside of the > university's network and send from port 587 on THAT machine. Complicated, > weird, and not horribly secure. But doable. Could you point me to a good link/resource on how to do this ? Walter, you suggested writing a web service running somewhere else (e.g. Google Apps, AWS, etc) which i could request from my python code, which in turn would do the emailing. Can you point me to any good links/example code which might explain writing a simple SOAP/ReST web service using port80(http) or preferably, 443(https). I know nothing about web services, but could this web service essentially be the python email code, i mentioned in my original post, if i run it on Google App Engine ? Thanks a ton, Best, ashish On Wed, Sep 12, 2012 at 3:29 AM, Walter Prins wrote: > Hi Ashish, > > On 11 September 2012 22:44, ashish makani wrote: > > These emails are automated diagnostic emails sent to a group of a few > > admins, so we get notified when a python heartbeat script, detects a > failure > > in things like n/w connectivity, router status, etc. > > We dont use university email, we use gmail. > > > > Emile, > > Please don't presume people's intentions (that we are sending spam) & > judge > > people without knowing anything about them. > > We are a tiny startup trying to connect rural communities using voice & > ivr > > systems - http://gramvaani.org/ > > OK, well I'm sure you can see how an apparent newbie asking to get out > of a university network without any explanation can be seem um, > suspect, so I think Emile's response was reasonable. I must further > note that I can't actually see how/where your request actually fits > under the projects listed by that site. So, colour me still a bit > sceptical, but I'll give you the benefit of the doubt. > > So then, given that you can only get out on port 80, your only real > option the way I see it is to write a small web service, maybe a SOAP > or preferably ReST service, to run on e.g. Google APP engine that will > do the emailing for you. Of course, you'll have to consider whether > to implement some security yourself if you use port 80 as the data > going over the wire will be sent unencrypted. It may not be a problem > but then again it may. Note, alternatively you can perhaps also use > https (port 443), if that's also open as that will give you end-to-end > encryption for free. (But I have no idea and suspect that this may > also introduce a boatload of other complications...) > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Sep 12 00:26:34 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 11 Sep 2012 15:26:34 -0700 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: On 9/11/2012 2:44 PM ashish makani said... > Emile, > Please don't presume people's intentions (that we are sending spam) & > judge people without knowing anything about them. I made no such presumption -- I appluad the university for taking appropriate actions to reduce the spread of spam. Perhaps you're not familiar with spam botnets. See http://en.wikipedia.org/wiki/Botnet Emile From d at davea.name Wed Sep 12 00:33:03 2012 From: d at davea.name (Dave Angel) Date: Tue, 11 Sep 2012 18:33:03 -0400 Subject: [Tutor] Python in Vertica In-Reply-To: References: , <504E84AB.1070103@davea.name> Message-ID: <504FBC1F.8020702@davea.name> A couple of points of order: please do a reply-all, or equivalent, so your response goes to the forum, and not just to one person. or you can add tutor at python.org to it, if that seem easier. Also, please don't top-post on the forum, unless you're deleting all context. And you usually shouldn't delete all of it, just the parts that aren't relevant. On 09/11/2012 09:18 AM, C.L. Shetline wrote: >>> If you're claiming that's coming from the above print statement (after > fixing the syntax error), then the variable number_of_rows is NOT a long > or an int. Perhaps it's a string. Without knowing that, we can't tell > you the best way to fix it. > > Yes, it is coming from the print (claiming? Would I lie about that?). And no, there was not a syntax error, it was a Not lie, but you might have been mistaken. Now that I see all the code, I know you were not mistaken. > cut and paste error. Since only part of the line was included, it gives a syntax error. Now that I see the whole line, I realize what happened. See below. > > This is the entire small test script: > > #!/usr/bin/python > > import pyodbc > import time > import os > import sys > > > cnstr = "DSN=dwprod;PWD=S at 1b@b at 18;Charset=UTF-8" > targetSchema = 'public' > > cnxn = pyodbc.connect(cnstr, autocommit=False) > cursor = cnxn.cursor() > > > cursor.execute("SELECT COUNT(*) from cv_gls_wkly_misc") > result = cursor.fetchone() > number_of_rows = result[0] > print `number_of_rows` Here you're using a deprecated form of syntax. The backquotes mean to call repr() on the object inside. The repr() function tries to give you enough characters that you could reproduce the object. Just remove the backquotes, and you won't see the trailing L. print number_of_rows > > cursor.execute('SELECT * FROM cv_gls_wkly_misc where period_gen_key = 5185') > print cursor.fetchall() > > > cursor.close() > cnxn.close() > > It is executed from the command line: > > vertica1:dbadmin:/pro/COLEGIFT/source/fix/cece/sistest> ./sisupd1.py > 4L > [(5185L, 93L, Decimal("42.50"), Decimal("50.36"), Decimal("3406.35"), Decimal("0"), Decimal("78.00"), Decimal("0"), Decimal("66.00"), Decimal("0"), Decimal("12.73"), Decimal("0"), Decimal("0"), Decimal("311.00"))] > > I do not know why it is printing a data type along with the value. I do not know if this is a Python issue or a Vertica issue. > > Regards, > CVez > -- DaveA From marc.tompkins at gmail.com Wed Sep 12 01:37:05 2012 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 11 Sep 2012 16:37:05 -0700 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: On Tue, Sep 11, 2012 at 3:27 PM, ashish makani wrote: > Marc, > your 3rd point, > >> you could establish a VPN tunnel to some server outside of the >> university's network and send from port 587 on THAT machine. Complicated, >> weird, and not horribly secure. But doable. > > Could you point me to a good link/resource on how to do this ? > Hmmm... having said that, I'm puzzling over the simplest way to actually do it. First idea (based on stuff I've set up in the past): - at your outside location, set up a VPN endpoint/router, with your SMTP server sitting behind it - on your computer inside the university's network, install a VPN client and establish the tunnel before launching your script I am very fond of pfSense as a router/firewall; it has OpenVPN support baked in, and if you install the "OpenVPN Client Export Utility" package (a single click, once pfSense is installed) it will export a ready-made configuration file for the remote machine. Two things: - as I said, this is a complicated and weird way to do this, although it's probably more secure than I thought when I first mentioned it. But it's probably NOT the best way to go about it. - somebody out there, with better Python chops than I, will no doubt point out a way to do the same thing all in Python. Even if this were the proper approach, I'm not guaranteeing it's the best way to implement it. If you do decide to go this way, you'll need a machine (it could even be a virtual machine, but I find it much simpler to use an old junker PC with two network cards) to run pfSense, and of course an SMTP server. I'd just like to add a quick endorsement for pfSense in general, by the way - it's free and open-source, but I have yet to find anything it doesn't do, and do well, compared to Cisco/Juniper/SonicWall/etc. Of course, the old junker PC you run it on needs to be in decent working condition - stable power supply (and power!), no flaky memory or unstable NICs - but it doesn't need to be very new or very powerful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From afowler2 at broncos.uncfsu.edu Wed Sep 12 04:23:25 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 12 Sep 2012 02:23:25 +0000 Subject: [Tutor] Constructing a object Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F391D26@BL2PRD0710MB363.namprd07.prod.outlook.com> How do you construct a object using variables? For instance I have to construct a student object, by first prompting the user to enter variables for the Student class (their first and last names, credits and gpa) then construct a Student object using those variables. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 12 06:30:01 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 00:30:01 -0400 Subject: [Tutor] Constructing a object In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F391D26@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F391D26@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Tue, Sep 11, 2012 at 10:23 PM, Ashley Fowler wrote: > How do you construct a object using variables? > > For instance I have to construct a student object, by first prompting > the user to enter variables for the Student class (their first and last > names, credits and gpa) then construct a Student object using those > variables. > > First you want to collect the variables from the user, like so: > >>> student_first_name = raw_input("Enter First Name: ") Enter First Name: David >>> Then I would init the class with these variable, and return a tuple, or dict. If I'm getting the question you're asking correctly. Except I'd just use a function to call(instead of a class, but this might be the assignment given to you), and collect it there, then write the data to a db, or a custom db file. Or you could call the class without init, then go through the input in different functions by defining them as self.first_name = raw_input("Enter First Name: "), collect those into a return value, and pass them through another function/class that inserted the data into a db. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 12 07:01:42 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 01:01:42 -0400 Subject: [Tutor] How to send email from a gmail a/c using smtp when port 587(smtp) is blocked In-Reply-To: References: Message-ID: Why don't you ask the university to setup a password protection on port 587 to allow access to specific users, and then they can monitor the incoming/outgoing connections identified by the user name? As well as encryption known by the university to monitor activity on other levels. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Sep 12 07:10:23 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 12 Sep 2012 01:10:23 -0400 Subject: [Tutor] Constructing a object In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F391D26@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F391D26@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Tue, Sep 11, 2012 at 10:23 PM, Ashley Fowler wrote: > How do you construct a object using variables? > > For instance I have to construct a student object, by first prompting the > user to enter variables for the Student class (their first and last names, > credits and gpa) then construct a Student object using those variables. You need to write a function that gets user input and converts it where appropriate (e.g. int, float). def make_student_from_input(): # input and convert first_name = ... last_name = ... num_credits = ... gpa = ... return Student(first_name, last_name, num_credits, gpa) This assumes the Student initializer (__init__) is as follows: class Student(object): def __init__(self, first_name, last_name, num_credits, gpa): # ... The constructor supplies the 'self' argument in position 0. The rest, if supplied as "positional" arguments, need to be provided in exactly the same order as the argument list. The names do not matter. Whatever argument is in position 1 will be assigned to the local variable 'first_name'. Whatever argument is in position 4 will be assigned to the local variable 'gpa'. On the other hand, if you supply each argument name as a "keyword", you're free to list them in any order. For example: first_name, last_name = 'John', 'Doe' num_credits, gpa = 60, 3.5 student = Student( gpa=gpa, num_credits=num_credits, last_name=last_name, first_name=first_name) From dvnsarma at gmail.com Wed Sep 12 07:17:07 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 12 Sep 2012 10:47:07 +0530 Subject: [Tutor] Musical note on python Message-ID: How to produce a musical note of given frequency,volume and duration in Python. -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 12 08:46:37 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 02:46:37 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system("speaker-test" + " --frequency 2000" + " --period 5000" + " --test sine") -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Sep 12 08:47:11 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Sep 2012 07:47:11 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/2012 06:17, D.V.N.Sarma ??.??.???.???? wrote: > How to produce a musical note of given frequency,volume and duration in > Python. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please give an indication of the research that you've done, the code that you've tried, the target OS, Python version number and the issues that you have before you post a question like this. -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Wed Sep 12 08:49:24 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 02:49:24 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 2:46 AM, Dwight Hutto wrote: > Python 2.7.3 (default, Aug 1 2012, 05:16:07) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.system("speaker-test" + " --frequency 2000" + " --period 5000" + " --test sine") > > Although there are other ways. Check out the python docs: > > http://docs.python.org/library/subprocess.html > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 12 08:57:00 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 02:57:00 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 2:47 AM, Mark Lawrence wrote: > On 12/09/2012 06:17, D.V.N.Sarma ??.??.???.???? wrote: > >> How to produce a musical note of given frequency,volume and duration in >> Python. >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> > Please give an indication of the research that you've done, the code that > you've tried, the target OS, Python version number and the issues that you > have before you post a question like this. > Apologies, > Forgot to mention I was using Ubuntu for this. However, I'm sure he's > going to want to initiate a command line app for this(no matter the OS, > unless he uses a python module), and define switches/params, even if he > wants to put it in an app. > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Sep 12 09:17:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Sep 2012 08:17:15 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/2012 07:57, Dwight Hutto wrote: > On Wed, Sep 12, 2012 at 2:47 AM, Mark Lawrence wrote: > >> On 12/09/2012 06:17, D.V.N.Sarma ??.??.???.???? wrote: >> >>> How to produce a musical note of given frequency,volume and duration in >>> Python. >>> >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >>> >> Please give an indication of the research that you've done, the code that >> you've tried, the target OS, Python version number and the issues that you >> have before you post a question like this. > > > >> Apologies, >> Forgot to mention I was using Ubuntu for this. However, I'm sure he's >> going to want to initiate a command line app for this(no matter the OS, >> unless he uses a python module), and define switches/params, even if he >> wants to put it in an app. >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Where have you forgotten to mention Ubuntu? "I'm sure...", the OP has specifically said "in Python", which implies to me using a Python package or module, hence my question above. -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Wed Sep 12 09:41:05 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 03:41:05 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: > Where have you forgotten to mention Ubuntu? "I'm sure...", the OP has specifically said "in Python", which implies to me using a Python package or module, hence my question above. > Well, I was assuming he would write a command line app like so: Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system("speaker-test" + " --frequency 2000" + " --period 5000" + " --test sine") This would work in linux/ubuntu, but if they're using windows or don't have this particular linux distribution/speaker-test installed, it might need to be a different command line call, such as : >>> import os >>> os.system("your_sound_app_here" + " --frequency 2000" + " --period 5000" + " --test sine") -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Wed Sep 12 09:47:48 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 03:47:48 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: So the following would be the script, except the ability to change specific values such as frequency with a scroll widget. import os #Variables for system call command_line_app_for sound = "speaker-test" frequency = " --frequency 2000" length_of_sound_ms = " --period 5000" test_type = " --test sine" #System call with variables placed in os.system( command_line_app_for sound + frequency + length_of_sound_ms + test_type) -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Wed Sep 12 09:54:06 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Sep 2012 08:54:06 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/2012 08:41, Dwight Hutto wrote: >> Where have you forgotten to mention Ubuntu? "I'm sure...", the OP has specifically said "in Python", which implies to me using a Python package or module, hence my question above. >> > Well, I was assuming he would write a command line app like so: > > Python 2.7.3 (default, Aug 1 2012, 05:16:07) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> os.system("speaker-test" + " --frequency 2000" + " --period 5000" + " --test sine") > > > This would work in linux/ubuntu, but if they're using windows or don't > have this particular linux distribution/speaker-test installed, it > might need to be a different command line call, such as : > >>>> import os >>>> os.system("your_sound_app_here" + " --frequency 2000" + " --period 5000" + " --test sine") > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You can assume until the cows come home, but unless the OP states their requirement nobody will know for certain :) -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Wed Sep 12 10:04:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Sep 2012 09:04:15 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/2012 08:47, Dwight Hutto wrote: > So the following would be the script, except the ability to change > specific values such as frequency with a scroll widget. > > import os > > #Variables for system call > > command_line_app_for sound = "speaker-test" > frequency = " --frequency 2000" > length_of_sound_ms = " --period 5000" > test_type = " --test sine" > > #System call with variables placed in > > os.system( command_line_app_for sound + frequency + length_of_sound_ms > + test_type) > Extremely useful if and only if this is what the OP wants. I prefer working to facts and not assumptions, plus the full context of previous messages. -- Cheers. Mark Lawrence. From eryksun at gmail.com Wed Sep 12 10:18:10 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 12 Sep 2012 04:18:10 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 1:17 AM, D.V.N.Sarma ??.??.???.???? wrote: > How to produce a musical note of given frequency,volume and duration in > Python. Do you just want a sinusoidal, pure tone, or do you need a more complex waveform? For a pure tone you can use math.sin(2 * math.pi * f * dt * n). The sin is a function of radians. 2*math.pi is the constant number of radians/cycle, f is the frequency in cycles/second (Hz), dt is your sampling step size in seconds/sample, and n is the index in samples. Multiply all those units together and you get an argument in radians. The sin function just samples the y value of the (x,y) coordinate as you step around a unit circle in the given radians/step. You can scale the amplitude and iterate for however many steps you want. The discrete frequency is f*dt in cycles/sample, and the discrete period is 1/(f*dt) in samples/cycle. You need this to be at least 2 samples/cycle to uniquely define a sinusoid. In other words, 1/dt >= 2*f. The term 1/dt is the sampling rate fs. Two times the highest frequency of interest (2*f) is called the Nyquist rate. Sampling a a sinusoid at a sub-Nyquist rate will alias to a different frequency (the spectrum of a sampled signal goes from 0 to fs/2; higher frequencies fold back around). Search the web for animations that show aliasing (typically with clock hands, fan blades, etc). If your sample rate is 48000 Hz, you can create tones up to 24000 Hz, which is beyond the spectrum of human hearing (20Hz - 20kHz). The example below creates a generator for 1 cycle of a tone at a sample rate of 48 ksps. Next it packs the floating point values as bytes using struct.pack(). The resulting byte string is written to a PyAudio stream. PyAudio is a C extension wrapper around the cross-platform PortAudio library: http://people.csail.mit.edu/hubert/pyaudio import math import struct import pyaudio def play_tone(frequency, amplitude, duration, fs, stream): N = int(fs / frequency) T = int(frequency * duration) # repeat for T cycles dt = 1.0 / fs # 1 cycle tone = (amplitude * math.sin(2 * math.pi * frequency * n * dt) for n in xrange(N)) # todo: get the format from the stream; this assumes Float32 data = ''.join(struct.pack('f', samp) for samp in tone) for n in xrange(T): stream.write(data) fs = 48000 p = pyaudio.PyAudio() stream = p.open( format=pyaudio.paFloat32, channels=1, rate=fs, output=True) # play the C major scale scale = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6] for tone in scale: play_tone(tone, 0.5, 0.75, fs, stream) # up an octave for tone in scale[1:]: play_tone(2*tone, 0.5, 0.75, fs, stream) stream.close() p.terminate() From dwightdhutto at gmail.com Wed Sep 12 10:30:36 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 04:30:36 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 4:04 AM, Mark Lawrence wrote: > On 12/09/2012 08:47, Dwight Hutto wrote: >> >> So the following would be the script, except the ability to change >> specific values such as frequency with a scroll widget. >> >> import os >> >> #Variables for system call >> >> command_line_app_for sound = "speaker-test" >> frequency = " --frequency 2000" >> length_of_sound_ms = " --period 5000" >> test_type = " --test sine" >> >> #System call with variables placed in >> >> os.system( command_line_app_for sound + frequency + length_of_sound_ms >> + test_type) >> > > Extremely useful if and only if this is what the OP wants. I prefer working > to facts and not assumptions, plus the full context of previous messages. > The facts are, he's either going to call from a python module with parameters, or use a command line call(whether it's windows, or linux), or maybe he can type in 'python docs sound' into google, or go through a ctypes(which I can reference, and find an example of. Those are the facts. The assumption is that they're going to use oneof the usual methods, and I'm giving a VARIETY of factual options available. What are you doing other than pointing out my comments are out of context, when they clearly are in context. All you can do is point out some it's out of context, when it's all in context, and that is a fact. Want to help them with how to ask a question...Quit saying give us an OS, and some short blurb about how I'm answering out of context, and point them to this link: http://catb.org/esr/faqs/smart-questions.html -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From joel.goldstick at gmail.com Wed Sep 12 11:28:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Sep 2012 05:28:44 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 2:47 AM, Mark Lawrence wrote: > On 12/09/2012 06:17, D.V.N.Sarma ??.??.???.???? wrote: >> >> How to produce a musical note of given frequency,volume and duration in >> Python. I've not tried it, but I have seen several references to a game making framework called pygame. It has modules to play files and also produce tones. http://www.pygame.org/project-pitch+perfect-1689-2941.html >> >> -- Joel Goldstick From chrisbva81 at gmail.com Wed Sep 12 11:32:38 2012 From: chrisbva81 at gmail.com (chrisbva81 at gmail.com) Date: Wed, 12 Sep 2012 09:32:38 +0000 Subject: [Tutor] How to print a variable from an if/else statement Message-ID: <2057338575-1347442886-cardhu_decombobulator_blackberry.rim.net-2019341514-@b3.c12.bise6.blackberry> Hello, I'm very new thanks in advance for your help. My If statement is: If age < (40): Print("you are young.") Else: Print("You look great.") Basically what I want to do is have a sentence using print that includes the results of the If or Else which is based on the users input of age. I don't know if I'm doing something wrong by doing it this way. I can't figure it out. Thankyou! Chris Sent via BlackBerry by AT&T From joel.goldstick at gmail.com Wed Sep 12 12:05:38 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Sep 2012 06:05:38 -0400 Subject: [Tutor] How to print a variable from an if/else statement In-Reply-To: <2057338575-1347442886-cardhu_decombobulator_blackberry.rim.net-2019341514-@b3.c12.bise6.blackberry> References: <2057338575-1347442886-cardhu_decombobulator_blackberry.rim.net-2019341514-@b3.c12.bise6.blackberry> Message-ID: On Wed, Sep 12, 2012 at 5:32 AM, wrote: > Hello, > > I'm very new thanks in advance for your help. > > My If statement is: > > If age < (40): this will work, but python doesn't need the parentheses around the second argument. You can use it to make the logic more clear, but for a single term it doesn't > Print("you are young.") > Else: in python else is lower case > Print("You look great.") > > Basically what I want to do is have a sentence using print that includes the results of the If or Else which is based on the users input of age. > > I don't know if I'm doing something wrong by doing it this way. I can't figure it out. > so try this: if age < 40: print ("you are young") else: print ("you look great!") -- Joel Goldstick From jsantos.lazer at gmail.com Wed Sep 12 12:39:23 2012 From: jsantos.lazer at gmail.com (Joaquim Santos) Date: Wed, 12 Sep 2012 11:39:23 +0100 Subject: [Tutor] How to print a variable from an if/else statement Message-ID: > > > > Message: 3 > Date: Wed, 12 Sep 2012 09:32:38 +0000 > From: chrisbva81 at gmail.com > To: tutor at python.org > Subject: [Tutor] How to print a variable from an if/else statement > Message-ID: > <2057338575-1347442886-cardhu_decombobulator_blackberry.rim.net- > 2019341514- at b3.c12.bise6.blackberry> > > Content-Type: text/plain > > Hello, > > I'm very new thanks in advance for your help. > > My If statement is: > > If age < (40): > Print("you are young.") > Else: > Print("You look great.") > > Basically what I want to do is have a sentence using print that includes > the results of the If or Else which is based on the users input of age. > > I don't know if I'm doing something wrong by doing it this way. I can't > figure it out. > > Thankyou! > > Chris > Sent via BlackBerry by AT&T > > > My first time answering the list!!! (sorry for this outburst!) >From my limited knowledge your if/else statement is correct BUT your print should start with lower caps, that's why it's not working. You can see here a bunch of examples on how to use it properly -> http://docs.python.org/release/3.0.1/library/functions.html?highlight=print#print Hope this helps! Cheers! Joaquim Santos -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Sep 12 12:45:00 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Sep 2012 06:45:00 -0400 Subject: [Tutor] How to print a variable from an if/else statement In-Reply-To: References: Message-ID: Following up on my earlier reply, ( I let the 'If' slip). Python statements are ALL lowercase. Case matters in python, so If is not if, Print is not print, Else is not else. -- Joel Goldstick From eryksun at gmail.com Wed Sep 12 12:47:29 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 12 Sep 2012 06:47:29 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 4:49 AM, Dwight Hutto wrote: > > pyaudio is compatible with python 3.0(just in case the OP has that > version, and it doesn't look like on the main site it has it listed, > nor if it's 64 bit, etc. I'm surprised they don't have an official Python 3 port yet. I see now the git repo hasn't seen a commit in 2 years. About a year ago I ported PyAudio to Python 3 for my own use, based on the guide for porting C extensions I found here: http://python3porting.com/cextensions.html But it was only a quick update (actually kind of tedious) of _portaudiomodule.c. Christoph Gholke has a port online that modifies setup.py as well. I prefer his version over my own (more eyes, fewer bugs). It just needs a small modification for Linux (see below). PyAudio for Windows Python 2.5 to 3.2 (32-bit and 64-bit): http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio Pre-release pygame for Python 3, in case you want to use SDL as a tone generator: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame Debian Build I downloaded Christoph's port of PyAudio from the site above and built it on my Debian Linux box. I needed to install portaudio19-dev. You'll also need python3-all-dev if it's not already installed. I had to comment out line 138 of setup.py (data_files=data_files). Christoph added it for the Windows build, but it's not required for Linux. I only got a few compiler warnings running "sudo python3 setup.py install". YMMV. The tone-playing script works fine, after making a few modifications to use range instead of xrange and b''.join instead of ''.join. From aaronpil at gmail.com Wed Sep 12 13:20:58 2012 From: aaronpil at gmail.com (Aaron Pilgrim) Date: Wed, 12 Sep 2012 04:20:58 -0700 Subject: [Tutor] convert ascii to binary Message-ID: Hello, I am trying to write a small program that converts ascii to binary. I tried using the python reference library section 18.8 but had trouble understanding how to make it work. Here is the code I am currently trying to use: def main(): import binascii myWord = input("Enter the word to convert..") #convert text to ascii for ch in myWord: print(ord(ch)) #convert ascii to binary binascii.a2b_uu(ord(ch)) main() Thank you for any help you can provide From joel.goldstick at gmail.com Wed Sep 12 13:54:05 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Sep 2012 07:54:05 -0400 Subject: [Tutor] convert ascii to binary In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 7:20 AM, Aaron Pilgrim wrote: > Hello, > I am trying to write a small program that converts ascii to binary. > > I tried using the python reference library section 18.8 but had > trouble understanding how to make it work. > > Here is the code I am currently trying to use: > > def main(): > import binascii > myWord = input("Enter the word to convert..") > #convert text to ascii > for ch in myWord: > print(ord(ch)) > #convert ascii to binary > binascii.a2b_uu(ord(ch)) > > main() > A couple of thoughts. The section you reference suggests using higher level modules such as uu. uu seems to want to read an ascii file and write a uu encoded file. I just read the wikipedia article on uuencoding, since I have heard of it, but never needed to know about it. It is apparently a pretty old method of transforming 3 consecutive 8 bit ascii characters into 4 6 bit uuencoded characters so that they can be sent between (unix) computers. What are you really trying to do? Is this for experimenting with python? or are you trying to solve some larger problem? -- Joel Goldstick From d at davea.name Wed Sep 12 14:14:00 2012 From: d at davea.name (Dave Angel) Date: Wed, 12 Sep 2012 08:14:00 -0400 Subject: [Tutor] convert ascii to binary In-Reply-To: References: Message-ID: <50507C88.8030009@davea.name> On 09/12/2012 07:54 AM, Joel Goldstick wrote: > > A couple of thoughts. The section you reference suggests using higher > level modules such as uu. > uu seems to want to read an ascii file and write a uu encoded file. > > I just read the wikipedia article on uuencoding, since I have heard of > it, but never needed to know about it. It is apparently a pretty old > method of transforming 3 consecutive 8 bit ascii characters into 4 6 > bit uuencoded characters so that they can be sent between (unix) > computers. It's old in the sense that it was defined a long time ago. But it's current, and variations of it are used regularly in email, as one way to send binary attachments. Look at the mime type called base64. It converts 3 consecutive 8-bit NON-ASCII bytes into 4 consecutive 7-bit ASCII characters. I'm not sure what that has to do with the OP question. > What are you really trying to do? Is this for experimenting with > python? or are you trying to solve some larger problem? > > -- DaveA From d at davea.name Wed Sep 12 14:31:12 2012 From: d at davea.name (Dave Angel) Date: Wed, 12 Sep 2012 08:31:12 -0400 Subject: [Tutor] convert ascii to binary In-Reply-To: References: Message-ID: <50508090.9000303@davea.name> On 09/12/2012 07:20 AM, Aaron Pilgrim wrote: > Hello, > I am trying to write a small program that converts ascii to binary. > > I tried using the python reference library section 18.8 but had > trouble understanding how to make it work. If you supplied a link, we might be able to figure out what section 10.8 is. It'll vary between versions of Python. And in version 2.7, there doesn't seem to be a section 10.8 http://docs.python.org/reference/index.html#reference-index It would also be useful to specify the version of Python that this is for. But on the assumption that it's either 2.6 or 2.7, try the following link: http://docs.python.org/library/functions.html#bin if that's not what you want, then you'd better give us some sample input and output, or give the usage context or quote the assigmment. > Here is the code I am currently trying to use: > > def main(): > import binascii > myWord = input("Enter the word to convert..") > #convert text to ascii > for ch in myWord: > print(ord(ch)) > #convert ascii to binary > binascii.a2b_uu(ord(ch)) That function converts a line of uuencoded data to the binary data that generated it. Your ch isn't a line of uuencoded data, and you don't do anything with the return value. Besides, your subject line implies you want the reverse order. > main() > > -- DaveA From eryksun at gmail.com Wed Sep 12 14:36:01 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 12 Sep 2012 08:36:01 -0400 Subject: [Tutor] convert ascii to binary In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 7:20 AM, Aaron Pilgrim wrote: > Hello, > I am trying to write a small program that converts ascii to binary. > > I tried using the python reference library section 18.8 but had > trouble understanding how to make it work. > > Here is the code I am currently trying to use: > > def main(): > import binascii > myWord = input("Enter the word to convert..") > #convert text to ascii > for ch in myWord: > print(ord(ch)) > #convert ascii to binary > binascii.a2b_uu(ord(ch)) I'm not sure what you want, based on the code above. uuencoding is meant for sending data through 7-bit channels like email and newsgroups. For example: >>> binascii.b2a_uu('\x81\x82') # 8-bit binary to 7-bit ascii '"@8( \n' >>> binascii.a2b_uu('"@8( \n') # 7-bit ascii back to 8-bit '\x81\x82' http://docs.python.org/py3k/library/binascii.html#binascii.a2b_uu Do you instead want an ASCII bitstring (i.e. 1s and 0s)? These will raise a UnicodeError if the string isn't ASCII. # Python 3 def iter_bin(s): sb = s.encode('ascii') return (format(b, '07b') for b in sb) # Python 2 def iter_bin(s): sb = s.encode('ascii') return (format(ord(b), '07b') for b in sb) For example: >>> for s in iter_bin("Spam"): ... print(s) ... 1010011 1110000 1100001 1101101 >>> print(*iter_bin("Spam"), sep='') # Python 3 1010011111000011000011101101 >>> print ''.join(s for s in iter_bin("Spam")) # Python 2 1010011111000011000011101101 From dwightdhutto at gmail.com Wed Sep 12 14:38:32 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 08:38:32 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: Please hit reply to all when responding. You should be able to type in 'sudo apt-get install speaker-test' or 'yum speaker-test' wrote: > This is what I got > >>>> import os >>>> os.system("speaker-test"+"--frequency 2000"+"--period 5000"+"--test >>>> sine") It should look like this: import os os.system("speaker-test"+" --frequency 2000"+" --period 5000"+ "--test sine") You can copy and paste it to see. This assumed you had speaker-test, you might have another command line app that does the same thing. So if the instructions to download above don't work. Let me know. Note that there is a space before everything in the string, except the first, speaker-test, other wise it looks like this to the command line: speaker-test--frequency2000--period5000--test sine The space before the " --frequency 2000", and the rest makes it look like: speaker-test --frequency 2000 --period 5000 --test sine so put a space at the beginning of every string except speaker-test If you have Windows, then you should be on the pywin32 list, I usually assume linux on this list, but both get answered. Remember to read this: http://catb.org/esr/faqs/smart-questions.html Mark is right, besides the little back and forth, that in fact you need to describe, otherwise I have a tendency to speculate;) Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From steve at pearwood.info Wed Sep 12 14:38:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 12 Sep 2012 22:38:50 +1000 Subject: [Tutor] convert ascii to binary In-Reply-To: References: Message-ID: <5050825A.2010705@pearwood.info> On 12/09/12 21:20, Aaron Pilgrim wrote: > Hello, > I am trying to write a small program that converts ascii to binary. Can you explain what you mean by "ascii to binary"? Any of these could be described that way: 'hello world' => '68656c6c6f20776f726c64' => 'begin 666 \n+:&5L;&\\@=V]R;&0 \n \nend\n' => 'aGVsbG8gd29ybGQ=\n' => 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' or many others. For the record, those are: * raw hex string * uuencode * base64 * zip compressed[1] Reading ahead, I think you want the raw hex string, correct? > I tried using the python reference library section 18.8 but had > trouble understanding how to make it work. > > Here is the code I am currently trying to use: > > def main(): > import binascii As a general rule, imports should go in the top-level of the module, not inside the body of a function. There are exceptions to that rule, but in this case there is no reason not to follow it. So: import binascii def main(): # body of main without the import > myWord = input("Enter the word to convert..") > #convert text to ascii > for ch in myWord: > print(ord(ch)) > #convert ascii to binary > binascii.a2b_uu(ord(ch)) There is no need to process the string one character at a time. Try this instead: import binascii def main(): line = input("Enter a line of text to convert: ") print(binascii.hexlify(line)) If you want to do it one character at a time, there's no need for binhex: def main(): line = input("Enter a line of text to convert: ") for c in line: print("Char: '%c' Ord: %3d (decimal) %x (hex)" % (c, ord(c), ord(c))) [1] It is ironic that zip compression on a short string leads to a *longer* string -- Steven From dwightdhutto at gmail.com Wed Sep 12 14:43:38 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 08:43:38 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: Also, you try eryksun's solution/example, pyaudio, as well, since it's a mpdule, using different forms for cross compatibility. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Wed Sep 12 15:17:24 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Sep 2012 14:17:24 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/2012 13:43, Dwight Hutto wrote: > Also, you try eryksun's solution/example, pyaudio, as well, since it's > a mpdule, using different forms for cross compatibility. > You have again snipped the entire context so nobody has a clue what you're replying to. -- Cheers. Mark Lawrence. From dvnsarma at gmail.com Wed Sep 12 15:53:57 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 12 Sep 2012 19:23:57 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: My OS is Windows XP. I have Python 2.7.3(32 bit). My question is are there any commands in Python which directly allow me to produce a pure note of a given frequency, given volume and given duration. Further can we access the different sound channels(sound card) available through Python. -- regards, Sarma. On Wed, Sep 12, 2012 at 6:47 PM, Mark Lawrence wrote: > On 12/09/2012 13:43, Dwight Hutto wrote: > >> Also, you try eryksun's solution/example, pyaudio, as well, since it's >> a mpdule, using different forms for cross compatibility. >> >> > You have again snipped the entire context so nobody has a clue what you're > replying to. > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From afowler2 at broncos.uncfsu.edu Wed Sep 12 17:36:23 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 12 Sep 2012 15:36:23 +0000 Subject: [Tutor] Print List Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> I am trying to complete the following below: You also need to write a function "printList" of one parameter that takes a list as its input and neatly prints the entire contents of the list in a column. Each student in the list should be printed using __str__. So far i have: def printList(lists): print("First Name\tLast Name\tCredits\tGPA") for i in lists: print (i) Any Suggestions or Corrections? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 12 18:01:17 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 12 Sep 2012 12:01:17 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: > You have again snipped the entire context so nobody has a clue what you're > replying to. > > Cheers. > > Mark Lawrence. My last post refers to a previous post by eryksun. If you can't look up and read it, that's cool, because you're the only one complaining. And to put it into context that you're a complete jackass, look at the context in this post, which is two above your last post(especially the end part): Please hit reply to all when responding. You should be able to type in 'sudo apt-get install speaker-test' or 'yum speaker-test' wrote: > This is what I got > >>>> import os >>>> os.system("speaker-test"+"--frequency 2000"+"--period 5000"+"--test >>>> sine") It should look like this: import os os.system("speaker-test"+" --frequency 2000"+" --period 5000"+ "--test sine") You can copy and paste it to see. This assumed you had speaker-test, you might have another command line app that does the same thing. So if the instructions to download above don't work. Let me know. Note that there is a space before everything in the string, except the first, speaker-test, other wise it looks like this to the command line: speaker-test--frequency2000--period5000--test sine The space before the " --frequency 2000", and the rest makes it look like: speaker-test --frequency 2000 --period 5000 --test sine so put a space at the beginning of every string except speaker-test If you have Windows, then you should be on the pywin32 list, I usually assume linux on this list, but both get answered. Remember to read this: http://catb.org/esr/faqs/smart-questions.html Mark is right, besides the little back and forth, that in fact you need to describe, otherwise I have a tendency to speculate;) -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From oscar.j.benjamin at gmail.com Wed Sep 12 18:10:54 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 12 Sep 2012 17:10:54 +0100 Subject: [Tutor] Print List In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Sep 12, 2012 4:53 PM, "Ashley Fowler" wrote: > > I am trying to complete the following below: > > > You also need to write a function "printList" of one parameter that > takes a list as its input and neatly prints the entire contents of the > list in a column. Each student in the list should be printed using __str__. > > > So far i have: > > > def printList(lists): > print("First Name\tLast Name\tCredits\tGPA") > for i in lists: > print (i) > > > Any Suggestions or Corrections? Looks good to me. My only suggestion is to use more descriptive names. I would have called it 'students' instead of 'lists' and 'student' instead of 'i'. I don't really like 'printList' either but I guess your stuck with that. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Sep 12 18:38:31 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 12 Sep 2012 12:38:31 -0400 Subject: [Tutor] How to print a variable from an if/else statement In-Reply-To: References: Message-ID: <5050BA87.9040209@gmail.com> Precision in terminology is good. Python has /keywords./ /if, //and, //else /are /keywords. /All keywords are all lower case. Keywords cannot be overridden by assignment. /Python has statements/./ /if // is a ///statement./////////So is /def.//// ///Some keywords are part of the structure of statements, e.g. if...else, for..in. Someof these may also be used in expressions, e.g. 3 if a == 1 else 2. /// ///In Python 3 /print/ is a /function./ Python has a few /built-in constants, /including /None, True, False. /These names are Title case, and can be overridden by assignment. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed Sep 12 18:47:01 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 12 Sep 2012 12:47:01 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 8:38 AM, Dwight Hutto wrote: > If you have Windows, then you should be on the pywin32 list, I usually > assume linux on this list, but both get answered. If you're having a problem with either the specific pywin32 module[1], or have questions about accessing the deep dark internals of windows or com objects, then I would highly recommend the pywin32 list -- there are some great people there who I've seen field all kinds of difficult problems. That said, general python on windows questions are perfectly on topic both here on the tutor list, and on the main python list. It does help to let us know right off what operating system you're using -- there are some programming problems where it doesn't make any difference at all, and for others it makes all the difference in the world. In this case, you're working on accessing hardware that doesn't have a specific built in python module that takes care of the platform specific difference, so your solution is very likely to be different depending on where you're planning on running your code. 1: http://starship.python.net/crew/mhammond/win32/Downloads.html and/or http://sourceforge.net/projects/pywin32/ -- Jerry From terrence.brannon at bankofamerica.com Wed Sep 12 19:01:42 2012 From: terrence.brannon at bankofamerica.com (Brannon, Terrence) Date: Wed, 12 Sep 2012 13:01:42 -0400 Subject: [Tutor] Print List In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <7F78496735D9004BA98D1FDC256C9C71B15C45@smtp_mail.bankofamerica.com> From: Tutor [mailto:tutor-bounces+terrence.brannon=bankofamerica.com at python.org] On Behalf Of Ashley Fowler Sent: Wednesday, September 12, 2012 11:36 AM To: tutor at python.org Subject: [Tutor] Print List I am trying to complete the following below: You also need to write a function "printList" of one parameter that takes a list as its input [Terrence Brannon] since it is taking a list as its input, why not call it students or simply list? Calling it "lists" implies that it is a list that contains other lists and neatly prints the entire contents of the list in a column. Each student in the list should be printed using __str__. So far i have: def printList(lists): print("First Name\tLast Name\tCredits\tGPA") for i in lists: print (i) Any Suggestions or Corrections? [Terrence Brannon] def print_list(students): for student in students: print("{0}\t{1}\t{2}\t{3}".format(student.first_name, student.last_name, student.credits, student.gpa)) OHHH.... Wait a minute... that means you need to redefine the __str__() method of your Student class: class Student(object): .... def __str__(self): return "{0}\t{1}\t{2}\t{3}".format(student.first_name, student.last_name, student.credits, student.gpa) And then print_list is simply: def print_list(students): for student in students: print student ---------------------------------------------------------------------- This message w/attachments (message) is intended solely for the use of the intended recipient(s) and may contain information that is privileged, confidential or proprietary. If you are not an intended recipient, please notify the sender, and then please delete and destroy all copies and attachments, and be advised that any review or dissemination of, or the taking of any action in reliance on, the information contained in or attached to this message is prohibited. Unless specifically indicated, this message is not an offer to sell or a solicitation of any investment products or other financial product or service, an official confirmation of any transaction, or an official statement of Sender. Subject to applicable law, Sender may intercept, monitor, review and retain e-communications (EC) traveling through its networks/systems and may produce any such EC to regulators, law enforcement, in litigation and as required by law. The laws of the country of each sender/recipient may impact the handling of EC, and EC may be archived, supervised and produced in countries other than the country in which you are located. This message cannot be guaranteed to be secure or free of errors or viruses. References to "Sender" are references to any subsidiary of Bank of America Corporation. Securities and Insurance Products: * Are Not FDIC Insured * Are Not Bank Guaranteed * May Lose Value * Are Not a Bank Deposit * Are Not a Condition to Any Banking Service or Activity * Are Not Insured by Any Federal Government Agency. Attachments that are part of this EC may have additional important disclosures and disclaimers, which you should read. This message is subject to terms available at the following link: http://www.bankofamerica.com/emaildisclaimer. By messaging with Sender you consent to the foregoing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Wed Sep 12 19:56:51 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Wed, 12 Sep 2012 18:56:51 +0100 Subject: [Tutor] setting a timer Message-ID: i have a way to set a timer for creating new objects copied from a book but as i have started my next exercise in a very different way, i want to avoid that math method/formula as it will cause me to rearrange some classes totally... i tried a simple method but its not working. any ideas? heres my code, ill leave out the irrelevant code. class Game(object): interval = 0 def play(self): Game.interval = 40 while Game.interval > 0: self.count_down() def count_down(self): Game.interval -= 1 so the play() method gives interval a value of 40. the while loop should reduce interval by 1 everytime it calls the count_down() method. The problem is this is happening instantly. i've even put the Game.interval value as high as 50000 and it reaches 0 instantly. From joel.goldstick at gmail.com Wed Sep 12 20:10:25 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Sep 2012 14:10:25 -0400 Subject: [Tutor] How to print a variable from an if/else statement In-Reply-To: <5050BA87.9040209@gmail.com> References: <5050BA87.9040209@gmail.com> Message-ID: On Wed, Sep 12, 2012 at 12:38 PM, bob gailer wrote: > Precision in terminology is good. > > Python has keywords. if, and, else are keywords. All keywords are all lower > case. > > Keywords cannot be overridden by assignment. > > Python has statements. if is a statement. So is def. > > Some keywords are part of the structure of statements, e.g. if...else, > for..in. > > Someof these may also be used in expressions, e.g. 3 if a == 1 else 2. > > In Python 3 print is a function. > > Python has a few built-in constants, including None, True, False. These > names are Title case, and can be overridden by assignment. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > thanks for clarifying. -- Joel Goldstick From steve at pearwood.info Wed Sep 12 20:24:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Sep 2012 04:24:07 +1000 Subject: [Tutor] setting a timer In-Reply-To: References: Message-ID: <5050D347.4060205@pearwood.info> On 13/09/12 03:56, Matthew Ngaha wrote: > class Game(object): > interval = 0 > > def play(self): > Game.interval = 40 > while Game.interval> 0: > self.count_down() > > def count_down(self): > Game.interval -= 1 > > so the play() method gives interval a value of 40. the while loop > should reduce interval by 1 everytime it calls the count_down() > method. The problem is this is happening instantly. i've even put the > Game.interval value as high as 50000 and it reaches 0 instantly. Get a slower computer. I expect that if you find an old Commodore 64 from 1982, or perhaps an 1984 Apple Macintosh, it might be slow enough for your count down idea to work. But with modern computers, counting up to, or down from, 50000 is more or less instantaneous in human terms. A better way to pause for a moment is this: import time time.sleep(0.1) # pause for 0.1 second time.sleep(60) # pause for 1 minutes -- Steven From chigga101 at gmail.com Wed Sep 12 21:10:27 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Wed, 12 Sep 2012 20:10:27 +0100 Subject: [Tutor] setting a timer In-Reply-To: <5050D347.4060205@pearwood.info> References: <5050D347.4060205@pearwood.info> Message-ID: > Get a slower computer. > > I expect that if you find an old Commodore 64 from 1982, or perhaps > an 1984 Apple Macintosh, it might be slow enough for your count down > idea to work. But with modern computers, counting up to, or down from, > 50000 is more or less instantaneous in human terms. > > A better way to pause for a moment is this: > > import time > time.sleep(0.1) # pause for 0.1 second > time.sleep(60) # pause for 1 minutes hah do u think i could find one of those on ebay??? i wasnt aware of the time module! thanks a lot for your help:) From eryksun at gmail.com Wed Sep 12 21:10:57 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 12 Sep 2012 15:10:57 -0400 Subject: [Tutor] setting a timer In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 1:56 PM, Matthew Ngaha wrote: > i have a way to set a timer for creating new objects copied from a > book but as i have started my next exercise in a very different way, i > want to avoid that math method/formula as it will cause me to > rearrange some classes totally... > > i tried a simple method but its not working. any ideas? threading has a Timer: http://docs.python.org/library/threading#timer-objects >>> def print_msg(msg): ... print msg >>> t = threading.Timer(1, print_msg, ('Spam',)) >>> t.start() >>> Spam >>> t = threading.Timer(3, print_msg, ('Spam',)) >>> t.start(); t.join() # waiting... Spam There's also the sched module, but only if you're not using threads: http://docs.python.org/library/sched >>> s = sched.scheduler(time.time, time.sleep) >>> e = s.enter(3, 1, print_msg, ('Spam',)) >>> s.run() Spam >>> e = s.enterabs(time.time() + 5, 1, print_msg, ('Spam',)) >>> s.run() Spam From alan.gauld at btinternet.com Thu Sep 13 01:15:42 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 00:15:42 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/12 14:53, D.V.N.Sarma ??.??.???.???? wrote: > My OS is Windows XP. I have Python 2.7.3(32 bit). My question is > are there any commands in Python which directly allow me to produce a > pure note Have a look at the audioop, wave and winsound modules. Also PyGame has some tools that try to do platform independent audio... Access to the sound card is another matter since that is non standard and determined by the sound drivers exposed by the manufacturer. The drivers may well vary in capability depending ion the OS in use etc. You can also use ctypes for direct access to the Windows audio libraries but that's a whole lot more complicated! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 13 01:20:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 00:20:01 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 12/09/12 17:01, Dwight Hutto wrote: > > If you have Windows, then you should be on the pywin32 list, I usually > assume linux on this list, but both get answered. Just to be clear the tutor list is not OS biased. Windows, MacOS or Linux are all equally welcome (and indeed MVS or OpenVMS if necessary!) If somebody asks an OS specific question we will often direct to a more focused forum but the tutor list does not favour any OS over another. -- Alan G Wearing my Moderator hat... From alan.gauld at btinternet.com Thu Sep 13 01:31:03 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 00:31:03 +0100 Subject: [Tutor] Print List In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 12/09/12 16:36, Ashley Fowler wrote: > def printList(lists): > print("First Name\tLast Name\tCredits\tGPA") > for i in lists: > print (i) > > > Any Suggestions or Corrections? The input parameter is called 'lists' which implies that the input is more than one list. Try to make your input parameter names as accurate as possible. In this case you might think 'list' would be good, but its no, because list is a Python builtin word. So we would be better to choose something like aList or theList. Your function could have been generic in that it printed any kind of list but by printing a header line you have made it specific to a list of students. So you could call the input studentList. In general, in Python, generic functions are favoured. One way to have a header and be generic would be to pass the header in as a parameter too: def printList(theList, theHeader=""): print(theHeader) for item in theList: print item And then you would call it with: printList(myStudentList, "First Name\tLast Name\tCredits\tGPA") Or printList(myPetList, "Name, Breed, Age") Or printList(myBlankList) # uses the default empty header or whatever... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Sep 13 01:35:00 2012 From: d at davea.name (Dave Angel) Date: Wed, 12 Sep 2012 19:35:00 -0400 Subject: [Tutor] How to print a variable from an if/else statement In-Reply-To: <5050BA87.9040209@gmail.com> References: <5050BA87.9040209@gmail.com> Message-ID: <50511C24.3010101@davea.name> On 09/12/2012 12:38 PM, bob gailer wrote: > > > /Python has statements/./ /if // is a ///statement./////////So is > /def.//// > > What's with the attempted italics? This is a text mailing list, and the text version of your html message was thoroughly mangled. It'd be much better to just send the messages in text form, as numerous manglings occur, depending on the combination of sender and reader. -- DaveA From akleider at sonic.net Thu Sep 13 01:36:57 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Wed, 12 Sep 2012 16:36:57 -0700 Subject: [Tutor] Print List In-Reply-To: References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <8c4c378fee72d4a28514d59390a652c7.squirrel@webmail.sonic.net> > On 12/09/12 16:36, Ashley Fowler wrote: > >> def printList(lists): >> print("First Name\tLast Name\tCredits\tGPA") >> for i in lists: >> print (i) >> >> >> Any Suggestions or Corrections? > > The input parameter is called 'lists' which implies that the input is > more than one list. Try to make your input parameter names as accurate > as possible. In this case you might think 'list' would be good, but its > no, because list is a Python builtin word. So we would be better to > choose something like aList or theList. > > Your function could have been generic in that it printed any kind of > list but by printing a header line you have made it specific to a list > of students. So you could call the input studentList. > > In general, in Python, generic functions are favoured. One way to have a > header and be generic would be to pass the header in as a parameter too: > > def printList(theList, theHeader=""): > print(theHeader) > for item in theList: > print item > > > And then you would call it with: > > printList(myStudentList, "First Name\tLast Name\tCredits\tGPA") > > Or > > printList(myPetList, "Name, Breed, Age") > > Or > > printList(myBlankList) # uses the default empty header > > or whatever... > > -- > Alan G To make it even more generic I would suggest replacing """ print(theHeader) """ with """ if theHeader: print(theHeader) """ to avoid a blank line if you don't need/want a header line. ak > def printList(theList, theHeader=""): > print(theHeader) > for item in theList: > print item > From dvnsarma at gmail.com Thu Sep 13 01:57:53 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Sep 2012 05:27:53 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: The Beep attribute of winsound module is useful. But the volume is feeble. Is there anyway to control the loudness. -- regards, Sarma. On Thu, Sep 13, 2012 at 4:45 AM, Alan Gauld wrote: > On 12/09/12 14:53, D.V.N.Sarma ??.??.???.???? wrote: > >> My OS is Windows XP. I have Python 2.7.3(32 bit). My question is >> are there any commands in Python which directly allow me to produce a >> pure note >> > > Have a look at the audioop, wave and winsound modules. > > Also PyGame has some tools that try to do platform independent audio... > > Access to the sound card is another matter since that is non standard and > determined by the sound drivers exposed by the manufacturer. The drivers > may well vary in capability depending ion the OS in use etc. > > You can also use ctypes for direct access to the Windows audio libraries > but that's a whole lot more complicated! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvnsarma at gmail.com Thu Sep 13 02:09:47 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Sep 2012 05:39:47 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: One can ofcourse increase the volume by adjusting master volume. But one needs ability to program volume level in order to produce sounds of different volume levels in a piece of music. -- regards, Sarma. On Thu, Sep 13, 2012 at 5:27 AM, D.V.N.Sarma ??.??.???.???? < dvnsarma at gmail.com> wrote: > The Beep attribute of winsound module is useful. But the volume is feeble. > Is there anyway to control the loudness. > > -- > regards, > Sarma. > On Thu, Sep 13, 2012 at 4:45 AM, Alan Gauld wrote: > >> On 12/09/12 14:53, D.V.N.Sarma ??.??.???.???? wrote: >> >>> My OS is Windows XP. I have Python 2.7.3(32 bit). My question is >>> are there any commands in Python which directly allow me to produce a >>> pure note >>> >> >> Have a look at the audioop, wave and winsound modules. >> >> Also PyGame has some tools that try to do platform independent audio... >> >> Access to the sound card is another matter since that is non standard and >> determined by the sound drivers exposed by the manufacturer. The drivers >> may well vary in capability depending ion the OS in use etc. >> >> You can also use ctypes for direct access to the Windows audio libraries >> but that's a whole lot more complicated! >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu Sep 13 02:12:45 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Sep 2012 01:12:45 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 13/09/2012 00:57, D.V.N.Sarma ??.??.???.???? wrote: > The Beep attribute of winsound module is useful. But the volume is feeble. > Is there anyway to control the loudness. > Have you read http://docs.python.org/library/winsound.html ? -- Cheers. Mark Lawrence. From bgailer at gmail.com Thu Sep 13 02:57:37 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 12 Sep 2012 20:57:37 -0400 Subject: [Tutor] Print List In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <50512F81.4020700@gmail.com> On 9/12/2012 11:36 AM, Ashley Fowler wrote: > I am trying to complete the following below: > You also need to write a function "printList" of one parameter that > takes a list as its input and neatly prints the entire contents of the > list in a column. > Any Suggestions or Corrections? I would correct the use of "neatly" and "column"- these are ill-defined terms! Specifications should leave nothing to be guessed or assumed -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Sep 13 03:35:58 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Sep 2012 11:35:58 +1000 Subject: [Tutor] Print List In-Reply-To: <50512F81.4020700@gmail.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> <50512F81.4020700@gmail.com> Message-ID: <5051387E.6040000@pearwood.info> On 13/09/12 10:57, bob gailer wrote: > On 9/12/2012 11:36 AM, Ashley Fowler wrote: >> I am trying to complete the following below: >> You also need to write a function "printList" of one parameter that >> takes a list as its input and neatly prints the entire contents of the >> list in a column. >> Any Suggestions or Corrections? > > I would correct the use of "neatly" and "column"- these are ill-defined terms! > > Specifications should leave nothing to be guessed or assumed Bob, "neatly" and "column" are perfectly clear and simple English words that don't need additional definition. One might just as well say that your use of the words "correct", "terms", "leave", "nothing", "guessed" and "assumed" are ill-defined. -- Steven From mikeofmany at gmail.com Thu Sep 13 05:06:06 2012 From: mikeofmany at gmail.com (Mike S) Date: Wed, 12 Sep 2012 20:06:06 -0700 Subject: [Tutor] Sigh first real python task Message-ID: So, trying to modify a python script that when invoked copies a local file to a remote host. Previously this was done with only needing to pass a username. try: ret = subprocess.call("smbclient //metricsmachine/reports/; put %s\" -U metrics%%" % (fileName), shell=True) if ret < 0: print >>sys.stderr, "Child was terminated by signal", -ret else: os.unlink(path+fileName) except OSError, e: print >>sys.stderr, "Execution failed:", e Now, I'm having to change the remote host and pass both the username and pass but cannot get it to work. Changing it to try: ret = subprocess.call("smbclient //reportingmachine/Dashboard/; put %s\" -U Username%Password" % (fileName), shell=True) if ret < 0: print >>sys.stderr, "Child was terminated by signal", -ret else: os.unlink(path+fileName) except OSError, e: print >>sys.stderr, "Execution failed:", e Any help would be appreciated. -- Mike of Many Stories, Ideas, and Ramblings Game Chef 2009, 2010 NaNoWriMo 2008, 2009 http://mikeofmanystories.blogspot.com/ - writings http://mikeofmany.wordpress.com/ - personal bloggery -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Sep 13 05:14:48 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Sep 2012 13:14:48 +1000 Subject: [Tutor] Sigh first real python task In-Reply-To: References: Message-ID: <50514FA8.7010307@pearwood.info> On 13/09/12 13:06, Mike S wrote: > Now, I'm having to change the remote host and pass both the username and > pass but cannot get it to work. Since we don't have access to your machine to try it, would you care to tell us what happens when you try, or shall we just guess? -- Steven From mikeofmany at gmail.com Thu Sep 13 06:18:48 2012 From: mikeofmany at gmail.com (Mike S) Date: Wed, 12 Sep 2012 21:18:48 -0700 Subject: [Tutor] Sigh first real python task In-Reply-To: <50514FA8.7010307@pearwood.info> References: <50514FA8.7010307@pearwood.info> Message-ID: Sorry, hit send a bit too fast there: here is the output: session setup failed: NT_STATUS_LOGON_FAILURE /bin/sh: put: command not found On Wed, Sep 12, 2012 at 8:14 PM, Steven D'Aprano wrote: > On 13/09/12 13:06, Mike S wrote: > > Now, I'm having to change the remote host and pass both the username and >> pass but cannot get it to work. >> > > Since we don't have access to your machine to try it, would you care to > tell > us what happens when you try, or shall we just guess? > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Mike of Many Stories, Ideas, and Ramblings Game Chef 2009, 2010 NaNoWriMo 2008, 2009 http://mikeofmanystories.blogspot.com/ - writings http://mikeofmany.wordpress.com/ - personal bloggery -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvnsarma at gmail.com Thu Sep 13 07:16:06 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Sep 2012 10:46:06 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: Yes. As far as I can see it does not contain any thing which concerns the volume of sound. -- regards, Sarma. On Thu, Sep 13, 2012 at 5:42 AM, Mark Lawrence wrote: > On 13/09/2012 00:57, D.V.N.Sarma ??.??.???.???? wrote: > >> The Beep attribute of winsound module is useful. But the volume is feeble. >> Is there anyway to control the loudness. >> >> > Have you read http://docs.python.org/**library/winsound.html? > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 13 12:00:09 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 13 Sep 2012 06:00:09 -0400 Subject: [Tutor] Sigh first real python task In-Reply-To: References: Message-ID: On Wed, Sep 12, 2012 at 11:06 PM, Mike S wrote: > try: > ret = subprocess.call("smbclient //reportingmachine/Dashboard/; put > %s\" -U Username%Password" % (fileName), shell=True) > if ret < 0: > print >>sys.stderr, "Child was terminated by signal", -ret > else: > os.unlink(path+fileName) > except OSError, e: > print >>sys.stderr, "Execution failed:", e I don't see a need to run this through the shell. I'd just use a list of arguments. Do you only want to delete the file if smbclient is killed by a signal? What if it fails for some other reason with a return code of 1? In the example below I assume the file is removed only if the put command succeeds. >From what I gather using "man smbclient", the basic template here is the following: smbclient servicename password -U username -c "put filename" The code below uses subprocess.check_call, which raises a CalledProcessError if the return code is non-zero. The variables username, password, filename, and path are strings. import sys import os from subprocess import check_call, CalledProcessError servicename = "//reportingmachine/Dashboard/" try: check_call(["smbclient", servicename, password, "-U", username, "-c", "put %s" % filename]) os.unlink(os.path.join(path, filename)) except CalledProcessError as e: print >>sys.stderr, "call failed:", e except OSError as e: print >>sys.stderr, "unlink failed:", e From alan.gauld at btinternet.com Thu Sep 13 12:54:31 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 11:54:31 +0100 Subject: [Tutor] Print List In-Reply-To: <8c4c378fee72d4a28514d59390a652c7.squirrel@webmail.sonic.net> References: <6962C976AE76AC4298CBF6FD6D0C63561F392ED4@BL2PRD0710MB363.namprd07.prod.outlook.com> <8c4c378fee72d4a28514d59390a652c7.squirrel@webmail.sonic.net> Message-ID: On 13/09/12 00:36, akleider at sonic.net wrote: > > To make it even more generic I would suggest replacing > """ print(theHeader) """ > with > """ if theHeader: > print(theHeader) > """ > to avoid a blank line if you don't need/want a header line. Good catch, yes, that would be better. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 13 12:58:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 11:58:04 +0100 Subject: [Tutor] Sigh first real python task In-Reply-To: References: Message-ID: On 13/09/12 04:06, Mike S wrote: > ret = subprocess.call("smbclient //metricsmachine/reports/; put %s\" -U > metrics%%" % (fileName), shell=True) Isn't there a mismatched quote in there? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dvnsarma at gmail.com Thu Sep 13 14:29:35 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Sep 2012 17:59:35 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: I want to thank all of you who have come forward to help me. -- regards, Sarma. On Thu, Sep 13, 2012 at 10:46 AM, D.V.N.Sarma ??.??.???.???? < dvnsarma at gmail.com> wrote: > Yes. As far as I can see it does not contain any thing which > concerns the volume of sound. > > > -- > regards, > Sarma. > > On Thu, Sep 13, 2012 at 5:42 AM, Mark Lawrence wrote: > >> On 13/09/2012 00:57, D.V.N.Sarma ??.??.???.???? wrote: >> >>> The Beep attribute of winsound module is useful. But the volume is >>> feeble. >>> Is there anyway to control the loudness. >>> >>> >> Have you read http://docs.python.org/**library/winsound.html? >> >> -- >> Cheers. >> >> Mark Lawrence. >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Sep 13 16:07:10 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 13 Sep 2012 15:07:10 +0100 Subject: [Tutor] simon game issues Message-ID: Hi guys. my Python tutorial set me a task to recreate a simon game using livewires. http://www.youtube.com/watch?v=agUABjGAJww this is quite long, i understand if you can't help right away summary: i create 4 squared shaped objects(red, blue, green, yellow) as instances for a class derived from the Sprite class i create 4 animation objects to represent the 4 colour shaped objects. the animations get brighter in colour so the user can understand which colour he has to follow the animations also light up when the user presses the keyboard key they are assigned too. they are instances for a class derived from the Animation class. i have also included 4 sound files, assigned to 1 animation object to be played each time that animation lights up My problems: everytime i want to play a sequence for the user to follow. i run into this problem. i create 1 animation say red, so the user can see the 1st colour he has to follow. then i put a timed delay time.sleep(1) before i display the next animation, say blue. i have tried many other timing methods to achieve this, but once there is some sort of timer, the whole screen pauses for the duration of the timed delay (but the sound files play simultaneously during that freeze) then after that, the sequence is displayed at the same time. not 1 after the other. so even though i put the timer after the creation of the 1st animation, the timer for some reason happens before it. is there a way i can get around this? I also start the game/program by displaying the 4 square objects (Sprite Class) before adding their animation. after the creation of the sprites i play the animation sequence. The problem is they play as soon as the game starts before the Sprites are even displayed, and also simultaneously (not in a sequnce) making it confusng. so after creating the sprites, i added a timer so the animations happens after the sprites are shown. But again because of this timer, which is meant to occur after the creation of the sprites, when i start the game, i get a blank screen for the duration of the timer((but the sound files, again play simultaneously during that time). After that i still don't get the sprites, i get their animatons instead, then finally the sprites are displayed. i dont understand, the Sprites are meant to be the 1st things on the screen, is there a solution? Getting user input: the last problem i have is when the user presses a key to select a colour. i have the script check for the key press, then return the colour to a function/method called def result(self, color): that determines if he got the right colour. if he does i increase score by 1. to check results i create 2 lists. one with all 4 colours: self.animation = [Pressed.dict_red, Pressed.dict_blue, Pressed.dict_green, Pressed.dict_yellow] then i create an empty list to append the sequence in the order i randomly played them, so i can check if the user got each colour: self.get_animation = [] < they append from the 1st list above and my result function uses it to check colours here's how it goes. if keyboard for colour red is pressed: create red animation: send results back to result method: self.game.result(red) my result method and its class: self.stage = 3 ..#say if we were on stage 3. i would play 3 colours. stage 4 would be 4 colours self.counter = -1 .....#to correctly index list def result(self, COLOUR): self.counter += 1 #count is now at 0 self.end_testing = self.stage ..#this will count down from the stages value. once it reaches 0, there is no more colours to check for if COLOUR in self.get_animation[self.counter]: self.score.value += 1 self.end_testing -= 1 even though i am using a counter here to count down: self.end_testing < i have used while and for loops also. My problem is none of these work because a keypress from the user, even if tapped, registers as multiple key presses, the self.score that i increment by 1 flies to about 40 from 1 key press. as a result my counter i use to index the list is way out of range. i tried to add a time.sleep(.03) as soon as a key is pressed, so it would register once. it managed to limit it to 4 presses, so self.score would equal 4 after 1 press, 8 after 2.. in that i started my counter at -4. then the code self.counter /= 4 would give me 0. after the next 4 presses, my counter would be at 4, the same code self.counter /= 4 would give me 1. after the next 4 presses, my counter would be at 8, the same code self.counter /= 4 would give me 2. this successfully fixed my indexing issue, but it needs A LOT of if statements and it is getting to confusing. isnt there a way to make 1 key press mean 1? and not 40? other wise how can i keep track of the score. any help? do i quit this exercise and blame it on the program just not following my instructions? From breamoreboy at yahoo.co.uk Thu Sep 13 17:12:55 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Sep 2012 16:12:55 +0100 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On 13/09/2012 13:29, D.V.N.Sarma ??.??.???.???? wrote: > I want to thank all of you who have come forward to help me. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > No problem :) If you have found a solution could you please publish it here for the benefit of others, or at least provide a link. -- Cheers. Mark Lawrence. From dvnsarma at gmail.com Thu Sep 13 17:48:13 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Sep 2012 21:18:13 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: As far as programming volume is concerned winsound.Beep has only frequency and duration. pyaudio module appears to have provision for volume control. Please refer to eryksun's post. -- regards, Sarma. On Thu, Sep 13, 2012 at 8:42 PM, Mark Lawrence wrote: > On 13/09/2012 13:29, D.V.N.Sarma ??.??.???.???? wrote: > >> I want to thank all of you who have come forward to help me. >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> > No problem :) If you have found a solution could you please publish it > here for the benefit of others, or at least provide a link. > > > -- > Cheers. > > Mark Lawrence. > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Thu Sep 13 19:23:36 2012 From: modulok at gmail.com (Modulok) Date: Thu, 13 Sep 2012 11:23:36 -0600 Subject: [Tutor] Does anyone use UML? Message-ID: List, Does anyone use UML (Unified Modeling Language) with python? If so, what tools do you use? Is it worth the added effort? -Modulok- From alan.gauld at btinternet.com Thu Sep 13 19:53:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 18:53:01 +0100 Subject: [Tutor] 'class' for someone with no object oriented programming experience In-Reply-To: References: Message-ID: > Classes elude me almost entirely. I've followed the tutorials at > http://bit.ly/MCAhYx and http://goo.gl/c170V but in neither one do > classes click. OK, the problem is all those tutorials assume you understand OOP and only show you how Python does it. You need something that explains OOP first (or as well). You can try the OOP topic in my tutor or google for an intro to OOP. Unfortunately OOP is one of those topics that has grown up from several different sources and so there are many slightly divergent views on what exactly it means. But the general gist is usually the same. > element to python, it's like building a car from the ground up but never > learning how to add oil. Actually you can go a very long way in Python without OOP. Certainly without classes. Its more like building a car from the ground up but not understanding thermodynamics. > As an example, I am going to reference this: > http://stackoverflow.com/questions/6671620/list-users-in-irc-channel-using-twisted-python-irc-framework Don;t even contemplate using Twisted as a concept learning tool, except for Twisted itself! :-) Twisted is very powerful but its not for beginners. > Are there any better resources for learning classes for someone who's > never touched object oriented programming in the past besides basic > interpretation for debugging purposes? There are many but the focus needs to be on OOP - the why and wherefore not the language syntax. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ascheel at gmail.com Thu Sep 13 20:00:23 2012 From: ascheel at gmail.com (Art Scheel) Date: Thu, 13 Sep 2012 12:00:23 -0600 Subject: [Tutor] 'class' for someone with no object oriented programming experience In-Reply-To: References: Message-ID: Yes, I've noticed that. However, after being asked to go re-read the classes section on python.org, it makes more sense to me. I've found it's the terminology used and until you have that down, the rest is gibberish. I'm doing ok, now, but still have a lot to learn on them. I think the only way I'll get it for sure is to do it. Do it again. Again. Again. Again. I'm not concerned about it so much because each time I go over it again, I understand more. On Thu, Sep 13, 2012 at 11:53 AM, Alan Gauld wrote: > > Classes elude me almost entirely. I've followed the tutorials at >> http://bit.ly/MCAhYx and http://goo.gl/c170V but in neither one do >> classes click. >> > > OK, the problem is all those tutorials assume you understand OOP and only > show you how Python does it. You need something that explains OOP first (or > as well). > > You can try the OOP topic in my tutor or google for an intro to OOP. > Unfortunately OOP is one of those topics that has grown up from several > different sources and so there are many slightly divergent views on what > exactly it means. But the general gist is usually the same. > > > element to python, it's like building a car from the ground up but never >> learning how to add oil. >> > > Actually you can go a very long way in Python without OOP. > Certainly without classes. Its more like building a car > from the ground up but not understanding thermodynamics. > > > > As an example, I am going to reference this: >> http://stackoverflow.com/**questions/6671620/list-users-** >> in-irc-channel-using-twisted-**python-irc-framework >> > > Don;t even contemplate using Twisted as a concept learning tool, except > for Twisted itself! :-) > > Twisted is very powerful but its not for beginners. > > > Are there any better resources for learning classes for someone who's >> never touched object oriented programming in the past besides basic >> interpretation for debugging purposes? >> > > There are many but the focus needs to be on OOP - the why and wherefore > not the language syntax. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Molon Labe "Come and take them" "By divine design, fathers are to preside over their families in love and righteousness and are responsible to provide the necessities of life and protection for their families." "The Marines I have seen around the world have the cleanest bodies, the filthiest minds, the highest morale, and the lowest morals of any group of animals I have ever seen. Thank God for the United States Marine Corps!" -Eleanor Roosevelt -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 13 21:03:45 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 13 Sep 2012 15:03:45 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Thu, Sep 13, 2012 at 11:48 AM, D.V.N.Sarma ??.??.???.???? wrote: > > As far as programming volume is concerned winsound.Beep has only frequency > and duration. pyaudio module appears to have provision for volume control. You should be able to add a wave header to a raw byte string. For example: import wave import winsound from cStringIO import StringIO def get_wave(data): f = StringIO() w = wave.open(f, 'w') w.setnchannels(1) # mono w.setsampwidth(2) # 2 bytes w.setframerate(48000) # samples/second w.writeframes(data) return f.getvalue() Then play the sound like this (_untested_): wave_data = get_wave(data) windsound.PlaySound(wave_data, winsound.SND_MEMORY) I've modified my previous script to add simple polyphonic sound. I included a basic square wave and a sawtooth wave, plus a random polyphonic wave. It's the kind of sound you might hear in a cheesy greeting card. Also, since you're looking to use winsound.PlaySound(), I changed the byte packing to use a little endian signed short (int16). I think that's what Windows wave files use. My demo below still uses pyaudio, which wraps the cross-platform PortAudio library. To me it seems like a better solution than relying on the standard library (e.g. the standard lib uses OSS on Linux; I don't even have that installed). Hopefully it performs OK on your computer. Using NumPy arrays would speed up the number crunching. import pyaudio from math import sin, pi from struct import pack from random import sample, randrange def polywave(freqs, amps, f0, fs): """create a polyphonic waveform freqs: sequence of frequencies (Hz) amps: sequence of amplitudes f0: fundamental frequency (Hz) fs: samples/second output is normalized to the range [-1,1]. """ N = int(fs / f0) rad_step = 2 * pi / fs # radians / (Hz * sample) wave = [0.0] * N for f, a in zip(freqs, amps): for n in xrange(N): wave[n] += a * sin(rad_step * f * n) maxamp = abs(max(wave, key=lambda x: abs(x))) return [samp / maxamp for samp in wave] def packwave(wave, vol=1, duration=None, fs=None): """pack a waveform as bytes (int16) wave: sample sequence, |mag| <= 1 vol: optional volume scale, |mag| <= 1 duration: optional loop time (seconds) fs: samples/second fs is required to set duration. """ scale = min(vol * 32767, 32767) ncycles = 1 if not (duration is None or fs is None): ncycles = int(round(1.0 * duration * fs / len(wave))) data = b''.join(pack(' Friends, I have a 2D matrix (a numpy array) and i am looping over each row in the matrix. I would like to know how i can find the index of each element in a while looping a row. Is there any function in numpy. Thanks -- C. Balasubramanian From oscar.j.benjamin at gmail.com Thu Sep 13 22:48:46 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 13 Sep 2012 21:48:46 +0100 Subject: [Tutor] index of elements in numpy array In-Reply-To: References: Message-ID: On 13 September 2012 21:16, Bala subramanian wrote: > Friends, > I have a 2D matrix (a numpy array) and i am looping over each row in > the matrix. I would like to know how i can find the index of each > element in a while looping a row. Is there any function in numpy. > Your question could mean several things. Could you post a small piece of example code and clarify what it is you're unable to do? Here's an example that loops over all elements of a 2D Matrix: >>> import numpy >>> M = numpy.array([[1, 1], [2, 3], [5, 8]]) >>> M array([[1, 1], [2, 3], [5, 8]]) >>> numrows, numcols = M.shape >>> for i in range(numrows): ... for j in range(numcols): ... print M[i, j] ... 1 1 2 3 5 8 Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 13 23:57:12 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2012 22:57:12 +0100 Subject: [Tutor] Does anyone use UML? In-Reply-To: References: Message-ID: On 13/09/12 18:23, Modulok wrote: > Does anyone use UML (Unified Modeling Language) with python? If so, what tools > do you use? Is it worth the added effort? I use UML with most things and even in situations where I'm not writing code or developing software. It is a good general purpose modelling notation for understanding co0mplex problems. And the last phrase is key. If the problem isn't complex you don't really need UML. If you can hold the concept in your head or explain it with text/pseudo code you don;t need UML. If you have a dozen or more classes all interacting and multi-level state machines and dozens of different user roles interacting or a 6 or 7 level deep inheritance lattice or a multi site distributed system then UML is invaluable. If you have less than 4 classes and only one level of inheritance then you probably don't need it. In between its a matter of taste and situation. As for tools I've used everything from Visio/Dia through to IBM RSA and Borland Together, and of course whiteboards! The fact its Python makes no difference at all, what matters is how complex is the problem? How many people need to share the understanding? Do you even understand it? If you don't understand what you are being asked to solve(*) then UML is possibly essential since it gives you the analytical tools needed to break the complexity into something you can get your head around and the notation to record the result. (*)The vast majority of the projects I work on start out with something I don't even begin to comprehend....It often takes 3-6 months of analysis before I'm even at the stage of starting a design. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Sep 14 00:25:49 2012 From: d at davea.name (Dave Angel) Date: Thu, 13 Sep 2012 18:25:49 -0400 Subject: [Tutor] simon game issues In-Reply-To: References: Message-ID: <50525D6D.1090409@davea.name> On 09/13/2012 10:07 AM, Matthew Ngaha wrote: > Hi guys. my Python tutorial set me a task to recreate a simon game > using livewires. > http://www.youtube.com/watch?v=agUABjGAJww > this is quite long, i understand if you can't help right away > > summary: > i create 4 squared shaped objects(red, blue, green, yellow) as > instances for a class derived from the Sprite class > i create 4 animation objects to represent the 4 colour shaped objects. > the animations get brighter in colour so the user can understand which > colour he has to follow > the animations also light up when the user presses the keyboard key > they are assigned too. > they are instances for a class derived from the Animation class. > i have also included 4 sound files, assigned to 1 animation object to > be played each time that animation lights up > > My problems: > everytime i want to play a sequence for the user to follow. i run into > this problem. i create 1 animation say red, so the user can see the > 1st colour he has to follow. then i put a timed delay time.sleep(1) > before i display the next animation, say blue. i have tried many other > timing methods to achieve this, but once there is some sort of timer, > the whole screen pauses for the duration of the timed delay (but the > sound files play simultaneously during that freeze) then after that, > the sequence is displayed at the same time. not 1 after the other. so > even though i put the timer after the creation of the 1st animation, > the timer for some reason happens before it. is there a way i can get > around this? > > I also start the game/program by displaying the 4 square objects > (Sprite Class) before adding their animation. after the creation of > the sprites i play the animation sequence. The problem is they play as > soon as the game starts before the Sprites are even displayed, and > also simultaneously (not in a sequnce) making it confusng. so after > creating the sprites, i added a timer so the animations happens after > the sprites are shown. But again because of this timer, which is meant > to occur after the creation of the sprites, when i start the game, i > get a blank screen for the duration of the timer((but the sound files, > again play simultaneously during that time). After that i still don't > get the sprites, i get their animatons instead, then finally the > sprites are displayed. i dont understand, the Sprites are meant to be > the 1st things on the screen, is there a solution? > > Getting user input: > the last problem i have is when the user presses a key to select a > colour. i have the script check for the key press, then return the > colour to a function/method called def result(self, color): that > determines if he got the right colour. if he does i increase score by > 1. to check results i create 2 lists. one with all 4 colours: > > self.animation = [Pressed.dict_red, Pressed.dict_blue, > Pressed.dict_green, Pressed.dict_yellow] > then i create an empty list to append the sequence in the order i > randomly played them, so i can check if the user got each colour: > self.get_animation = [] < they append from the 1st list above and my > result function uses it to check colours > > here's how it goes. > if keyboard for colour red is pressed: > create red animation: > send results back to result method: self.game.result(red) > > my result method and its class: > self.stage = 3 ..#say if we were on stage 3. i would play 3 > colours. stage 4 would be 4 colours > > self.counter = -1 .....#to correctly index list > def result(self, COLOUR): > self.counter += 1 #count is now at 0 > self.end_testing = self.stage ..#this will count down from > the stages value. once it reaches 0, there is no more colours to check > for > > if COLOUR in self.get_animation[self.counter]: > self.score.value += 1 > self.end_testing -= 1 > > even though i am using a counter here to count down: self.end_testing > < i have used while and for loops also. My problem is none of these > work because a keypress from the user, even if tapped, registers as > multiple key presses, the self.score that i increment by 1 flies to > about 40 from 1 key press. as a result my counter i use to index the > list is way out of range. i tried to add a time.sleep(.03) as soon as > a key is pressed, so it would register once. it managed to limit it to > 4 presses, so self.score would equal 4 after 1 press, 8 after 2.. in > that i started my counter at -4. then the code self.counter /= 4 would > give me 0. after the next 4 presses, my counter would be at 4, the > same code self.counter /= 4 would give me 1. after the next 4 presses, > my counter would be at 8, the same code self.counter /= 4 would give > me 2. this successfully fixed my indexing issue, but it needs A LOT of > if statements and it is getting to confusing. isnt there a way to make > 1 key press mean 1? and not 40? other wise how can i keep track of the > score. any help? do i quit this exercise and blame it on the program > just not following my instructions? It would appear you're running some form of event loop, such as wxpython, tkinter, pygame, or whatever. If so, you have to do your delays using the mechanism that system defines, not using sleep(). As you've discovered, sleep() stops the whole thread, and that's not what you want. What you want is to set an event to fire at some measured time in the future, so the actual waiting is done inside the event loop. -- DaveA From akleider at sonic.net Fri Sep 14 00:32:56 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Thu, 13 Sep 2012 15:32:56 -0700 Subject: [Tutor] index of elements in numpy array In-Reply-To: References: Message-ID: <0215d8096c28445547907d4c2cf49a93.squirrel@webmail.sonic.net> > On 13 September 2012 21:16, Bala subramanian > wrote: > >> Friends, >> I have a 2D matrix (a numpy array) and i am looping over each row in >> the matrix. I would like to know how i can find the index of each >> element in a while looping a row. Is there any function in numpy. >> > > Your question could mean several things. Could you post a small piece of > example code and clarify what it is you're unable to do? > > Here's an example that loops over all elements of a 2D Matrix: > >>>> import numpy >>>> M = numpy.array([[1, 1], [2, 3], [5, 8]]) >>>> M > array([[1, 1], > [2, 3], > [5, 8]]) >>>> numrows, numcols = M.shape >>>> for i in range(numrows): > ... for j in range(numcols): > ... print M[i, j] > ... > 1 > 1 > 2 > 3 > 5 > 8 > > Oscar I think what he wants is to replace your print statement with """ if : print "Indeces are %d and %d."%(i, j, ) """ From d at davea.name Fri Sep 14 00:39:29 2012 From: d at davea.name (Dave Angel) Date: Thu, 13 Sep 2012 18:39:29 -0400 Subject: [Tutor] index of elements in numpy array In-Reply-To: References: Message-ID: <505260A1.20800@davea.name> On 09/13/2012 04:16 PM, Bala subramanian wrote: > Friends, > I have a 2D matrix (a numpy array) and i am looping over each row in > the matrix. I would like to know how i can find the index of each > element in a while looping a row. Is there any function in numpy. > > Thanks > Perhaps you're asking a more general question. When iterating over a collection, sometimes you not only want the object, but you also want the index you might have used to fetch it. for row in rows: dosomething with row for index, row in enumerate(rows): dosomething with row and with index Now if rows be a list, or whatever numpy decides to call it, then you can manipulate the particular one with rows[index]. -- DaveA From dvnsarma at gmail.com Fri Sep 14 02:37:24 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Fri, 14 Sep 2012 06:07:24 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: Error: "name data undefined" On Fri, Sep 14, 2012 at 12:33 AM, eryksun wrote: > On Thu, Sep 13, 2012 at 11:48 AM, D.V.N.Sarma ??.??.???.???? > wrote: > > > > As far as programming volume is concerned winsound.Beep has only > frequency > > and duration. pyaudio module appears to have provision for volume > control. > > You should be able to add a wave header to a raw byte string. For example: > > > import wave > import winsound > from cStringIO import StringIO > > def get_wave(data): > f = StringIO() > w = wave.open(f, 'w') > w.setnchannels(1) # mono > w.setsampwidth(2) # 2 bytes > w.setframerate(48000) # samples/second > w.writeframes(data) > return f.getvalue() > > > Then play the sound like this (_untested_): > > > wave_data = get_wave(data) > windsound.PlaySound(wave_data, winsound.SND_MEMORY) > > > > -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvnsarma at gmail.com Fri Sep 14 02:49:41 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Fri, 14 Sep 2012 06:19:41 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: This worked on my computor. Thank you. It will take me sometime to digest the program. -- regards, Sarma. On Fri, Sep 14, 2012 at 12:33 AM, eryksun wrote: > > I've modified my previous script to add simple polyphonic sound. I > included a basic square wave and a sawtooth wave, plus a random > polyphonic wave. It's the kind of sound you might hear in a cheesy > greeting card. Also, since you're looking to use winsound.PlaySound(), > I changed the byte packing to use a little endian signed short > (int16). I think that's what Windows wave files use. > > My demo below still uses pyaudio, which wraps the cross-platform > PortAudio library. To me it seems like a better solution than relying > on the standard library (e.g. the standard lib uses OSS on Linux; I > don't even have that installed). > > Hopefully it performs OK on your computer. Using NumPy arrays would > speed up the number crunching. > > > import pyaudio > from math import sin, pi > from struct import pack > from random import sample, randrange > > def polywave(freqs, amps, f0, fs): > """create a polyphonic waveform > > freqs: sequence of frequencies (Hz) > amps: sequence of amplitudes > f0: fundamental frequency (Hz) > fs: samples/second > > output is normalized to the range [-1,1]. > """ > N = int(fs / f0) > rad_step = 2 * pi / fs # radians / (Hz * sample) > wave = [0.0] * N > for f, a in zip(freqs, amps): > for n in xrange(N): > wave[n] += a * sin(rad_step * f * n) > maxamp = abs(max(wave, key=lambda x: abs(x))) > return [samp / maxamp for samp in wave] > > def packwave(wave, vol=1, duration=None, fs=None): > """pack a waveform as bytes (int16) > > wave: sample sequence, |mag| <= 1 > vol: optional volume scale, |mag| <= 1 > duration: optional loop time (seconds) > fs: samples/second > > fs is required to set duration. > """ > scale = min(vol * 32767, 32767) > ncycles = 1 > if not (duration is None or fs is None): > ncycles = int(round(1.0 * duration * fs / len(wave))) > data = b''.join(pack(' return data * ncycles > > def make_square(num, f0, fs): > """generate square wave components > > num: number of harmonics > f0: funamental frequency (Hz) > fs: samples/second > > fs/2 is the upper bound. > """ > stop = min(2*num, int(fs / (2 * f0))) > freqs = [n * f0 for n in xrange(1, stop, 2)] > amps = [1.0 / n for n in xrange(1, stop, 2)] > return freqs, amps > > def make_saw(num, f0, fs): > """generate sawtooth wave components > > num: number of harmonics > f0: funamental frequency (Hz) > fs: samples/second > > fs/2 is the upper bound. > """ > stop = min(num + 1, int(fs / (2 * f0))) > freqs = [n * f0 for n in xrange(1, stop)] > amps = [(-1.0) ** (n + 1) / n for n in xrange(1, stop)] > return freqs, amps > > def make_rand(num, f0, fs): > """generate wave with random harmonics/amplitudes""" > ftop = min(fs // 2, 12000) > nmax = int(ftop / f0) > num = min(num, nmax) > freqs = [n * f0 for n in sample(xrange(1, nmax+1), num)] > amps = [randrange(32768)/32767.0 for n in xrange(num)] > return freqs, amps > > def play(data, stream): > chunks = (data[i:i+1024] for i in xrange(0, len(data), 1024)) > for chunk in chunks: > stream.write(chunk) > > if __name__ == "__main__": > from time import sleep > > fs = 48000 > > p = pyaudio.PyAudio() > stream = p.open( > format=pyaudio.paInt16, > channels=1, > rate=fs, > frames_per_buffer=fs//4, > output=True) > > # http://en.wikipedia.org/wiki/ > # Equal_temperament#Calculating_absolute_frequencies > > note = lambda n: 440 * (2**(1/12.)) ** (-21 + n) > > scale = [note(n) for n in range(12)] > rscale = [note(13-n) for n in range(12)] > vols = [0.2 + 0.05*n for n in range(len(scale))] > rvols = list(reversed(vols)) > > def play_scale(scale, vols, wave_func, master_vol=1): > duration = 0.5 > nharmonics = 30 > for f0, vol in zip(scale, vols): > freqs, amps = wave_func(nharmonics, f0, fs) > wave = polywave(freqs, amps, f0, fs) > data = packwave(wave, master_vol * vol, duration, fs) > play(data, stream) > sleep(0.5) > > play_scale(scale, vols, make_square, 0.5) > play_scale(rscale, rvols, make_saw, 0.5) > play_scale(scale, vols, make_rand, 0.75) > play_scale(rscale, rvols, make_rand, 0.75) > > stream.close() > p.terminate() > -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Fri Sep 14 09:29:00 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 14 Sep 2012 00:29:00 -0700 Subject: [Tutor] 2.7.3 documentation gripe (feel free to ignore) Message-ID: <5052DCBC.8040402@gmail.com> 6.5. The del statement *del_stmt* ::= "del" target_list Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints. =============================================== They call this DOCUMENTATION??? "it's similar to such and such - you figure it out....here are the hints"! Bah! I hope their code is better than the documentation. :-p Ray P.S. Not a request for help - I can find the answers. Just a comment on the documentation in general From bala.biophysics at gmail.com Fri Sep 14 10:36:08 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Fri, 14 Sep 2012 10:36:08 +0200 Subject: [Tutor] index of elements in numpy array In-Reply-To: <505260A1.20800@davea.name> References: <505260A1.20800@davea.name> Message-ID: Thank you all for the answer. Below, i have pasted a sample code that shows what i am intending to do. The code fails at line 13 as numpy array dnt have a index attribute. 1 #!/usr/bin/env python 2 import numpy as np 3 4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12]) 5 6 b=np.reshape(a,(3,4)) 7 8 z=[100,101,102,103,104,106,107,108,109,110,111,112] 9 10 # loop over each row 11 for i1, d1 in enumerate(b): 12 # each x in d1 - value in z corresponding to index of x in d1 13 d1=[x-z[d1.index(x)] for x in d1] If d1 is a simple list, i can fetch the index of its element as d1.index(x). So i would like to know how can achieve the same with numpy array. Thanks once again, Bala On Fri, Sep 14, 2012 at 12:39 AM, Dave Angel wrote: > On 09/13/2012 04:16 PM, Bala subramanian wrote: >> Friends, >> I have a 2D matrix (a numpy array) and i am looping over each row in >> the matrix. I would like to know how i can find the index of each >> element in a while looping a row. Is there any function in numpy. >> >> Thanks >> > > Perhaps you're asking a more general question. When iterating over a > collection, sometimes you not only want the object, but you also want > the index you might have used to fetch it. > > for row in rows: > dosomething with row > > for index, row in enumerate(rows): > dosomething with row and with index > > Now if rows be a list, or whatever numpy decides to call it, then you > can manipulate the particular one with rows[index]. > > > > -- > > DaveA > -- C. Balasubramanian From crawlzone at gmail.com Fri Sep 14 10:43:24 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 14 Sep 2012 01:43:24 -0700 Subject: [Tutor] (2.7.3) Inexplicable change of type Message-ID: <5052EE2C.8080303@gmail.com> The code: def split_string(source,splitlist): idx = 0 while idx < len(splitlist): if splitlist[idx] in source: source = ' '.join(source.split(splitlist[idx])) idx += 1 source = source.split(' ') print "source is", source, "and its type is", type(source) # <-- while "'' in source: # <-- source = source.remove('') return source out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.') print out The result: source is ['Hi', '', 'I', 'am', 'your', 'Assistant', 'Instructor', '', 'Peter', ''] and its type is Traceback (most recent call last): File "/tmp/pytmp.py", line 18, in out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.') File "/tmp/pytmp.py", line 13, in split_string while '' in source: TypeError: argument of type 'NoneType' is not iterable Between the two arrows, 'source' inexplicably switches from to . Why? Ray From __peter__ at web.de Fri Sep 14 11:02:22 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Sep 2012 11:02:22 +0200 Subject: [Tutor] index of elements in numpy array References: <505260A1.20800@davea.name> Message-ID: Bala subramanian wrote: > Thank you all for the answer. Below, i have pasted a sample code that > shows what i am intending to do. The code fails at line 13 as numpy > array dnt have a index attribute. > > 1 #!/usr/bin/env python > 2 import numpy as np > 3 > 4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12]) > 5 > 6 b=np.reshape(a,(3,4)) > 7 > 8 z=[100,101,102,103,104,106,107,108,109,110,111,112] > 9 > 10 # loop over each row > 11 for i1, d1 in enumerate(b): > 12 # each x in d1 - value in z corresponding to index of x in d1 > 13 d1=[x-z[d1.index(x)] for x in d1] > > If d1 is a simple list, i can fetch the index of its element as > d1.index(x). So i would like to know how can achieve the same with > numpy array. How about >>> b - np.array(z[:4]) array([[-99, -99, -99, -99], [-95, -95, -95, -95], [-91, -91, -91, -91]]) (Note that the result may differ from that of your code if d1 contains duplicate values) From steve at pearwood.info Fri Sep 14 11:07:18 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 14 Sep 2012 19:07:18 +1000 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: <5052EE2C.8080303@gmail.com> References: <5052EE2C.8080303@gmail.com> Message-ID: <5052F3C6.5070404@pearwood.info> On 14/09/12 18:43, Ray Jones wrote: > Between the two arrows, 'source' inexplicably switches from > to. Why? source.remove('') does not do what you think it does. Checking the Fine Manual is always a good idea, or experimentation at the interactive interpreter: py> source = list('abcd') py> result = source.remove('a') py> result is None True py> source ['b', 'c', 'd'] The list.remove method operates on the list in place, and like (nearly?) all such in-place methods, it returns None. So source = source.remove(' ') replaces source with None instead of the list, which is then lost. By the way, at the interactive interpreter you can also say: help(list.remove) to read some documentation on the method. -- Steven From eryksun at gmail.com Fri Sep 14 11:09:29 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Sep 2012 05:09:29 -0400 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: <5052EE2C.8080303@gmail.com> References: <5052EE2C.8080303@gmail.com> Message-ID: On Fri, Sep 14, 2012 at 4:43 AM, Ray Jones wrote: > > source = source.remove('') > > Between the two arrows, 'source' inexplicably switches from > to . Why? >>> x = [1,2,3] >>> result = x.remove(1) >>> type(result) >>> x [2, 3] Methods that mutate an object typically return None. Just call remove() without reassignment. From __peter__ at web.de Fri Sep 14 11:06:46 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Sep 2012 11:06:46 +0200 Subject: [Tutor] (2.7.3) Inexplicable change of type References: <5052EE2C.8080303@gmail.com> Message-ID: Ray Jones wrote: > source = source.remove('') list.remove() modifies the list in-place and therefore by convention returns None: >>> source = ["one", "", "three"] >>> source.remove("") >>> source ['one', 'three'] From crawlzone at gmail.com Fri Sep 14 11:13:45 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 14 Sep 2012 02:13:45 -0700 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: <5052F3C6.5070404@pearwood.info> References: <5052EE2C.8080303@gmail.com> <5052F3C6.5070404@pearwood.info> Message-ID: <5052F549.5010309@gmail.com> On 09/14/2012 02:07 AM, Steven D'Aprano wrote: > On 14/09/12 18:43, Ray Jones wrote: > >> Between the two arrows, 'source' inexplicably switches from >> to. Why? > > source.remove('') does not do what you think it does. Checking the > Fine Manual is always a good idea, or experimentation at the interactive > interpreter: [...] > So source = source.remove(' ') replaces source with None instead of the > list, which is then lost. > > By the way, at the interactive interpreter you can also say: > > > help(list.remove) > > to read some documentation on the method. > I did use the help() on that, but I missed the 'in place' part. That would explain things! :)) Thanks. Ray From crawlzone at gmail.com Fri Sep 14 11:15:10 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 14 Sep 2012 02:15:10 -0700 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: References: <5052EE2C.8080303@gmail.com> Message-ID: <5052F59E.2090507@gmail.com> Thanks for the responses. I knew it had to be something stupid ;)). Ray From steve at pearwood.info Fri Sep 14 11:32:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 14 Sep 2012 19:32:34 +1000 Subject: [Tutor] 2.7.3 documentation gripe (feel free to ignore) In-Reply-To: <5052DCBC.8040402@gmail.com> References: <5052DCBC.8040402@gmail.com> Message-ID: <5052F9B2.4030802@pearwood.info> On 14/09/12 17:29, Ray Jones wrote: > > 6.5. The del > statement [...] > They call this DOCUMENTATION??? "it's similar to such and such - you > figure it out....here are the hints"! > > Bah! I hope their code is better than the documentation. :-p *shrug* Look at the size of the documentation for assignments, two and a half pages. Deletion is almost exactly the same except there is no target on the left hand side of the "operator". I'm honestly not sure that there would be any advantage to spelling out in gory detail over a page and a half how del works, but if you think the documentation is lacking, remember that Python is an open-source project and community input is welcome and desired. -- Steven From crawlzone at gmail.com Fri Sep 14 11:37:35 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 14 Sep 2012 02:37:35 -0700 Subject: [Tutor] 2.7.3 documentation gripe (feel free to ignore) In-Reply-To: <5052F9B2.4030802@pearwood.info> References: <5052DCBC.8040402@gmail.com> <5052F9B2.4030802@pearwood.info> Message-ID: <5052FADF.2050705@gmail.com> On 09/14/2012 02:32 AM, Steven D'Aprano wrote: > On 14/09/12 17:29, Ray Jones wrote: >> >> 6.5. The del >> statement > [...] >> They call this DOCUMENTATION??? "it's similar to such and such - you >> figure it out....here are the hints"! > I'm honestly not sure that there would be any advantage to spelling out > in gory detail over a page and a half how del works, but if you think the > documentation is lacking, remember that Python is an open-source project > and community input is welcome and desired. > Great reply to sour grapes! lol I'll remember that ;). Ray From eryksun at gmail.com Fri Sep 14 12:05:33 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Sep 2012 06:05:33 -0400 Subject: [Tutor] index of elements in numpy array In-Reply-To: References: <505260A1.20800@davea.name> Message-ID: On Fri, Sep 14, 2012 at 4:36 AM, Bala subramanian wrote: > > 10 # loop over each row > 11 for i1, d1 in enumerate(b): > 12 # each x in d1 - value in z corresponding to index of x in d1 > 13 d1=[x-z[d1.index(x)] for x in d1] > > If d1 is a simple list, i can fetch the index of its element as > d1.index(x). So i would like to know how can achieve the same with > numpy array. In general you don't want to loop over and enumerate a NumPy array. That's a lot slower than using vectorized operations (just like in MATLAB) and broadcasting. See Peter Otten's answer. For an 'index' operation you have a couple of options. To begin with, a test returns a bool array: >>> d = np.array([1,2,1,2,1]) >>> d == 1 array([ True, False, True, False, True], dtype=bool) You can use this bool array to index the source array: >>> d[d == 1] array([1, 1, 1]) >>> d[d == 1] = 3 >>> d array([3, 2, 3, 2, 3]) To get the indexes, use "nonzero" or "where": >>> np.nonzero(d == 2) (array([1, 3]),) >>> np.where(d == 2) (array([1, 3]),) From eryksun at gmail.com Fri Sep 14 13:54:42 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Sep 2012 07:54:42 -0400 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: On Thu, Sep 13, 2012 at 8:37 PM, D.V.N.Sarma ??.??.???.???? wrote: > > Error: "name data undefined" > >> import wave >> import winsound >> from cStringIO import StringIO >> >> def get_wave(data): >> f = StringIO() >> w = wave.open(f, 'w') >> w.setnchannels(1) # mono >> w.setsampwidth(2) # 2 bytes >> w.setframerate(48000) # samples/second >> w.writeframes(data) >> return f.getvalue() >> >> >> Then play the sound like this (_untested_): >> >> >> wave_data = get_wave(data) >> windsound.PlaySound(wave_data, winsound.SND_MEMORY) "data" is a byte string of packed samples. For example, the function packwave() converts a sequence of floats into a byte string. It assumes the input is in the range [-1.0, 1.0]. It scales this range to [-32767, 32767]. Each scaled value is packed as 2 bytes in little endian order. That means the order is (low byte, high byte). For example, 32767 becomes "\xff\x7f", where 0xff (255) is the low byte and 0x7f (127) is the high byte. You can calculate the value as follows: 255 + 127*256 = 32767. Since the format is 2's complement, the next value up, "\x00\x80", wraps around to -32768. Then "\x01\x80" is -32767, and so on, up to -1 at "\xff\xff". http://docs.python.org/library/struct http://en.wikipedia.org/wiki/Endianness http://en.wikipedia.org/wiki/Two%27s_complement From fomcl at yahoo.com Fri Sep 14 14:16:49 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 14 Sep 2012 05:16:49 -0700 (PDT) Subject: [Tutor] is this use or abuse of __getitem__ ? Message-ID: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> Hi, I defined a __getitem__ special method in a class that reads a binary data file using a C library. The docstring should clarify the purpose of the method. This works exactly as I intended it, however, the "key" argument is actually used as an index (it also raises an IndexError when is greater than the number of records in the file). Am I abusing the __getitem__ method, or is this just a creative way of using it? # Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 ??? def __getitem__(self, key): ??????? """ This function reports the record of case number . ??????? For example: firstRecord = FileReader(fileName)[0] """ ??????? if not isinstance(key, (int, float)): ??????????? raise TypeError ??????? if abs(key) > self.nCases: ??????????? raise IndexError ??????? retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(int(key))) ??????? self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() ??????? retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr) ??????? record = struct.unpack(self.structFmt, self.caseBuffer.raw) ??????? if any([retcode1, retcode2]): ??????????? raise RuntimeError, "Error retrieving record %d [%s, %s]" % \ ????????????????? (key, retcodes[retcode1], retcodes[retcode2]) ??????? return record ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From oscar.j.benjamin at gmail.com Fri Sep 14 14:38:18 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 14 Sep 2012 13:38:18 +0100 Subject: [Tutor] index of elements in numpy array In-Reply-To: References: <505260A1.20800@davea.name> Message-ID: On 14 September 2012 11:05, eryksun wrote: > On Fri, Sep 14, 2012 at 4:36 AM, Bala subramanian > wrote: > > > > 10 # loop over each row > > 11 for i1, d1 in enumerate(b): > > 12 # each x in d1 - value in z corresponding to index of x in d1 > > 13 d1=[x-z[d1.index(x)] for x in d1] > > > > If d1 is a simple list, i can fetch the index of its element as > > d1.index(x). So i would like to know how can achieve the same with > > numpy array. > Whether you use a list or a numpy array, iterating over the elements and then trying to get the index of each value from the value itself is inefficient. It's also leads to problems when the array/list contains duplicate values. I think the way to replace your line 13 would be to use: d1 = [x - z[n] for n, x in enumerate(d1)] There is another problem though which is that you're assigning to d1 which is the same name that you've used for your loop variable in the outer loop. This means that you're throwing away the values you compute. Are you hoping that by assigning to d1, the values would get stored in b? Perhaps what you need to do is: b[i1, :] = [x - z[n] for n, x in enumerate(d1)] This way the values will get stored in b. If you actually want them to be stored in another array, say c, then create that array before the loop with c = np.zeros_like(b) If this is what you're trying to do, though you would be better off just using Peter's suggestion: c = b - np.array(z[:b.shape[1]]) so that you don't need a loop at all. > In general you don't want to loop over and enumerate a NumPy array. > That's a lot slower than using vectorized operations (just like in > MATLAB) and broadcasting. See Peter Otten's answer. > > For an 'index' operation you have a couple of options. To begin with, > a test returns a bool array: > > > >>> d = np.array([1,2,1,2,1]) > > >>> d == 1 > array([ True, False, True, False, True], dtype=bool) > > > You can use this bool array to index the source array: > > > >>> d[d == 1] > array([1, 1, 1]) > > >>> d[d == 1] = 3 > >>> d > array([3, 2, 3, 2, 3]) > > > To get the indexes, use "nonzero" or "where": > > > >>> np.nonzero(d == 2) > (array([1, 3]),) > > >>> np.where(d == 2) > (array([1, 3]),) The suggestions above from eryksun are closer to what actually happens when you use the index function on a list, but you should consider whether or not that is really what you want to do. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Sep 14 14:37:14 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 14 Sep 2012 05:37:14 -0700 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: <5052EE2C.8080303@gmail.com> References: <5052EE2C.8080303@gmail.com> Message-ID: On 9/14/2012 1:43 AM Ray Jones said... > The code: > source = source.remove('') > return source To round things out, here's one way to do what I expect you're expecting: >>> r=range(10) >>> a = r.pop(r.index(4)) >>> a 4 >>> r [0, 1, 2, 3, 5, 6, 7, 8, 9] Emile From eryksun at gmail.com Fri Sep 14 14:50:55 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Sep 2012 08:50:55 -0400 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> Message-ID: On Fri, Sep 14, 2012 at 8:16 AM, Albert-Jan Roskam wrote: > > Am I abusing the __getitem__ method, or is this just a creative way of using it? No, you're using it the normal way. The item to get can be an index, a key, or even a slice. http://docs.python.org/reference/datamodel.html#object.__getitem__ > if not isinstance(key, (int, float)): > raise TypeError Instead you could raise a TypeError if "not hasattr(key, '__int__')" since later you call int(key). > if abs(key) > self.nCases: > raise IndexError You might also want to support slicing. Here's an example: http://stackoverflow.com/a/2936876/205580 From eryksun at gmail.com Fri Sep 14 15:28:26 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Sep 2012 09:28:26 -0400 Subject: [Tutor] (2.7.3) Inexplicable change of type In-Reply-To: References: <5052EE2C.8080303@gmail.com> Message-ID: On Fri, Sep 14, 2012 at 8:37 AM, Emile van Sebille wrote: > >> source = source.remove('') > > To round things out, here's one way to do what I expect you're expecting: > > >>> r=range(10) > >>> a = r.pop(r.index(4)) > >>> a > 4 > >>> r > [0, 1, 2, 3, 5, 6, 7, 8, 9] Ray was probably thinking in terms of immutable objects such as strings: >>> "1".replace('1', '2').replace('2', '3') '3' Since Python doesn't do in-place operations on strings, it has to return a new object for each call to replace(). list.pop() returns a value, but Ray doesn't want the value. Splitting on a single character leaves empty strings between consecutive runs of the character (or at the edges). For example, splitting 'babbbab' on 'b' returns ['', 'a', '', '', 'a', '']. Ray is looping until all of the empty strings have been removed from the list. It's a completely in-place modification. From steve at pearwood.info Fri Sep 14 17:33:11 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Sep 2012 01:33:11 +1000 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> Message-ID: <50534E37.6050106@pearwood.info> On 14/09/12 22:16, Albert-Jan Roskam wrote: > Hi, > > I defined a __getitem__ special method in a class that reads a binary data > file using a C library. The docstring should clarify the purpose of the >method. This works exactly as I intended it, however, the "key" argument is > actually used as an index (it also raises an IndexError when is >greater than the number of records in the file). Am I abusing the __getitem__ >method, or is this just a creative way of using it? No, that's exactly what __getitem__ is for. It does double-duty for key-lookup in mappings (dict[key]) and index-lookup in sequences (list[index]). You can also support ranges of indexes by accepting a slice argument. Another comment below: > # Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 > > def __getitem__(self, key): > """ This function reports the record of case number. > For example: firstRecord = FileReader(fileName)[0] """ > if not isinstance(key, (int, float)): > raise TypeError Floats? Do you actually have have case number (for example) 0.14285714285714285 ? For this case, I think it is reasonable to insist on exactly an int, and nothing else (except possibly a slice object, to support for example obj[2:15]). -- Steven From chigga101 at gmail.com Fri Sep 14 19:17:31 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Fri, 14 Sep 2012 18:17:31 +0100 Subject: [Tutor] simon game issues In-Reply-To: <50525D6D.1090409@davea.name> References: <50525D6D.1090409@davea.name> Message-ID: > It would appear you're running some form of event loop, such as > wxpython, tkinter, pygame, or whatever. If so, you have to do your > delays using the mechanism that system defines, not using sleep(). As > you've discovered, sleep() stops the whole thread, and that's not what > you want. What you want is to set an event to fire at some measured > time in the future, so the actual waiting is done inside the event loop. > hey i looked at the livewires documentation and pulled up the timer information. im struggling to figure out how to use its explanation. i need to use it at 2 different parts of the program. 1st when the game starts i need to create my sprite objects so they appear before my animation objects: red = Sprite(colour = Colours.red, x = 250, y = 255) games.screen.add(red) #timer event delay goes here so the animations don't start as soon as the game is opened, before the coloured sprites as they've been doing. self.create_animations() --------------------------------------------- i also need a timer event when i display my sequence of animation objects so they dont show on screen simultaneously. so: #1st animation red_animation = Animation(images = c_red, x = 250, y = 255, repeat_interval = 4, n_repeats = 1) games.screen.add(red_ani) red_sound.play() #Timer event to go here, so next animation in sequence goes after the timed pause. #2nd animation blue_animation = Animation(images = c_blue, x = 373, y = 255, repeat_interval = 4, n_repeats = 1) games.screen.add(blue_ani) blue_sound.play() do you think you can offer any help how to implement the timer code or function? i will provide the link to the page, but here's the relevant code: Timer The Timer class is a class you can add to something which is also a subclass of Object, to make an object that performs actions at regular intervals. A class which is intended to be used with another class is called a mix-in. For instance, if you wanted to make a new class of your own which was a Circle and also a Timer, you would define the class by saying class MyClass (games.Circle, games.Timer): ? init_timer (interval) interval is how often the tick method is called, measured in timer ticks. How long a tick is depends on the fps argument you give to the Screen?s mainloop method. Setting fps to 50 means a tick is 1/50 of a second. You must call this method emph{after} you have called the init_ method for the Object subclass you are using. ? stop () Stop the timer running. It continues to exist, but doesn?t count any more. ? start () Starts the timer again. A full interval will elapse before it ticks. ? get_interval () Gets the current interval. ? set_interval (interval) Sets the current interval. ? tick () This method must be supplied by you, by subclassing the Timer class. http://www.geon.wz.cz/livewires/w-livewires.html From fomcl at yahoo.com Fri Sep 14 20:33:02 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 14 Sep 2012 11:33:02 -0700 (PDT) Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <50534E37.6050106@pearwood.info> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> Message-ID: <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> > On 14/09/12 22:16, Albert-Jan Roskam wrote: >>??Hi, >> >>??I defined a __getitem__ special method in a class that reads a binary data >>??file using a C library. The docstring should clarify the purpose of the >> method. This works exactly as I intended it, however, the "key" > argument is >>??actually used as an index (it also raises an IndexError when? is >> greater than the number of records in the file). Am I abusing the > __getitem__ >> method, or is this just a creative way of using it? > > No, that's exactly what __getitem__ is for. It does double-duty for > key-lookup > in mappings (dict[key]) and index-lookup in sequences (list[index]). > > You can also support ranges of indexes by accepting a slice argument. ? COOL! I was already wondering how this could be implemented. Dive into Python is pretty exhaustive wrt special methods, but I don't think they mentioned using the slice class. Below is how I did it. Is it recommended to define the geitem() function inside the __getitem__() method? I was thinking I could also define a _getitem() private method. Hmmm, maybe getitem() is redefined over and over again the way I did it now? ??? def __getitem__(self, key): ??????? """ This function reports the record of case number . ??????? For example: firstRecord = SavReader(savFileName)[0] """ ??????? def getitem(key): ??????????? retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(int(key))) ??????????? self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() ??????????? retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr) ??????????? record = struct.unpack(self.structFmt, self.caseBuffer.raw) ??????????? if any([retcode1, retcode2]): ??????????????? raise RuntimeError, "Error retrieving record %d [%s, %s]" % \ ????????????????????? (key, retcodes[retcode1], retcodes[retcode2]) ??????????? return record ??????? if isinstance(key, slice): ??????????? records = [getitem(i) for i in range(*key.indices(self.nCases))] ??????????? return records ??????? elif hasattr(key, "__int__"): # isinstance(key, (int, float)): ??????????? if abs(key) > (self.nCases - 1): ??????????????? raise IndexError ??????????? else: ??????????????? key = self.nCases + key if key < 0 else key ??????????????? record = getitem(key) ??????????????? return record ??????? else: ??????????? raise TypeError?? > Another comment below: > > >>??# Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit > (Intel)] on win32 >> >> ? ? ? def __getitem__(self, key): >> ? ? ? ? ? """ This function reports the record of case > number. >> ? ? ? ? ? For example: firstRecord = FileReader(fileName)[0] > """ >> ? ? ? ? ? if not isinstance(key, (int, float)): >> ? ? ? ? ? ? ? raise TypeError > > Floats? Do you actually have have case number (for example) > 0.14285714285714285 ? > > For this case, I think it is reasonable to insist on exactly an int, > and nothing else (except possibly a slice object, to support for > example obj[2:15]). > I also accepted floats as a convenience. I had examples in mind like: record = data[1.0] . Kind of annoying when this raises a TypeError. But in your example makes perfect sense to raise such an exception. Eryksun, Steven: Thanks!!! Albert-Jan From rei.johny at yahoo.com.ph Sat Sep 15 07:09:55 2012 From: rei.johny at yahoo.com.ph (Johny Rei) Date: Sat, 15 Sep 2012 13:09:55 +0800 (SGT) Subject: [Tutor] (no subject) Message-ID: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> hi ?to all readers, i 'm a newbie and i'm interested to learn python programming, can anybody please guide me out to learn basic to advance python programming, be actually can anyone out there should suggest a free book that i can read it on just to learn from as a newbie to python programming? i can be kindly respect and appreciate the guidance you can ?recommend it to me..thnx -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen at averagesecurityguy.info Sat Sep 15 07:13:57 2012 From: stephen at averagesecurityguy.info (Stephen Haywood) Date: Sat, 15 Sep 2012 01:13:57 -0400 Subject: [Tutor] (no subject) In-Reply-To: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> References: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> Message-ID: http://learnpythonthehardway.org/book/ http://docs.python.org/tutorial/ http://www.readwriteweb.com/hack/2011/03/python-is-an-increasingly-popu.php That should keep you busy for a while. -- Stephen Haywood Information Security Consultant CISSP, GPEN, OSCP T: @averagesecguy W: averagesecurityguy.info -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Sep 15 09:03:24 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Sep 2012 17:03:24 +1000 Subject: [Tutor] (no subject) In-Reply-To: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> References: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> Message-ID: <5054283C.40708@pearwood.info> On 15/09/12 15:09, Johny Rei wrote: > hi to all readers, i 'm a newbie and i'm interested to learn >python programming, can anybody please guide me out to learn >basic to advance python programming, be actually can anyone out >there should suggest a free book that i can read it on just to >learn from as a newbie to python programming? i can be kindly >respect and appreciate the guidance you can recommend it to >me..thnx Try this one: http://www.springer.com/mathematics/computational+science+%26+engineering/book/978-3-642-30292-3 http://codingcat.com/knjige/python/A%20Primer%20on%20Scientific%20Programming%20with%20Python.pdf -- Steven From fomcl at yahoo.com Sat Sep 15 10:21:01 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 15 Sep 2012 01:21:01 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> References: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> Message-ID: <1347697261.45550.YahooMailNeo@web110701.mail.gq1.yahoo.com> _______________________________ > From: Johny Rei >To: "tutor at python.org" >Sent: Saturday, September 15, 2012 7:09 AM >Subject: [Tutor] (no subject) > > >hi ?to all readers, i 'm a newbie and i'm interested to learn python programming, can anybody please guide me out to learn basic to advance python programming, be actually can anyone out there should suggest a free book that i can read it on just to learn from as a newbie to python programming? i can be kindly respect and appreciate the guidance you can ?recommend it to me..thnx > I like this one a LOT: http://www.qtrac.eu/py3book.html. It's really an art how well the author can explain complex things. It's about Python 3, but that hardly matters. Even though I've read just about everything of it now, I regularly pick it up again and discover new stuff. Some chapters are a bit over my head (e.g. one about metaclasses). Albert-Jan From eryksun at gmail.com Sat Sep 15 10:43:25 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Sep 2012 04:43:25 -0400 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> Message-ID: On Fri, Sep 14, 2012 at 2:33 PM, Albert-Jan Roskam wrote: >> On 14/09/12 22:16, Albert-Jan Roskam wrote: > > Is it recommended to define the geitem() function inside the __getitem__() method? > I was thinking I could also define a _getitem() private method. > > def getitem(key): > retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(int(key))) > .... I wouldn't do this since it incurs the cost of a repeated function call. A slice could involve thousands of such calls. Maybe use a boolean variable like "is_slice". Then use a for loop to build the records list (maybe only 1 item). If is_slice, return records, else return records[0]. > if isinstance(key, slice): > records = [getitem(i) for i in range(*key.indices(self.nCases))] > return records > elif hasattr(key, "__int__"): # isinstance(key, (int, float)): > if abs(key) > (self.nCases - 1): > raise IndexError > else: > key = self.nCases + key if key < 0 else key > record = getitem(key) > return record > else: > raise TypeError I agree with Steven's reasoning that it doesn't make sense to support floating point indexes. Python 2.6+ has the __index__ special method. int and long have this method. float, Decimal,and Fraction do not have it. It lets you support any user-defined class that can be used as an index. For example: >>> class MyInt(object): ... def __index__(self): ... return 5 >>> slice(MyInt(), MyInt(), MyInt()).indices(10) (5, 5, 5) operator.index() is the corresponding function. It raises TypeError if __index__ isn't supported. But watch out because you're using ctypes.c_long. It doesn't do any range checking. It just silently wraps around modulo the size of a long on your platform: >>> c_long(2**32-1), c_long(2**32), c_long(2**32+1) (c_long(-1), c_long(0), c_long(1)) Calling int(key) or index(key) is no help because it will silently return a Python long (big int). You need to do range checking on the upper bound and raise a ValueError. For example: from operator import index # calls obj.__index__() is_slice = isinstance(key, slice) if is_slice: start, stop, step = key.indices(self.nCases) # may raise TypeError else: start = index(self.nCases + key if key < 0 else key) # may raise TypeError stop = start + 1 step = 1 if stop > 2 ** (ctypes.sizeof(ctypes.c_long) * 8 - 1): raise ValueError('useful message') records = [] for i in range(start, stop, step): retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(i)) self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr) record = struct.unpack(self.structFmt, self.caseBuffer.raw) if any([retcode1, retcode2]): raise RuntimeError("Error retrieving record %d [%s, %s]" % (i, retcodes[retcode1], retcodes[retcode2])) records.append(record) if not is_slice: records = records[0] return records From dwightdhutto at gmail.com Sat Sep 15 11:17:26 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 15 Sep 2012 05:17:26 -0400 Subject: [Tutor] (no subject) In-Reply-To: <1347697261.45550.YahooMailNeo@web110701.mail.gq1.yahoo.com> References: <1347685795.63881.YahooMailNeo@web192302.mail.sg3.yahoo.com> <1347697261.45550.YahooMailNeo@web110701.mail.gq1.yahoo.com> Message-ID: How to think like a computer scientist, in python: http://greenteapress.com/thinkpython/thinkpython.html And plenty of practice: Print Lists Dicts Tuples DB Files, you parse for data yourself Basic manipulation of data. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From eryksun at gmail.com Sat Sep 15 14:37:28 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Sep 2012 08:37:28 -0400 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> Message-ID: On Sat, Sep 15, 2012 at 4:43 AM, eryksun wrote: > else: > start = index(self.nCases + key if key < 0 else key) # may > raise TypeError > stop = start + 1 > step = 1 Gmail is such a pain sometimes. I should have called index first anyway: key = index(key) # may raise TypeError start = key + self.nCases if key < 0 else key stop = start + 1 step = 1 > records = [] > for i in range(start, stop, step): > ... > records.append(record) You can boost the performance here a bit by caching the append method. This avoids a LOAD_ATTR operation on each iteration: records = [] append = records.append for i in range(start, stop, step): ... append(record) From leamhall at gmail.com Sat Sep 15 14:51:43 2012 From: leamhall at gmail.com (leam hall) Date: Sat, 15 Sep 2012 07:51:43 -0500 Subject: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE? Message-ID: Hey all, not trying to contribute to the flames of one graphical IDE over another. I'm just trying to figure out if they are worth the learning curve? I have been doing most of my work in vi and the graphical IDE I'm supposed to use for a class keeps adding crap that I have to erase, and I have to move my hands to use the GUI parts instead of just typing. Is there a point in which a GUI IDE becomes more of a help than a hindrance? Thanks! Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sat Sep 15 16:18:26 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 15 Sep 2012 07:18:26 -0700 (PDT) Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> Message-ID: <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> >On Sat, Sep 15, 2012 at 4:43 AM, eryksun wrote: > >>? ???else: >>? ? ? ???start = index(self.nCases + key if key < 0 else key)? # may >> raise TypeError >>? ? ? ???stop = start + 1 >>? ? ? ???step = 1 > > >Gmail is such a pain sometimes. I should have called index first anyway: > >? ? ? ? key = index(key)? # may raise TypeError >? ? ? ? start = key + self.nCases if key < 0 else key >? ? ? ? stop = start + 1 >? ? ? ? step = 1 > Thanks, I hadn't noticed this yet. I am refactoring some of the rest of my code and I hadn't run anything yet. My code has two methods that return record(s): an iterator (__getitem__) and a generator (readFile, which is also called by __enter__). Shouldn't I also take the possibility of a MemoryError into account when the caller does something like data[:10**8]? It may no longer fit into memory, esp. when the dataset is also wide. > >>? ???records = [] >>? ???for i in range(start, stop, step): >>? ? ? ???... >>? ? ? ???records.append(record) > > >You can boost the performance here a bit by caching the append method. >This avoids a LOAD_ATTR operation on each iteration: > >? ? records = [] >? ? append = records.append >? ? for i in range(start, stop, step): >? ? ? ? ... >? ? ? ? append(record) I knew that trick from http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... but I didn't know about LOAD_ATTR. Is a list comprehension still faster than this? Does it also mean that e.g. "from ctypes import *" (--> c_long()) is faster than "import ctypes" (--> ctypes.c_long()). I am now putting as much as possible in __init__. I don't like the first way of importing at all. From dhulse94 at gmail.com Sat Sep 15 17:21:55 2012 From: dhulse94 at gmail.com (Daniel Hulse) Date: Sat, 15 Sep 2012 11:21:55 -0400 Subject: [Tutor] Python help Message-ID: <94F4F020-61BB-47AC-A6FA-A447D0002628@gmail.com> Hi. I am trying to solve a problem and I'm stuck. The problem is something like as x goes up by 1, y goes up by the previous value times 2. I have no idea where to start. So lets say x = 10 and y=5, when x=11, why would be equal to 10. From joel.goldstick at gmail.com Sat Sep 15 17:57:26 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Sep 2012 11:57:26 -0400 Subject: [Tutor] Python help In-Reply-To: <94F4F020-61BB-47AC-A6FA-A447D0002628@gmail.com> References: <94F4F020-61BB-47AC-A6FA-A447D0002628@gmail.com> Message-ID: On Sat, Sep 15, 2012 at 11:21 AM, Daniel Hulse wrote: > Hi. I am trying to solve a problem and I'm stuck. The problem is something like as x goes up by 1, y goes up by the previous value times 2. I have no idea where to start. So lets say x = 10 and y=5, when x=11, why would be equal to 10. Your question is really one of simple algebra This looks like homework. You should explain your problem more completely, and show any code you have tried to solve your problem -- Joel Goldstick From modulok at gmail.com Sat Sep 15 20:32:10 2012 From: modulok at gmail.com (Modulok) Date: Sat, 15 Sep 2012 12:32:10 -0600 Subject: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE? In-Reply-To: References: Message-ID: > Hey all, not trying to contribute to the flames of one graphical IDE over > another. I'm just trying to figure out if they are worth the learning > curve? I have been doing most of my work in vi and the graphical IDE I'm > supposed to use for a class keeps adding crap that I have to erase, and I > have to move my hands to use the GUI parts instead of just typing. > > Is there a point in which a GUI IDE becomes more of a help than a > hindrance? > > Thanks! > > Leam Leam, It's really a personal taste. I can't speak for others, but this is my basic setup: I use a highly customised graphical text editor (jEdit) with several plugins specific to what I'm doing. I guess it kind of equates to a lightweight IDE. I combine this with an ssh connection to a FreeBSD box for all the wonderful *nix command line tools, scripts, debuggers, etc that are out there. I like the idea of an IDE, but haven't met one I really care for. I much prefer a GUI editor over a purely console based one. That is, I like the ability to use a mouse to aid in quickly moving text around. I also like the sub-pixel anti-aliased fonts that you don't always get on a console. (Of course, this depends on the console.) You can do most things with command line editors, (some even support using a mouse) but I never found it to be as fast. Again, it's personal and I'm probably getting off the subject. This is more of a console vs. GUI debate. I short, I'd say use whatever you're comfortable with. After that, use what your friends/co-workers use. The popup auto-complete for class names or variable names in IDE's is nice and can often save you from having to look something up, but it isn't critical. Console tools like ipython can make up for some of that, but even so that's not something I generally write code in. Perhaps others have more insight. -Modulok- From eryksun at gmail.com Sat Sep 15 21:21:13 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Sep 2012 15:21:13 -0400 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> Message-ID: On Sat, Sep 15, 2012 at 10:18 AM, Albert-Jan Roskam wrote: > Thanks, I hadn't noticed this yet. I am refactoring some of the rest of my code > and I hadn't run anything yet. My code has two methods that return record(s): > an iterator (__getitem__) and a generator (readFile, which is also called by > __enter__). Shouldn't I also take the possibility of a MemoryError into > account when the caller does something like data[:10**8]? It may no longer fit > into memory, esp. when the dataset is also wide. The issue with c_long isn't a problem for a slice since key.indices(self.nCases) limits the upper bound. For the individual index you had it right the first time by raising IndexError before it even gets to the c_long conversion. I'm sorry for wasting your time on a non-problem. However, your test there is a bit off. A negative index can be -nCases since counting from the end starts at -1. If you first do the ternary check to add the offset to a negative index, afterward you can raise an IndexError if "not 0 <= value < nCases". As to MemoryError, dealing with gigabytes of data in main memory is not a problem I've come up against in practice. You might still want a reasonable upper bound for slices. Often when the process runs out of memory it won't even see a MemoryError. The OS simply kills it. On the other hand, while bugs like a c_long wrapping around need to be caught to prevent silent corruption of data, there's nothing at all silent about crashing the process. It's up to you how much you want to micromanage the situation. You might want to check out psutil as a cross-platform way to monitor the process memory usage: http://code.google.com/p/psutil If you're also supporting the iterator protocol with the __iter__ method, then I think a helper _items(start, stop, step) generator function would be a good idea. Here's an updated example (not tested however; it's just a suggestion): import operator def _items(self, start=0, stop=None, step=1): if stop is None: stop = self.nCases for i in range(start, stop, step): retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(i)) self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr) record = struct.unpack(self.structFmt, self.caseBuffer.raw) if any([retcode1, retcode2]): raise RuntimeError("Error retrieving record %d [%s, %s]" % (i, retcodes[retcode1], retcodes[retcode2])) yield record def __iter__(self): return self._items() def __getitem__(self, key): is_slice = isinstance(key, slice) if is_slice: start, stop, step = key.indices(self.nCases) else: key = operator.index(key) start = key + self.nCases if key < 0 else key if not 0 <= start < self.nCases: raise IndexError stop = start + 1 step = 1 records = self._items(start, stop, step) if is_slice: return list(records) return next(records) > but I didn't know about LOAD_ATTR. That's the bytecode operation to fetch an attribute. Whether or not bypassing it will provide a significant speedup depends on what else you're doing in the loop. If the the single LOAD_ATTR is only a small fraction of the total processing time, or you're not looping thousands of times, then this little change is insignificant. > Is a list comprehension still faster than this? I think list comprehensions or generator expressions are best if the evaluated expression isn't too complex and uses built-in types and functions. I won't typically write a function just to use a list comprehension for a single statement. Compared to a regular for loop (especially if append is cached in a fast local), the function call overhead makes it a wash or worse, even given the comprehension's efficiency at building the list. If the main work of the loop is the most significant factor, then the choice of for loop vs list comprehension doesn't matter much with regard to performance, but I still think it's simpler to just use a regular for loop. You can also write a generator function if you need to reuse an iteration in multiple statements. > Does it also mean that e.g. "from ctypes import *" (--> c_long()) is > faster than "import ctypes" (--> ctypes.c_long()). I am now putting as much as > possible in __init__. I don't like the first way of importing at all. It's not a good idea to pollute your namespace with "import *" statements. In a function, you can cache an attribute locally if doing so will provide a significant speedup. Or you can use a default argument like this: def f(x, c_long=ctypes.c_long): return c_long(x) From acolle00 at g.uafortsmith.edu Sat Sep 15 23:28:47 2012 From: acolle00 at g.uafortsmith.edu (Amanda Colley) Date: Sat, 15 Sep 2012 16:28:47 -0500 Subject: [Tutor] Cube root Message-ID: Ok, I have to get input from a user ('enter a number') and then get the cube root of that number. I am having trouble with the code to get the cube root. If anyone can help me solve this I would greatly appreciate it. ('enter a number') n=number ??? cube root?? -- Amanda Colley -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Sep 15 23:36:32 2012 From: d at davea.name (Dave Angel) Date: Sat, 15 Sep 2012 17:36:32 -0400 Subject: [Tutor] Cube root In-Reply-To: References: Message-ID: <5054F4E0.4080105@davea.name> On 09/15/2012 05:28 PM, Amanda Colley wrote: > Ok, I have to get input from a user ('enter a number') and then get the > cube root of that number. I am having trouble with the code to get the > cube root. If anyone can help me solve this I would greatly appreciate it. > ('enter a number') > n=number > ??? cube root?? > > The operator to raise a number to a particular power is **, and it's not constrained to integer powers. So 5*2 is 25. See what's next? -- DaveA From joel.goldstick at gmail.com Sun Sep 16 00:24:21 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Sep 2012 18:24:21 -0400 Subject: [Tutor] Cube root In-Reply-To: <5054F4E0.4080105@davea.name> References: <5054F4E0.4080105@davea.name> Message-ID: On Sat, Sep 15, 2012 at 5:36 PM, Dave Angel wrote: > On 09/15/2012 05:28 PM, Amanda Colley wrote: >> Ok, I have to get input from a user ('enter a number') and then get the >> cube root of that number. I am having trouble with the code to get the >> cube root. If anyone can help me solve this I would greatly appreciate it. >> ('enter a number') >> n=number >> ??? cube root?? >> >> > > The operator to raise a number to a particular power is **, and it's not > constrained to integer powers. So 5*2 is 25. See what's next? > This is a great place to ask questions. But don't forget google (or bing) try googling python cube root see how you do and come back with your code! -- Joel Goldstick From etanes.rm at gmail.com Sun Sep 16 00:50:46 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sat, 15 Sep 2012 15:50:46 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? Message-ID: Hello again python tutor list. I have what I see as a somewhat complicated problem which I have no idea where to begin. I'm hoping you fine folks can help me. I'm trying to generate a list of every possible 16 character string containing only 2-7 and a-z lowercase. I've seen some examples using regex to define which characters I want to use but not a way to generate the complete list of all possibilities. I'm not looking for a handout- just a point in the right direction. Any information would be awesome, thanks. Right now I've got something like: import random >>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in range(16)) Which only prints 1 number, obviously. or possibly something like this: def genKey(): hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") alnum_hash = re.sub(r'[^a-z2-7]', "", hash) return alnum_hash[:16] Keeping in mind that although I understand this code, I did not write it, I got it from stackoverflow. Again any help would be great. Feel free to ask if you must know exactly what I'm trying to do. I'm running Ubuntu 12.04 and python 2.7 Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Sep 16 01:12:04 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Sep 2012 19:12:04 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: On Sat, Sep 15, 2012 at 6:50 PM, Scurvy Scott wrote: > Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. I've seen some examples using regex > to define which characters I want to use but not a way to generate the > complete list of all possibilities. I'm not looking for a handout- just a > point in the right direction. > > Any information would be awesome, thanks. > > Right now I've got something like: > > import random >>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in >>>> range(16)) > > > Which only prints 1 number, obviously. > > or possibly something like this: > > > def genKey(): > > hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") > > alnum_hash = re.sub(r'[^a-z2-7]', "", hash) > > return alnum_hash[:16] > > > Keeping in mind that although I understand this code, I did not write it, I > got it from stackoverflow. > > Again any help would be great. Feel free to ask if you must know exactly > what I'm trying to do. > check this out: http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python -- Joel Goldstick From __peter__ at web.de Sun Sep 16 01:30:01 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Sep 2012 01:30:01 +0200 Subject: [Tutor] All possible 16 character alphanumeric strings? References: Message-ID: Scurvy Scott wrote: > Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. I've seen some examples using regex > to define which characters I want to use but not a way to generate the > complete list of all possibilities. I'm not looking for a handout- just a > point in the right direction. > > Any information would be awesome, thanks. > > Right now I've got something like: > > import random >>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in >>>> range(16)) > > Which only prints 1 number, obviously. > > or possibly something like this: > > > def genKey(): > hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") > alnum_hash = re.sub(r'[^a-z2-7]', "", hash) > return alnum_hash[:16] > > > Keeping in mind that although I understand this code, I did not write it, > I got it from stackoverflow. > > Again any help would be great. Feel free to ask if you must know exactly > what I'm trying to do. > > I'm running Ubuntu 12.04 and python 2.7 > > Scott from itertools import product from string import ascii_lowercase chars = ascii_lowercase + "234567" assert len(chars) == 32 for item in product(*[chars]*16): print "".join(item) Now, assuming this script will print 10 million 16-character strings per second it should terminate in... >>> 32**16 / (10000000*60*60*24*365) 3833478626L about four billion years. From d at davea.name Sun Sep 16 02:01:32 2012 From: d at davea.name (Dave Angel) Date: Sat, 15 Sep 2012 20:01:32 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: <505516DC.20500@davea.name> On 09/15/2012 06:50 PM, Scurvy Scott wrote: > Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. That list would fill all the PC's on the planet a few billions times. The number of items in the list has 25 digits in it. print 32**16 > I've seen some examples using regex Not likely to be the least bit useful. > to define which characters I want to use but not a way to generate the > complete list of all possibilities. I'm not looking for a handout- just a > point in the right direction. > > Any information would be awesome, thanks. > > Right now I've got something like: > > import random >>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in range(16)) You said you wanted a list with every possible string, not a list of random strings. > Which only prints 1 number, obviously. > > or possibly something like this: > > > def genKey(): > hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") > alnum_hash = re.sub(r'[^a-z2-7]', "", hash) > return alnum_hash[:16] still random, does not apply to the problem as stated. > > Keeping in mind that although I understand this code, I did not write it, I > got it from stackoverflow. > > Again any help would be great. Feel free to ask if you must know exactly > what I'm trying to do. > > I'm running Ubuntu 12.04 and python 2.7 > > Scott > If you wanted to use a smaller string, or a smaller set of characters, so that it might be actually possible to list ALL the possibilities, then start with Peter Otten's code using itertools.product(). import itertools chars = "ab5" result = ["".join(item) for item in product(*[chars]*4)] print len(result) This one only has 81 items in it ( 3**4 ) so it's quite workable. if you want to see the first seven items: for item in result[:7]: print item aaaa aaab aaa5 aaba aabb aab5 aa5a -- DaveA From steve at pearwood.info Sun Sep 16 03:33:23 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 11:33:23 +1000 Subject: [Tutor] Cube root In-Reply-To: References: Message-ID: <50552C63.1020505@pearwood.info> On 16/09/12 07:28, Amanda Colley wrote: > Ok, I have to get input from a user ('enter a number') and then get the > cube root of that number. I am having trouble with the code to get the > cube root. If anyone can help me solve this I would greatly appreciate it. > ('enter a number') > n=number > ??? cube root?? The definition of "cube root of x" is "x to the power of one third". To calculate cube root, you need to get the number from the user and raise it to the power of one third. This is actually a subtle problem: * input you get from the user is a string, you need to turn it into a number * you have a choice between using the ** operator or the pow() function for raising x to a power * the obvious solution: x**1/3 is wrong. Can you see why? (Hint: there are two operators there, power and divide. What order do they get executed?) * even more subtle: there is a difference in how Python does division depending on the version you use. Calculating one third correctly is slightly trickier than it seems. I hope this is enough hints for you to solve the problem. If not, show us the code you have and ask for more help. -- Steven From akleider at sonic.net Sun Sep 16 03:37:09 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 18:37:09 -0700 Subject: [Tutor] Cube root In-Reply-To: References: <5054F4E0.4080105@davea.name> Message-ID: <296abb7b0899896ca7c2304769706e58.squirrel@webmail.sonic.net> > On Sat, Sep 15, 2012 at 5:36 PM, Dave Angel wrote: >> On 09/15/2012 05:28 PM, Amanda Colley wrote: >>> Ok, I have to get input from a user ('enter a number') and then get >>> the >>> cube root of that number. I am having trouble with the code to get the >>> cube root. If anyone can help me solve this I would greatly appreciate >>> it. >>> ('enter a number') >>> n=number >>> ??? cube root?? >>> >>> >> >> The operator to raise a number to a particular power is **, and it's not >> constrained to integer powers. So 5*2 is 25. See what's next? >> > This is a great place to ask questions. But don't forget google (or bing) > > try googling python cube root > > see how you do and come back with your code! > -- > Joel Goldstick Why does: """ >>> import math >>> 9**(1/3.0) 2.080083823051904 >>> 9.0**(1.0/3.0) 2.080083823051904 >>> """ not seem to work? > From akleider at sonic.net Sun Sep 16 03:40:35 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 18:40:35 -0700 Subject: [Tutor] Cube root In-Reply-To: References: <5054F4E0.4080105@davea.name> Message-ID: <7cb4c8c3cd8ca393c2e0ae6bc163da19.squirrel@webmail.sonic.net> > On Sat, Sep 15, 2012 at 5:36 PM, Dave Angel wrote: >> On 09/15/2012 05:28 PM, Amanda Colley wrote: >>> Ok, I have to get input from a user ('enter a number') and then get >>> the >>> cube root of that number. I am having trouble with the code to get the >>> cube root. If anyone can help me solve this I would greatly appreciate >>> it. >>> ('enter a number') >>> n=number >>> ??? cube root?? >>> >>> >> >> The operator to raise a number to a particular power is **, and it's not >> constrained to integer powers. So 5*2 is 25. See what's next? >> > This is a great place to ask questions. But don't forget google (or bing) > > try googling python cube root > > see how you do and come back with your code! > -- > Joel Goldstick OOPS!! Should have been: >>> 27.0**(1.0/3.0) 3.0 >>> Which works better than expected! From etanes.rm at gmail.com Sun Sep 16 04:03:18 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sat, 15 Sep 2012 19:03:18 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <505516DC.20500@davea.name> References: <505516DC.20500@davea.name> Message-ID: > > That list would fill all the PC's on the planet a few billions times. > The number of items in the list has 25 digits in it. print 32**16 > > I actually should've specified that the list I'm trying to create would not start at say "0000000000000001". I'm attempting to generate all possible .onion addressess which look like " kpvz7ki2v5agwt35.onion" for instance. The TOR network generates these numbers with this method: "If you decide to run a hidden service Tor generates an RSA-1024keypair. The .onion name is computed as follows: first the SHA1 hash of the DER-encoded ASN.1 public key is calculated. Afterwards the first half of the hash is encoded to Base32 and the suffix ".onion" is added. Therefore .onion names can only contain the digits 2-7 and the letters a-z and are exactly 16 characters long." -from the Tor Hidden Services DOC page. I'm not sure if that changes anything as far as the impossible size of my dataset. Again, any input is useful. Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Sun Sep 16 04:22:52 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 19:22:52 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: > Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. I've seen some examples using regex > to define which characters I want to use but not a way to generate the > complete list of all possibilities. I'm not looking for a handout- just a > point in the right direction. > > Any information would be awesome, thanks. > > Right now I've got something like: > > import random >>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in >>>> range(16)) > > Which only prints 1 number, obviously. > > or possibly something like this: > > > def genKey(): > hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") > alnum_hash = re.sub(r'[^a-z2-7]', "", hash) > return alnum_hash[:16] > > > Keeping in mind that although I understand this code, I did not write it, > I > got it from stackoverflow. > > Again any help would be great. Feel free to ask if you must know exactly > what I'm trying to do. > > I'm running Ubuntu 12.04 and python 2.7 > > Scott This seems to work: #!/usr/bin/env python # file : every.py print 'Running "every.py"' possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word # There may come a time you won't want this line. else: for c in possible: new_word = word + c add_word(new_word) add_word("") # print word_list From steve at pearwood.info Sun Sep 16 04:48:01 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 12:48:01 +1000 Subject: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE? In-Reply-To: References: Message-ID: <50553DE1.7050508@pearwood.info> On 15/09/12 22:51, leam hall wrote: > Hey all, not trying to contribute to the flames of one graphical IDE over > another. I'm just trying to figure out if they are worth the learning > curve? I have been doing most of my work in vi and the graphical IDE I'm > supposed to use for a class keeps adding crap that I have to erase, and I > have to move my hands to use the GUI parts instead of just typing. > > Is there a point in which a GUI IDE becomes more of a help than a hindrance? Certainly. But where that point is will depend on personal taste and what other tools you have. If your only tools are Notepad and command.com on Windows, then an IDE will seem like a *really excellent idea*. On the other hand, if you have a rich set of powerful editors and command line tools, then you have a full Development Environment right there, and adding Integrated doesn't really add much. It might even subtract. A single Integrated DE can only have a single user- interface, which may not suit your tastes and ways of working. Having a rich set of independently configurable tools makes it easier to find your own personal sweet spot. So don't knock the power of an Unintegrated Development Environment. Or rather, a very loosely integrated one, since the integration is done via the shell. http://blog.sanctum.geek.nz/series/unix-as-ide/ There are many IDEs for Python, and I suppose some people must like them: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://wiki.python.org/moin/PythonEditors Back in ancient days when I was programming on an Apple Macintosh, I found IDEs to be *very* useful. To start with, the original Apple Macs had no command line and weren't multitasking, so everything was a GUI and if you wanted to run an compiler and an editor at the same time, you needed to have an integrated compiler/editor. I used Lightspeed Pascal, later known as THINK Pascal, and it was excellent. It was also before the term IDE was invented, so I never thought of myself as using an IDE, I thought all compilers were the same. I was in for rather a shock when I learned that they weren't. The editor was fast and responsive, and automatically formatted my code as I typed. It could pick up syntax errors automatically. There was no interactive shell, like Python has, but Pascal doesn't really watch that paradigm very well, and you could run your application live in the IDE and set break-points to inspect variables using a powerful integrated debugger. In my opinion, a good GUI integrated debugger makes or breaks an IDE: I don't use debuggers enough to learn all the obscure commands for driving it from the keyboard, so for me the choices are: (1) a good GUI debugger, or (2) print statements in the code. Currently I use (2). THINK Pascal didn't have anything like "Intellisense" or code refactoring, but this was back in 1990 so the technology wasn't really up to it. Another IDE I used, also back on the Macintosh, was Hypercard, which was a combined GUI-builder app and runtime environment. The IDE part was even more primative, but the model of a GUI builder where you can run code is *fantastic*, and I've never seen anything that comes close since. I recently decide to start looking at some Python IDE's to see what I'm missing out on. To start with, forget IDLE that comes with Python. In my opinion, it's worse than useless. But apparently, some people like it. Heaven knows why. I also looked at Spyder. What I found was that it is feature-rich, but on my laptop the editor was not *quite* responsive enough. I'm not a touch-typist, but if I were, I would probably notice the lag. But absolutely deadly in my opinion is that Spyder tries to flag syntax errors, programming bugs, and style issues as you type. That's not a bad thing in itself, but there is a second or two lag between me typing something and the editor flagging lines with little coloured flags and what-not. As a consequence, as I type I'm constantly being distracted by bling appearing and disappeared all over the page (not just on the line I'm typing). In my opinion, if as-you-type code analysis isn't instantaneous, it is worse than useless. Some feedback needs to be immediate, within a tenth of a second, or else must be on-demand only. -- Steven From etanes.rm at gmail.com Sun Sep 16 04:58:42 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sat, 15 Sep 2012 19:58:42 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> Message-ID: possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 print 'Running "every.py"' word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word else: for c in possible: new_word = word + c add_word(new_word) The only problem with this code is that it actually takes a word as its input and just checks that it is == word length. If not it just appends the string possible to the variable word that was called in the function add_word. I need to be able to generate every possible combination of the characters in the variable possible, ideally coming up with a string that resembles the TOR hidden network strings that look like this: "kpvz7ki2v5agwt35.onion" Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Sun Sep 16 05:06:35 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 20:06:35 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> Message-ID: <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> #!/usr/bin/env python # file : every.py print 'Running "every.py"' possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word # There may come a time you won't want this line. else: for c in possible: new_word = word + c add_word(new_word) add_word("") # print word_list > That solution is really nice, thanks, I doubt I would've come up with > something as nice. What I'll do is have that write to a file then use > regex > to strip out any characters like whitespace or commas from the list and > that should give me a good solid list, no? > > I'm using this to write a program I'm calling TORdialer with the goal of > attempting to basically ping all possible TOR hidden service pages with > the > goal of having an absolutely complete list of all TOR hidden services on > the net right now. Unfortunately it will probably be a lot of fucked up CP > sites and drug related marketplaces. I'm mostly interested in the sites > that aren't publicized (ie- government related sites, etc). > Thanks for your help and I'll try to keep everyone posted. > There won't be any whitespace or commas in any of the derived output. For your purposes, you might want to make this into a generator although that would be getting too sophisticated for me to help you. Since in its present form the algorithm is a recursive one, I'm guessing it'll run out of memory long before it comes to completion although I haven't let it run for more than a few seconds, just enough to see that it seemed to be doing what I wanted. >From what I know about computer science, I believe that most if not all recursive algorithms can be re-written to be non recursive. If you could do that, you could then make a generator and presumably make use of it without overwhelming resources. I look forward to hearing what those with more expertise might have to say about that. From akleider at sonic.net Sun Sep 16 05:13:32 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 20:13:32 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> Message-ID: > possible = "234567abcdefghijklmnopqrstuvwxyz" > word_length = 16 > print 'Running "every.py"' > word_list = [] > def add_word(word): > if len(word)==word_length: > word_list.append(word) > print word > else: > for c in possible: > new_word = word + c > add_word(new_word) > > > The only problem with this code is that it actually takes a word as its > input and just checks that it is == word length. If not it just appends > the > string possible to the variable word that was called in the function > add_word. > > I need to be able to generate every possible combination of the characters > in the variable possible, ideally coming up with a string that resembles > the TOR hidden network strings that look like this: > "kpvz7ki2v5agwt35.onion" > > > Scott Actually it doesn't even do that. It only prints "running 'every.py'"! You forgot the line that does all the work: """ add_word("") """ I'm attaching the whole file so you don't miss the important bit. Run it and see what happens, but be ready to CNTL-C (I'm assuming you are running Linux, I think it'll be the same on Mac, all bets are off regarding M$ Windoz:-) Alex -------------- next part -------------- A non-text attachment was scrubbed... Name: every.py Type: text/x-python Size: 435 bytes Desc: not available URL: From akleider at sonic.net Sun Sep 16 04:29:17 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 19:29:17 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> >> Hello again python tutor list. >> I have what I see as a somewhat complicated problem which I have no idea >> where to begin. I'm hoping you fine folks can help me. >> >> I'm trying to generate a list of every possible 16 character string >> containing only 2-7 and a-z lowercase. I've seen some examples using >> regex >> to define which characters I want to use but not a way to generate the >> complete list of all possibilities. I'm not looking for a handout- just >> a >> point in the right direction. >> >> Any information would be awesome, thanks. >> >> Right now I've got something like: >> >> import random >>>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in >>>>> range(16)) >> >> Which only prints 1 number, obviously. >> >> or possibly something like this: >> >> >> def genKey(): >> hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") >> alnum_hash = re.sub(r'[^a-z2-7]', "", hash) >> return alnum_hash[:16] >> >> >> Keeping in mind that although I understand this code, I did not write >> it, >> I >> got it from stackoverflow. >> >> Again any help would be great. Feel free to ask if you must know exactly >> what I'm trying to do. >> >> I'm running Ubuntu 12.04 and python 2.7 >> >> Scott > > This seems to work: > #!/usr/bin/env python > > # file : every.py > print 'Running "every.py"' > > possible = "234567abcdefghijklmnopqrstuvwxyz" > word_length = 16 > > word_list = [] > def add_word(word): > if len(word)==word_length: > word_list.append(word) > print word # There may come a time you won't want this line. > else: > for c in possible: > new_word = word + c > add_word(new_word) > > add_word("") > > # print word_list > Addendum: As others have pointed out, you might run out of patience, time, memory, or what ever ...long before completion. one solution would be to make "word_length" &/or "possible" shorter. It was fun trying to knock this one out. From steve at pearwood.info Sun Sep 16 05:20:11 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 13:20:11 +1000 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> Message-ID: <5055456B.3090307@pearwood.info> On 16/09/12 13:06, akleider at sonic.net wrote: > > #!/usr/bin/env python > > # file : every.py > print 'Running "every.py"' > > possible = "234567abcdefghijklmnopqrstuvwxyz" > word_length = 16 > > word_list = [] > def add_word(word): > if len(word)==word_length: > word_list.append(word) > print word # There may come a time you won't want this line. > else: > for c in possible: > new_word = word + c > add_word(new_word) > > add_word("") > > # print word_list [...] > There won't be any whitespace or commas in any of the derived output. > For your purposes, you might want to make this into a generator although > that would be getting too sophisticated for me to help you. > Since in its present form the algorithm is a recursive one, I'm guessing > it'll run out of memory long before it comes to completion although I > haven't let it run for more than a few seconds, There are 32**16 = 1208925819614629174706176 16-character strings using digits 2-7 and lowercase a-z. To store a full list of them all will take at least 74953400816107 terrabytes of memory. Given that even high-end IBM Blade servers don't support even a single terrabyte of RAM, I think that your guess about running out of memory is pretty safe... -- Steven From steve at pearwood.info Sun Sep 16 05:21:15 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 13:21:15 +1000 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: <505545AB.7010103@pearwood.info> On 16/09/12 08:50, Scurvy Scott wrote: > Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. [...] > I'm not looking for a handout- just a point in the right direction. Look at itertools.product for a way to generate such strings one at a time, without needing to store them all in a list. -- Steven From d at davea.name Sun Sep 16 05:27:53 2012 From: d at davea.name (Dave Angel) Date: Sat, 15 Sep 2012 23:27:53 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: <505516DC.20500@davea.name> Message-ID: <50554739.2000909@davea.name> On 09/15/2012 10:03 PM, Scurvy Scott wrote: >> >> That list would fill all the PC's on the planet a few billions times. >> The number of items in the list has 25 digits in it. print 32**16 >> >> I actually should've specified that the list I'm trying to create would > not start at say "0000000000000001". Of course not. Your defined set of characters didn't have a zero in it. > I'm attempting to generate all possible .onion addressess which look like " > kpvz7ki2v5agwt35.onion" for instance. > "Look like" is pretty vague. To me, 2222222222222222.onion certainly looks like the one you said. And if it's missing, then you don't have them all. > > The TOR network generates these numbers with this method: > "If you decide to run a hidden service Tor generates an > RSA-1024keypair. The .onion name is > computed as follows: first the > SHA1 hash of the > DER-encoded > ASN.1 public > key is calculated. Afterwards the first half of the hash is encoded to > Base32 and the suffix ".onion" is > added. Therefore .onion names can only contain the digits 2-7 and the > letters a-z and are exactly 16 characters long." > -from the Tor Hidden Services DOC page. > > I'm not sure if that changes anything as far as the impossible size of my > dataset. > I can't see any reason why it changes anything. The world doesn't have enough disk space to store *every* address. If you need to calculate all of them, you don't have enough time. You need to rethink whatever your real problem is. For example, if you were really trying to crack a safe with 32 numbers on the dial and 16 settings to open it, perhaps you should forget all of it and get some nitro. Or a stethoscope. Or bribe somebody who knows the combination. If you have to try all of the combinations systematically, you'll never get there. > Again, any input is useful. > > Scott > -- DaveA From akleider at sonic.net Sun Sep 16 05:48:07 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 20:48:07 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <50554739.2000909@davea.name> References: <505516DC.20500@davea.name> <50554739.2000909@davea.name> Message-ID: <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> > On 09/15/2012 10:03 PM, Scurvy Scott wrote: >>> >>> That list would fill all the PC's on the planet a few billions times. >>> The number of items in the list has 25 digits in it. print 32**16 >>> >> > > I can't see any reason why it changes anything. The world doesn't have > enough disk space to store *every* address. If you need to calculate > all of them, you don't have enough time. > > You need to rethink whatever your real problem is. For example, if you > were really trying to crack a safe with 32 numbers on the dial and 16 > settings to open it, perhaps you should forget all of it and get some > nitro. Or a stethoscope. Or bribe somebody who knows the combination. > If you have to try all of the combinations systematically, you'll never > get there. We can probably all agree that there aren't enough resources (time, memory, etc) to solve the problem, but that doesn't make the problem uninteresting. What interests me, and I acknowledge that this is more a question for a computer science forum than a python one, is: can this be done in a non recursive way so the limiting factor will be time, not memory? I couldn't think of a way. From steve at pearwood.info Sun Sep 16 05:52:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 13:52:06 +1000 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> Message-ID: <50554CE6.1030606@pearwood.info> Akleider, you didn't include attribution for the person you are quoting, which is a bit rude and also means I can't be sure who it was. From context, I *think* it is the original poster Scott: On 16/09/12 13:06, akleider at sonic.net wrote: >> I'm using this to write a program I'm calling TORdialer with the goal of >> attempting to basically ping all possible TOR hidden service pages with >> the goal of having an absolutely complete list of all TOR hidden services >> on the net right now. Did you really think that when a group of really smart security and network experts sit down to design a protocol for hiding services from discovery, that it would actually be vulnerable to a programming beginner who just lists out all the possible sites and pings them? And the TOR designers didn't think of that? I'm sorry if this comes across as condescending, but it's kinda cute that you thought this was viable. TOR is designed to be resistant to discovery from people with the full resources of the United States and Chinese governments. Believe me, they already considered the "brute force attack" where you list out every possible address. If every person in the world runs their own TOR hidden network, then the chances of you pinging *even one* by accident is about 1 in 172703688516375. If your TORdialer program could ping a million addresses per second, you would need to run it non-stop for over five years just to find *one* address. "An absolutely complete list"... oh my stars and garters. (Remember those maths classes on permutations and combinations that you probably thought were totally pointless? *This* is why they're important.) -- Steven From d at davea.name Sun Sep 16 06:05:35 2012 From: d at davea.name (Dave Angel) Date: Sun, 16 Sep 2012 00:05:35 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> References: <505516DC.20500@davea.name> <50554739.2000909@davea.name> <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> Message-ID: <5055500F.8040800@davea.name> On 09/15/2012 11:48 PM, akleider at sonic.net wrote: >> On 09/15/2012 10:03 PM, Scurvy Scott wrote: >>>> That list would fill all the PC's on the planet a few billions times. >>>> The number of items in the list has 25 digits in it. print 32**16 >>>> >> I can't see any reason why it changes anything. The world doesn't have >> enough disk space to store *every* address. If you need to calculate >> all of them, you don't have enough time. >> >> You need to rethink whatever your real problem is. For example, if you >> were really trying to crack a safe with 32 numbers on the dial and 16 >> settings to open it, perhaps you should forget all of it and get some >> nitro. Or a stethoscope. Or bribe somebody who knows the combination. >> If you have to try all of the combinations systematically, you'll never >> get there. > We can probably all agree that there aren't enough resources (time, > memory, etc) to solve the problem, but that doesn't make the problem > uninteresting. > What interests me, and I acknowledge that this is more a question for a > computer science forum than a python one, is: can this be done in a non > recursive way so the limiting factor will be time, not memory? I couldn't > think of a way. > it can certainly be done non-recursively, as I showed with a relatively simple list comprehension, borrowing the idea from Peter Otten. import itertools chars = "ab5" result = ["".join(item) for item in itertools.product(*[chars]*4)] Non-recursive doesn't mean "uses little memory," however. Since the problem is to build a list, it will use lots of memory. If the problem were instead to make a generator that yields all possible strings, import itertools chars = "ab5" result_generator = ("".join(item) for item in itertools. product(*[chars]*4)) Now, you could write a loop that examined all these items (pretending you had unlimited time), something like: for item in result_generator: if test_safe(item): print item, "cracked the algorithm" obviously, you'd need a longer chars, and to change *4 to *16, if you actually wanted to do the original dataset. And if you don't want to use itertools, you can trivially do it in a loop, since you're basically just counting, base 32. -- DaveA From steve at pearwood.info Sun Sep 16 06:10:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 14:10:29 +1000 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> References: <505516DC.20500@davea.name> <50554739.2000909@davea.name> <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> Message-ID: <50555135.6000500@pearwood.info> On 16/09/12 13:48, akleider at sonic.net wrote: > What interests me, and I acknowledge that this is more a question for a > computer science forum than a python one, is: can this be done in a non > recursive way so the limiting factor will be time, not memory? I couldn't > think of a way. Of course. That's what iterators and generators are for: to generate data lazily, as required, rather than all up front. Since this project isn't homework and I have no fear that I'm going to teach the US and Chinese governments how to break the TOR network's security module, here's how you could do it given enough time. py> import string, itertools py> chars = '234567' + string.lowercase py> chars '234567abcdefghijklmnopqrstuvwxyz' py> it = itertools.product(*([chars]*16)) py> next(it) ('2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2') py> for i in range(5): # get the next five address ... print(''.join(next(it)) + '.onion') ... 2222222222222223.onion 2222222222222224.onion 2222222222222225.onion 2222222222222226.onion 2222222222222227.onion py> # grab 10 thousand addresses ... addresses = list(itertools.islice(it, 10000)) py> [''.join(a)+'.onion' for a in addresses[-3:]] # look at the last three ['2222222222222dsn.onion', '2222222222222dso.onion', '2222222222222dsp.onion'] py> # skip ahead a million addresses, just throwing the values away ... for i in range(1000000): ... _ = next(it) ... py> ''.join(next(it)) '222222222222yueq' Like the speedo on your car, each digit takes longer and longer to roll over as you move towards the left. It took < ten thousand iterations to change the third digit from the right. It took < a million iterations to change the fourth digit. To roll over the left-most 2 into a 3 will take 32**15 iterations, or 37778931862957161709568. -- Steven From akleider at sonic.net Sun Sep 16 06:11:44 2012 From: akleider at sonic.net (akleider at sonic.net) Date: Sat, 15 Sep 2012 21:11:44 -0700 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <50554CE6.1030606@pearwood.info> References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> <50554CE6.1030606@pearwood.info> Message-ID: <20a10f9dc69c59763569c0cee44947b4.squirrel@webmail.sonic.net> > Akleider, you didn't include attribution for the person you are quoting, > which is a bit rude and also means I can't be sure who it was. From > context, I *think* it is the original poster Scott: > > On 16/09/12 13:06, akleider at sonic.net wrote: >>> I'm using this to write a program I'm calling TORdialer with the goal >>> of >>> attempting to basically ping all possible TOR hidden service pages with >>> the goal of having an absolutely complete list of all TOR hidden >>> services >>> on the net right now. > > Did you really think that when a group of really smart security and > network > experts sit down to design a protocol for hiding services from discovery, > that it would actually be vulnerable to a programming beginner who just > lists out all the possible sites and pings them? And the TOR designers > didn't think of that? > > I'm sorry if this comes across as condescending, but it's kinda cute that > you thought this was viable. TOR is designed to be resistant to discovery > from people with the full resources of the United States and Chinese > governments. Believe me, they already considered the "brute force attack" > where you list out every possible address. > > If every person in the world runs their own TOR hidden network, then the > chances of you pinging *even one* by accident is about 1 in > 172703688516375. > If your TORdialer program could ping a million addresses per second, you > would need to run it non-stop for over five years just to find *one* > address. > > "An absolutely complete list"... oh my stars and garters. > > (Remember those maths classes on permutations and combinations that you > probably thought were totally pointless? *This* is why they're important.) > > > > -- > Steven I do sincerely apologize for anything that was rude. Please believe me, it was not my intent to be so. I also apologize for in any way contributing to anything that might be considered nefarious. I did not appreciate that the goal of the exercise was less than honourable. My interest in this had only to do with how one might come up with all possible x length strings consisting only of a predefined set of characters. Why one might want to do this, was of no interest to me at the time; in fact I didn't understand what the goal was and I appreciate your explaining that to me. Might I also take this opportunity to thank you and all the other contributers on this mailing list for the friendly helpful place I have found this list to be. Sincerely, Alex Kleider From steve at pearwood.info Sun Sep 16 06:17:00 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Sep 2012 14:17:00 +1000 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <20a10f9dc69c59763569c0cee44947b4.squirrel@webmail.sonic.net> References: <17e4420f29c6ecb6ecae648b206e32a8.squirrel@webmail.sonic.net> <5a0922c92568a945aaade890eaa1e4be.squirrel@webmail.sonic.net> <50554CE6.1030606@pearwood.info> <20a10f9dc69c59763569c0cee44947b4.squirrel@webmail.sonic.net> Message-ID: <505552BC.6070106@pearwood.info> On 16/09/12 14:11, akleider at sonic.net wrote: >> Akleider, you didn't include attribution for the person you are quoting, >> which is a bit rude and also means I can't be sure who it was. From >> context, I *think* it is the original poster Scott: > I do sincerely apologize for anything that was rude. Please believe me, it > was not my intent to be so. No problem! It's just a minor faux pas to *not* name the person you are quoting when replying to email. It just makes it hard for people to know who said what. > I also apologize for in any way contributing to anything that might be > considered nefarious. I did not appreciate that the goal of the exercise > was less than honourable. Again, no, I don't think there's anything nefarious in trying to discover TOR networks. I'm curious to know what is out there myself. It's just that the naivety of the original poster, Scott, thinking that this was a trivial problem to solve when it was *designed* to be massively hard to solve even for the CIA or Chinese military. I don't think he's a bad guy, just a bit lacking in numeracy. -- Steven From wayne at waynewerner.com Sun Sep 16 06:48:28 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 15 Sep 2012 23:48:28 -0500 (CDT) Subject: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE? In-Reply-To: References: Message-ID: On Sat, 15 Sep 2012, leam hall wrote: > Hey all, not trying to contribute to the flames of one graphical IDE over > another. I'm just trying to figure out if they are worth the learning curve? I > have been doing most of my work in vi and the graphical IDE I'm supposed to use > for a class keeps adding crap that I have to erase, and I have to move my hands > to use the GUI parts instead of just typing. > > Is there a point in which a GUI IDE becomes more of a help than a hindrance? If you really like vi, then probably not ;) I do my Python coding in Vim with some plugins. I use IPython or BPython interpreters for quickly running code/examining modules. I search duckduckgo for "python somemodule.method" to get docs/helpful examples for what I'm looking for. The only IDE I've seen that seemed like it could be worth it to me is WingIDE - because it does offer vim keybindings, and a lot of Python specific goodies. But I don't feel like laying down that chunk of change since I don't code Python professionally. The biggest thing that I'm trying to train myself to do now is `import pdb` and `pdb.set_trace()` instead of `print(value_im_interested_in)`. I've thought about setting up a vim keybinding for F9 to insert a pdb.set_trace() line where I'm at... or do some fancy things involving other files and :make. But I haven't quite hit that point of frustration yet ;) I write .NET code at work (sadly), so it might be telling that even with the ViEmu plugin for Visual Studio, I actually prefer programming in Vim (using :make), with ctags, and grep, to using Visual Studio... Of course YMMV. -HTH, Wayne From d at davea.name Sun Sep 16 07:20:24 2012 From: d at davea.name (Dave Angel) Date: Sun, 16 Sep 2012 01:20:24 -0400 Subject: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE? In-Reply-To: References: Message-ID: <50556198.7000209@davea.name> On 09/16/2012 12:48 AM, Wayne Werner wrote: > On Sat, 15 Sep 2012, leam hall wrote: > >> Hey all, not trying to contribute to the flames of one graphical IDE >> over >> another. I'm just trying to figure out if they are worth the learning >> curve? I >> have been doing most of my work in vi and the graphical IDE I'm >> supposed to use >> for a class keeps adding crap that I have to erase, and I have to >> move my hands >> to use the GUI parts instead of just typing. >> >> Is there a point in which a GUI IDE becomes more of a help than a >> hindrance? > > If you really like vi, then probably not ;) > > I do my Python coding in Vim with some plugins. I use IPython or > BPython interpreters for quickly running code/examining modules. I > search duckduckgo for "python somemodule.method" to get docs/helpful > examples for what I'm looking for. > > The only IDE I've seen that seemed like it could be worth it to me is > WingIDE - because it does offer vim keybindings, and a lot of Python > specific goodies. But I don't feel like laying down that chunk of > change since I don't code Python professionally. > > The biggest thing that I'm trying to train myself to do now is `import > pdb` and `pdb.set_trace()` instead of `print(value_im_interested_in)`. > I've thought about setting up a vim keybinding for F9 to insert a > pdb.set_trace() line where I'm at... or do some fancy things involving > other files and :make. But I haven't quite hit that point of > frustration yet ;) > > I write .NET code at work (sadly), so it might be telling that even > with the ViEmu plugin for Visual Studio, I actually prefer programming > in Vim (using :make), with ctags, and grep, to using Visual Studio... > If i were still coding C++ with MS Visual Studio, I'd probably still be using Visual Assist, by Whole Tomato. http://www.wholetomato.com/default.asp I had two companies purchase it for me, but I'm not working for either of them at the moment. And the last time i did C++ development, it was for Linux, using gcc. This product had "intellisense" before Microsoft coined the term, and hooks into their IDE to provide its enhanced features. For Python, I've paid for and am using Komodo IDE, from ActivePython. http://www.activestate.com/komodo-ide However, like most others here, i mostly work in my editor (emacs), and only switch to Komodo when I have a tougher problem to trace. -- DaveA From d at davea.name Sun Sep 16 07:25:55 2012 From: d at davea.name (Dave Angel) Date: Sun, 16 Sep 2012 01:25:55 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: <5055500F.8040800@davea.name> References: <505516DC.20500@davea.name> <50554739.2000909@davea.name> <24c7564ec693ec59d52b162a74ea6b57.squirrel@webmail.sonic.net> <5055500F.8040800@davea.name> Message-ID: <505562E3.9000001@davea.name> On 09/16/2012 12:05 AM, Dave Angel wrote: > On 09/15/2012 11:48 PM, akleider at sonic.net wrote: >>> On 09/15/2012 10:03 PM, Scurvy Scott wrote: >>>>> That list would fill all the PC's on the planet a few billions times. >>>>> The number of items in the list has 25 digits in it. print 32**16 >>>>> >>> I can't see any reason why it changes anything. The world doesn't have >>> enough disk space to store *every* address. If you need to calculate >>> all of them, you don't have enough time. >>> >>> You need to rethink whatever your real problem is. For example, if you >>> were really trying to crack a safe with 32 numbers on the dial and 16 >>> settings to open it, perhaps you should forget all of it and get some >>> nitro. Or a stethoscope. Or bribe somebody who knows the combination. >>> If you have to try all of the combinations systematically, you'll never >>> get there. >> We can probably all agree that there aren't enough resources (time, >> memory, etc) to solve the problem, but that doesn't make the problem >> uninteresting. >> What interests me, and I acknowledge that this is more a question for a >> computer science forum than a python one, is: can this be done in a non >> recursive way so the limiting factor will be time, not memory? I couldn't >> think of a way. >> > it can certainly be done non-recursively, as I showed with a relatively > simple list comprehension, borrowing the idea from Peter Otten. > > import itertools > chars = "ab5" > result = ["".join(item) for item in itertools.product(*[chars]*4)] > > Non-recursive doesn't mean "uses little memory," however. > > Since the problem is to build a list, it will use lots of memory. If > the problem were instead to make a generator that yields all possible > strings, > > import itertools > chars = "ab5" > result_generator = ("".join(item) for item in itertools. product(*[chars]*4)) > > Now, you could write a loop that examined all these items (pretending > you had unlimited time), something like: > > for item in result_generator: > if test_safe(item): > print item, "cracked the algorithm" > > obviously, you'd need a longer chars, and to change *4 to *16, if you > actually wanted to do the original dataset. > > And if you don't want to use itertools, you can trivially do it in a > loop, since you're basically just counting, base 32. > A slight addendum. The other, recursive, implementation ran out of memory not because of recursion, but because it was building a ginormous list. The recursion is limited to 16 levels, as written. So that algorithm could also be turned into a generator, if we wanted to be time-limited and not memory limited. -- DaveA From dvnsarma at gmail.com Sun Sep 16 16:36:21 2012 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Sun, 16 Sep 2012 20:06:21 +0530 Subject: [Tutor] Musical note on python In-Reply-To: References: Message-ID: winsound.Beep() takes only integral values for frequency. Therefore you cannot use it if you want either just intonation or equal temperment scales exactly. -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sun Sep 16 18:50:24 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Sep 2012 12:50:24 -0400 Subject: [Tutor] All possible 16 character alphanumeric strings? In-Reply-To: References: Message-ID: On Sat, Sep 15, 2012 at 6:50 PM, Scurvy Scott wrote: > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. This type of problem is just nested iteration: >>> seq = '01' >>> r = [] >>> for g0 in seq: ... for g1 in seq: ... for g2 in seq: ... r.append( ''.join([g0, g1, g2])) ... >>> r ['000', '001', '010', '011', '100', '101', '110', '111'] You can generalize this with a recursive generator, or use itertools.product(seq, repeat=N): def seq_prod(seq, n): if n > 1: for left in seq: for right in seq_prod(seq, n - 1): yield (left,) + right elif n == 1: for item in seq: yield (item,) >>> [''.join(s) for s in seq_prod('01', 3)] ['000', '001', '010', '011', '100', '101', '110', '111'] >>> [''.join(s) for s in itertools.product('01', repeat=3)] ['000', '001', '010', '011', '100', '101', '110', '111'] From etanes.rm at gmail.com Mon Sep 17 01:50:07 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sun, 16 Sep 2012 16:50:07 -0700 Subject: [Tutor] How to run this block of code dozens of times Message-ID: Hello all, I'm just wondering how to run this block of code X amount of times (a lot) and then store the ouput to a .txt file. The code I've written is below. from Crypto.PublicKey import RSA import hashlib m = RSA.generate(1024) b = hashlib.sha1() b.update(str(m)) a = b.hexdigest() print a[:16] + '.onion' Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Mon Sep 17 01:51:00 2012 From: dfjennings at gmail.com (Don Jennings) Date: Sun, 16 Sep 2012 19:51:00 -0400 Subject: [Tutor] find('') returns 0 Message-ID: <3A181C7D-B323-4709-BF48-EAC1BBF18D20@gmail.com> This behavior seems strange to me: the find method of a string returns the position zero when you search for an empty string (granted, I can't quite figure out why you'd search for an empty string, either). >>> 'abc'.find('') 0 Anyone care to share a good explantion for this behavior and possible use cases? Thanks! Take care, Don From etanes.rm at gmail.com Mon Sep 17 01:56:04 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sun, 16 Sep 2012 16:56:04 -0700 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: Message-ID: scratch that, new code is below for your perusal: from Crypto.PublicKey import RSA import hashlib def repeat_a_lot(): count = 0 while count < 20: m = RSA.generate(1024) b = hashlib.sha1() b.update(str(m)) a = b.hexdigest() print a[:16] + '.onion' count += 1 repeat_a_lot() Thanks again, Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Sep 17 02:23:43 2012 From: d at davea.name (Dave Angel) Date: Sun, 16 Sep 2012 20:23:43 -0400 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: Message-ID: <50566D8F.9090709@davea.name> On 09/16/2012 07:56 PM, Scurvy Scott wrote: > scratch that, new code is below for your perusal: > > from Crypto.PublicKey import RSA > import hashlib > > def repeat_a_lot(): > count = 0 > while count < 20: You're kidding, aren't you? while loops are meant for those times when you don't know how many times the loop is to iterate. > m = RSA.generate(1024) > b = hashlib.sha1() > b.update(str(m)) > a = b.hexdigest() > print a[:16] + '.onion' > count += 1 > repeat_a_lot() > > > def repeat_a_lot(): for _ in xrange(20): m = RSA.generate(1024) b = hashlib.sha1() b.update(str(m)) a = b.hexdigest() print a[:16] + '.onion' repeat_a_lot() -- DaveA From eryksun at gmail.com Mon Sep 17 02:33:32 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Sep 2012 20:33:32 -0400 Subject: [Tutor] find('') returns 0 In-Reply-To: <3A181C7D-B323-4709-BF48-EAC1BBF18D20@gmail.com> References: <3A181C7D-B323-4709-BF48-EAC1BBF18D20@gmail.com> Message-ID: On Sun, Sep 16, 2012 at 7:51 PM, Don Jennings wrote: > This behavior seems strange to me: the find method of a string returns the position zero when you search for an empty string (granted, I can't quite figure out why you'd search for an empty string, either). > >>>> 'abc'.find('') > 0 > > Anyone care to share a good explantion for this behavior and possible use cases? Thanks! It actually returns the value of "start": >>> 'abc'.find('', 0) 0 >>> 'abc'.find('', 1) 1 >>> 'abc'.find('', 2) 2 It's looking for the length 0 substring ''. So it will match a 0 length slice at the given start position: >>> 'abc'[0:0] '' >>> 'abc'[1:1] '' >>> 'abc'[2:2] '' When you find 'b', for example, it searches for a length 1 slice: >>> 'abc'.find('b') 1 >>> 'abc'[1:2] 'b' The 'in' operator also searches for a substring: >>> '' in 'abc' True From etanes.rm at gmail.com Mon Sep 17 02:56:20 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sun, 16 Sep 2012 17:56:20 -0700 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: <50566D8F.9090709@davea.name> References: <50566D8F.9090709@davea.name> Message-ID: On Sun, Sep 16, 2012 at 5:23 PM, Dave Angel wrote: > On 09/16/2012 07:56 PM, Scurvy Scott wrote: > > scratch that, new code is below for your perusal: > > > > from Crypto.PublicKey import RSA > > import hashlib > > > > def repeat_a_lot(): > > count = 0 > > while count < 20: > > >You're kidding, aren't you? while loops are meant for those times when > >you don't know how many times the loop is to iterate. > > Acutally, Dave, I would be the one setting just how many times the loop would run manually. Actually the loop would run 2^80 times, so it was more of a test to see if the output was different each time it ran more than trying to run it the correct amount of times. > > m = RSA.generate(1024) > > b = hashlib.sha1() > > b.update(str(m)) > > a = b.hexdigest() > > print a[:16] + '.onion' > > count += 1 > > repeat_a_lot() > > > > > > > > def repeat_a_lot(): > for _ in xrange(20): > m = RSA.generate(1024) > b = hashlib.sha1() > b.update(str(m)) > a = b.hexdigest() > print a[:16] + '.onion' > > repeat_a_lot() > > Why would you use an underscore rather than a letter or name like I've always seen. I've never seen an underscore used before. Scott > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Sep 17 02:57:31 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Sep 2012 20:57:31 -0400 Subject: [Tutor] find('') returns 0 In-Reply-To: References: <3A181C7D-B323-4709-BF48-EAC1BBF18D20@gmail.com> Message-ID: On Sun, Sep 16, 2012 at 8:33 PM, eryksun wrote: > > The 'in' operator also searches for a substring: > > >>> '' in 'abc' > True I forgot to mention, this use of slices is a peculiarity to strings. In contrast, list.index and list.__contains__ ("in") match against individual items. An empty list slice [] is not "in" ['a', 'b', 'c']. Be careful about this use of substrings: >>> 'care' in 'careful programming' True >>> 'care' in 'careful programming'.split() False From breamoreboy at yahoo.co.uk Mon Sep 17 03:16:16 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Sep 2012 02:16:16 +0100 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: <50566D8F.9090709@davea.name> Message-ID: On 17/09/2012 01:56, Scurvy Scott wrote: > > Why would you use an underscore rather than a letter or name like I've > always seen. I've never seen an underscore used before. > Try reading some of the documentation here http://www.python.org/doc/ It's amazing what you can learn. -- Cheers. Mark Lawrence. From pedrooconnell at gmail.com Mon Sep 17 03:15:14 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 17 Sep 2012 13:15:14 +1200 Subject: [Tutor] reducing a list evenly when deleting elements by index Message-ID: Hi, I have a bezier line with 20 points on it and I am trying to reduce this to a line with 4 points, keeping the first and last points and 2 evenly spaced points in between like so: *....................* becomes: *. . . .* These points are removable only by index, so if I remove point 2, point 3 then becomes point 2 in the next iteration, so I end up having a spacing like this which is not what I want: *. . . .* Here is the code that I have so far. I hope it makes sense: ############################################################################################## for aNode in nuke.allNodes(): if aNode.shown(): theRotoNode = aNode curveKnob = theRotoNode['curves'] rootLayer = curveKnob.rootLayer theNumberOfPointToReduceTo = 5 for aShape in rootLayer: theOriginalShape = aShape thePointList = [] for aPoint in aShape: thePointList.append(aPoint) if len(thePointList) > 5: theNumberOfPoints = len(thePointList) keepEvery = float(theNumberOfPoints)/theNumberOfPointToReduceTo theIndicesToKeep = [] theIndicesToKeep.append(0) theIndicesToKeep.append(1) for i in range(theNumberOfPoints)[1:-1]: if i*keepEvery < theNumberOfPoints: theIndicesToKeep.append(int(round(i*keepEvery))) theIndicesToKeep.append(theNumberOfPoints-2) theIndicesToKeep.append(theNumberOfPoints-1) thePointsToRemove = tuple(set(range(theNumberOfPoints)) - set(theIndicesToKeep)) #everything is good up to here, the code below doesn't work properly and I'm kinda stuck counter = -1 for aPointIndex in thePointsToRemove: counter+=1 aPointIndex = aPointIndex-(counter) print aPointIndex aShape.remove(aPointIndex) ############################################################################################ Any advice would be greatly appreciated. Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Sep 17 03:29:44 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Sep 2012 02:29:44 +0100 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: Message-ID: On 17 September 2012 02:15, Pete O'Connell wrote: > Hi, I have a bezier line with 20 points on it and I am trying to reduce > this to a line with 4 points, keeping the first and last points and 2 > evenly spaced points in between like so: > *....................* > becomes: > *. . . .* > > These points are removable only by index, so if I remove point 2, > point 3 then becomes point 2 in the next iteration, so I end up having a > spacing like this which is not what I want: > *. . . .* But removing item 19 doesn't affect the position of item 2. The trick is to start the loop at the end of the list and work back to the beginning. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Mon Sep 17 03:47:55 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 17 Sep 2012 13:47:55 +1200 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: Message-ID: Ah of course. Thanks very much Oscar! Pete On Mon, Sep 17, 2012 at 1:29 PM, Oscar Benjamin wrote: > On 17 September 2012 02:15, Pete O'Connell wrote: > >> Hi, I have a bezier line with 20 points on it and I am trying to reduce >> this to a line with 4 points, keeping the first and last points and 2 >> evenly spaced points in between like so: >> *....................* >> becomes: >> *. . . .* >> >> These points are removable only by index, so if I remove point 2, >> point 3 then becomes point 2 in the next iteration, so I end up having a >> spacing like this which is not what I want: >> *. . . .* > > > But removing item 19 doesn't affect the position of item 2. The trick is > to start the loop at the end of the list and work back to the beginning. > > Oscar > -- - -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Sep 17 04:22:01 2012 From: d at davea.name (Dave Angel) Date: Sun, 16 Sep 2012 22:22:01 -0400 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: <50566D8F.9090709@davea.name> Message-ID: <50568949.4030804@davea.name> On 09/16/2012 08:56 PM, Scurvy Scott wrote: > On Sun, Sep 16, 2012 at 5:23 PM, Dave Angel wrote: > >> On 09/16/2012 07:56 PM, Scurvy Scott wrote: >>> scratch that, new code is below for your perusal: >>> >>> from Crypto.PublicKey import RSA >>> import hashlib >>> >>> def repeat_a_lot(): >>> count = 0 >>> while count < 20: >>> You're kidding, aren't you? while loops are meant for those times when >>> you don't know how many times the loop is to iterate. >> > Acutally, Dave, I would be the one setting just how many times the loop > would run manually. Actually the loop would run 2^80 times, so it was more > of a test to see if the output was different each time it ran more than > trying to run it the correct amount of times. > Since you know the count before you start the loop, then use xrange(), rather than while. If you had to test some condition other than a simple count, then you might want to use while. As the loop was coded, you have three uses of a variable that doesn't matter to anyone reading the code. one to initialize it, one to test it, and one to increment it. >>> m = RSA.generate(1024) >>> b = hashlib.sha1() >>> b.update(str(m)) >>> a = b.hexdigest() >>> print a[:16] + '.onion' >>> count += 1 >>> repeat_a_lot() >>> >>> >>> >> def repeat_a_lot(): >> for _ in xrange(20): >> m = RSA.generate(1024) >> b = hashlib.sha1() >> b.update(str(m)) >> a = b.hexdigest() >> print a[:16] + '.onion' >> >> repeat_a_lot() >> >> > Why would you use an underscore rather than a letter or name like I've > always seen. I've never seen an underscore used before Standard convention for an unused loop variable. But if you prefer, no harm in naming it something like for unused_counter_here in xrange(20): The unadorned underscore leads the reader to expect that you don't use the loop variable anywhere, like for indexing some matrix. -- DaveA From computer_dude15 at hotmail.com Mon Sep 17 04:45:35 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Sun, 16 Sep 2012 22:45:35 -0400 Subject: [Tutor] simple random string generator Message-ID: hey im new to the tutor thing so please correct me if im doing something wrong. Anyway what i am trying to do is make a simple string (word) generator and get it to make strings (or words) starting at 10 chars up to 100 in steps of 5 using a make word function. Now my problem is how do i get it to run the mkword function and manipulate the n value to fit those requirements? the main goal of the assignment is to get it to generate the strings (words) and compare it to itself so we can see the time it takes to compare using different methods. http://pastie.org/4735416 the problem lies in the "main()" function i know that. there is my code...in no way am i asking anyone to do it for me! i really want to learn but i feel like my professor is kinda doing a questionable job teaching it...this will be my second semester of python and i have just started dealing with classes and multiple functions about a week ago and also trying to switch from 2.7 to 3.2. also another question and hopefully someone has some suggestions for me...i am just having problems learning python...like in understand it, i can read it, and know what is going on and what needs to be done...but when it comes to writing it i just dont know how to do it... does anyone else have this prob? and is there anything i can do to start really soaking it in? thanks in advance guys :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Sep 17 05:17:20 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Sep 2012 13:17:20 +1000 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: <50566D8F.9090709@davea.name> Message-ID: <50569640.4080807@pearwood.info> On 17/09/12 10:56, Scurvy Scott wrote: > Why would you use an underscore rather than a letter or name like I've > always seen. I've never seen an underscore used before. An underscore on its own is often used to mean "don't care". Like a scratch variable to hold a result when you don't actually need the result. So in a for-loop: for _ in range(20): ... the idea is to tell the reader we don't actually care about the indexes 0, 1, 2, ... but only care that the loop happens 20 times. Other uses are: * a single leading underscore usually means "private, don't touch" E.g. if you see a function called _func then you shouldn't use it in your own code, because the author is stating that the function is for private use only and it might go away or change in the next version. * double leading and trailing underscore names have special meaning to Python, e.g.: __name__ __class__ __len__ __add__ and many others -- Steven From steve at pearwood.info Mon Sep 17 05:25:53 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Sep 2012 13:25:53 +1000 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: Message-ID: <50569841.2090006@pearwood.info> On 17/09/12 11:15, Pete O'Connell wrote: > Hi, I have a bezier line with 20 points on it and I am trying to reduce > this to a line with 4 points, keeping the first and last points and 2 > evenly spaced points in between like so: In general in Python, it is faster and much easier to create a new list rather than to mess about deleting items from a list. So instead of calling del 16 times, which has to move list items around, it will be faster and simpler to create a new list: new = [old[0], old[6], old[13], old[19]] then just use the new list. If you really need to modify the old list in place (perhaps because other parts of the code need to see the same change) then you can do a slice-assignment: old[:] = new # note the [:] slice -- Steven From steve at pearwood.info Mon Sep 17 06:33:41 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Sep 2012 14:33:41 +1000 Subject: [Tutor] simple random string generator In-Reply-To: References: Message-ID: <5056A825.308@pearwood.info> On 17/09/12 12:45, Matthew Dalrymple wrote: > Anyway what i am trying to do is make a simple string (word) > generator and get it to make strings (or words) starting at 10 chars > up to 100 in steps of 5 using a make word function. Now my problem > is how do i get it to run the mkword function and manipulate the n > value to fit those requirements? Use a for-loop. for n in range(10, 101, 5): print(n) The print is just as a demonstration. In your code, you would instead call your mkword function. [...] >i am just having problems learning python...like in understand it, i > can read it, and know what is going on and what needs to be done...but >when it comes to writing it i just dont know how to do it... Hang in there mate, practice makes perfect. Writing code is a combination of creativity and careful, precise, logical reasoning. Some people find it easy, some people don't. When you have a task, try breaking it up into simple steps, like you were giving instructions to your two-year-old cousin. (In reality, computers are *much* dumber than a two-year old, but that's a good start.) > does anyone else have this prob? I'm sure most people have had this problem for at least a little while. > and is there anything i can do to start really soaking it in? Write code. Lots of code. It doesn't matter if it is junk code, or toy code, just write lots of code, until it becomes second nature. -- Steven From etanes.rm at gmail.com Mon Sep 17 08:21:48 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sun, 16 Sep 2012 23:21:48 -0700 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: Message-ID: Wow, thanks Dave, et al., for explaining things the way they did. I'm not trying to and apologize for top posting, gmail wasn't giving me the option of replying to all. I definitely understand what was going on and why when you all were explaining the code portions to me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Sep 17 08:58:19 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Sep 2012 08:58:19 +0200 Subject: [Tutor] How to run this block of code dozens of times References: <50566D8F.9090709@davea.name> Message-ID: Scurvy Scott wrote: > Actually the loop would run 2^80 times Remember the previous thread? This means the loop will not terminate in the next few million years. From rei.johny at yahoo.com.ph Mon Sep 17 09:12:19 2012 From: rei.johny at yahoo.com.ph (Johny Rei) Date: Mon, 17 Sep 2012 15:12:19 +0800 (SGT) Subject: [Tutor] Convert from meters to British length units. Message-ID: <1347865939.78322.YahooMailNeo@web192304.mail.sg3.yahoo.com> Help out there folks,,.I'm completely lost on ?how to make a program where you set a length given in meters and then compute and write out the corresponding length measured in inches,in feet, in yards, and in miles.Can anybody guide me here, By the example you may provide will be appreciated.., -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Sep 17 09:40:30 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Sep 2012 09:40:30 +0200 Subject: [Tutor] Convert from meters to British length units. References: <1347865939.78322.YahooMailNeo@web192304.mail.sg3.yahoo.com> Message-ID: Johny Rei wrote: > Help out there folks,,.I'm completely lost on how to make a program where > you set a length given in meters and then compute and write out the > corresponding length measured in inches,in feet, in yards, and in > miles.Can anybody guide me here, By the example you may provide will be > appreciated.., Here's an example that converts days into seconds: >>> days = float(raw_input("Days ")) Days 12.5 >>> print "That's %s seconds" % (days * 24 * 60 * 60) That's 1080000.0 seconds Can you understand how that works? Try to apply it to a meter to feet conversion and show us your code. Then we may look into the next step, converting meters into a combination of inches and feet. From fomcl at yahoo.com Mon Sep 17 09:42:41 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 17 Sep 2012 00:42:41 -0700 (PDT) Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> Message-ID: <1347867761.57208.YahooMailNeo@web110713.mail.gq1.yahoo.com> > > http://code.google.com/p/psutil > I looked at the website and it looks like a cool module. Some of it appeared to be *nix only, but I'll have to dig into it more. But it's also just like you said: how far should one go with micromanaging things?? Maybe some things are the caller's responsibility. > If you're also supporting the iterator protocol with the __iter__ > method, then I think a helper _items(start, stop, step) generator > function would be a good idea. > > Here's an updated example (not tested however; it's just a suggestion): > > > ? ? import operator > > ? ? def _items(self, start=0, stop=None, step=1): > ? ? ? ? if stop is None: > ? ? ? ? ? ? stop = self.nCases > > ? ? ? ? for i in range(start, stop, step): > ? ? ? ? ? ? retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(i)) > ? ? ? ? ? ? self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() > ? ? ? ? ? ? retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr) > ? ? ? ? ? ? record = struct.unpack(self.structFmt, self.caseBuffer.raw) > ? ? ? ? ? ? if any([retcode1, retcode2]): > ? ? ? ? ? ? ? ? raise RuntimeError("Error retrieving record %d [%s, > %s]" % > ? ? ? ? ? ? ? ? ? ? (i, retcodes[retcode1], retcodes[retcode2])) > ? ? ? ? ? ? yield record > > > ? ? def __iter__(self): > ? ? ? ? return self._items() > > > ? ? def __getitem__(self, key): > > ? ? ? ? is_slice = isinstance(key, slice) > > ? ? ? ? if is_slice: > ? ? ? ? ? ? start, stop, step = key.indices(self.nCases) > ? ? ? ? else: > ? ? ? ? ? ? key = operator.index(key) > ? ? ? ? ? ? start = key + self.nCases if key < 0 else key > ? ? ? ? ? ? if not 0 <= start < self.nCases: > ? ? ? ? ? ? ? ? raise IndexError > ? ? ? ? ? ? stop = start + 1 > ? ? ? ? ? ? step = 1 > > ? ? ? ? records = self._items(start, stop, step) > ? ? ? ? if is_slice: > ? ? ? ? ? ? return list(records) > ? ? ? ? return next(records) > > Awesome, thank you so much. This has been very inspiring! When this is working, I'm thinking about also implementing an Ellipsis (just because it's possible ;-), so I can cut out certain parts of the data using a numpy array. Another idea would be to also use __getitem__ as a dictionary. So when the data contains an id (let's say ssn), r = Reader(key="ssn"); r.data["87654321"] returns the corresponding (first available) record. But although this is cool from an educational perspective, I do wonder whether, from a design perspective, it's a good idea to make __getitem__ this fully packed. From fomcl at yahoo.com Mon Sep 17 10:59:02 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 17 Sep 2012 01:59:02 -0700 (PDT) Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347867761.57208.YahooMailNeo@web110713.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> <1347867761.57208.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: <1347872342.94975.YahooMailNeo@web110714.mail.gq1.yahoo.com> ----- Original Message ----- > From: Albert-Jan Roskam > To: eryksun > Cc: "tutor at python.org" > Sent: Monday, September 17, 2012 9:42 AM > Subject: Re: [Tutor] is this use or abuse of __getitem__ ? > >& lt;snip> > >> >>??http://code.google.com/p/psutil >> > > > I looked at the website and it looks like a cool module. Some of it appeared to > be *nix only, but I'll have to dig into it more. > But it's also just like you said: how far should one go with micromanaging > things?? Maybe some things are the caller's responsibility. > > >>??If you're also supporting the iterator protocol with the __iter__ >>??method, then I think a helper _items(start, stop, step) generator >>??function would be a good idea. >> >>??Here's an updated example (not tested however; it's just a > suggestion): >> >> >>??? ? import operator >> >>??? ? def _items(self, start=0, stop=None, step=1): >>??? ? ? ? if stop is None: >>??? ? ? ? ? ? stop = self.nCases >> >>??? ? ? ? for i in range(start, stop, step): >>??? ? ? ? ? ? retcode1 = self.iomodule.SeekNextCase(self.fh, > ctypes.c_long(i)) >>??? ? ? ? ? ? self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer() >>??? ? ? ? ? ? retcode2 = self.iomodule.WholeCaseIn(self.fh, > self.caseBufferPtr) >>??? ? ? ? ? ? record = struct.unpack(self.structFmt, self.caseBuffer.raw) >>??? ? ? ? ? ? if any([retcode1, retcode2]): >>??? ? ? ? ? ? ? ? raise RuntimeError("Error retrieving record %d [%s, >>??%s]" % >>??? ? ? ? ? ? ? ? ? ? (i, retcodes[retcode1], retcodes[retcode2])) >>??? ? ? ? ? ? yield record >> >> >>??? ? def __iter__(self): >>??? ? ? ? return self._items() >> >> >>??? ? def __getitem__(self, key): >> >>??? ? ? ? is_slice = isinstance(key, slice) >> >>??? ? ? ? if is_slice: >>??? ? ? ? ? ? start, stop, step = key.indices(self.nCases) >>??? ? ? ? else: >>??? ? ? ? ? ? key = operator.index(key) >>??? ? ? ? ? ? start = key + self.nCases if key < 0 else key >>??? ? ? ? ? ? if not 0 <= start < self.nCases: >>??? ? ? ? ? ? ? ? raise IndexError >>??? ? ? ? ? ? stop = start + 1 >>??? ? ? ? ? ? step = 1 >> >>??? ? ? ? records = self._items(start, stop, step) >>??? ? ? ? if is_slice: >>??? ? ? ? ? ? return list(records) >>??? ? ? ? return next(records) >> >> > > Awesome, thank you so much. This has been very inspiring! When this is working, > I'm thinking about also implementing an Ellipsis (just because it's > possible ;-), so I can cut out certain parts of the data using a numpy array. > Another idea would be to also use __getitem__ as a dictionary. So when the data > contains an id (let's say ssn), r = Reader(key="ssn"); > r.data["87654321"] returns the corresponding (first available) record. > But although this is cool from an educational perspective, I do wonder whether, > from a design perspective, it's a good idea to make __getitem__ this fully > packed. > To respond to my own reply: I couldn't resist checking out numpy/Ellipsis (maybe because "Ellipsis" is such a weird statement ;-) Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 >>> import numpy >>> class C (object): ??? def __init__(self, records): ??? ??? self.records = records ??? def __getitem__(self, key): ??? ??? print key, type(key) ??? ??? if key is Ellipsis or Ellipsis in key or isinstance(key, tuple): ??? ??? ??? return numpy.array(self.records)[key].tolist() >>> records = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> c = C(records) >>> c[...] # all records Ellipsis [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> c[1,...]? # second record (1, Ellipsis) [4, 5, 6] >>> c[...,1] # second column (Ellipsis, 1) [2, 5, 8] >>> c[0,1] # value on first row, second column (0, 1) 2 From eryksun at gmail.com Mon Sep 17 11:46:36 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 17 Sep 2012 05:46:36 -0400 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: <50569640.4080807@pearwood.info> References: <50566D8F.9090709@davea.name> <50569640.4080807@pearwood.info> Message-ID: On Sun, Sep 16, 2012 at 11:17 PM, Steven D'Aprano wrote: > > Other uses are: > > * a single leading underscore usually means "private, don't touch" > > * double leading and trailing underscore names have special meaning > to Python, e.g.: There's also the _() function for I18N: http://docs.python.org/library/gettext.html#gettext.install http://docs.python.org/library/gettext.html#internationalizing-your-programs-and-modules From dsbmach at gmail.com Mon Sep 17 11:56:30 2012 From: dsbmach at gmail.com (DM) Date: Mon, 17 Sep 2012 05:56:30 -0400 Subject: [Tutor] Resources to create a form filler Message-ID: Hi I've learned a little python via MIT's 6.01SC and would like to gain experience with personal projects. I'd like to make a web form filler for the desktop. I'd appreciate it if someone could suggest what resources I would need to build it. Thanks! From eryksun at gmail.com Mon Sep 17 12:18:13 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 17 Sep 2012 06:18:13 -0400 Subject: [Tutor] is this use or abuse of __getitem__ ? In-Reply-To: <1347867761.57208.YahooMailNeo@web110713.mail.gq1.yahoo.com> References: <1347625009.71590.YahooMailNeo@web110716.mail.gq1.yahoo.com> <50534E37.6050106@pearwood.info> <1347647582.97381.YahooMailNeo@web110708.mail.gq1.yahoo.com> <1347718706.22052.YahooMailNeo@web110712.mail.gq1.yahoo.com> <1347867761.57208.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: On Mon, Sep 17, 2012 at 3:42 AM, Albert-Jan Roskam wrote: > > Another idea would be to also use __getitem__ as a dictionary. So when > the data contains an id (let's say ssn), r = Reader(key="ssn"); > r.data["87654321"] returns the corresponding (first available) record. > But although this is cool from an educational perspective, I do wonder > whether, from a design perspective, it's a good idea to make __getitem__ > this fully packed. Maybe have a mappingview() method that returns a lazy mapping view of the object. That way you're not mixing up indexed and mapping subscription. From __peter__ at web.de Mon Sep 17 12:52:17 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Sep 2012 12:52:17 +0200 Subject: [Tutor] Convert from meters to British length units. References: <1347865939.78322.YahooMailNeo@web192304.mail.sg3.yahoo.com> Message-ID: Johny Rei wrote: [Please hit replay-all when you answer posts on this mailing list; that way everyone on the list can see your post] > Yes Sir, thank you sir, You're welcome. Note that we're OK with a less formal tone over here ;) > I do understand how this works, these is the printf formatting, Sir I tried to apply the conversion from meter to feet that you recommend, > > Here's what i write from my code sir; > > >>>feet = 3.28 > >>>meter = float(input("meter ")) # py version 3.2 > meter 640 > >>>print ('Is it %g feet?' %(meter*feet)) > Is it 2099.2 feet?.... > ...... > > Sir, It's bothering me enough about some of the area of the decimal point from this numbers in a solution on a certain occasion especially when I'm verifying in from computing because of i'am not so sure off whether is it accurate, correct or not...sir whats your opinion from these? > and Again, Thank you Sir, If I understand you correctly you're bothered about rounding errors? These are unavoidable with floating point numbers. If you need exact results for the multiplication of decimal values you can use the decimal module, see http://docs.python.org/dev/py3k/library/decimal.html However, the problem resurfaces as soon as you try to calculate something like 1/3 that cannot be represented as a decimal number. From oscar.j.benjamin at gmail.com Mon Sep 17 15:02:48 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Sep 2012 13:02:48 +0000 (UTC) Subject: [Tutor] reducing a list evenly when deleting elements by index References: <50569841.2090006@pearwood.info> Message-ID: On 2012-09-17, Steven D'Aprano wrote: > On 17/09/12 11:15, Pete O'Connell wrote: >> Hi, I have a bezier line with 20 points on it and I am trying to reduce >> this to a line with 4 points, keeping the first and last points and 2 >> evenly spaced points in between like so: > > In general in Python, it is faster and much easier to create a new list > rather than to mess about deleting items from a list. > > So instead of calling del 16 times, which has to move list items around, > it will be faster and simpler to create a new list: > > new = [old[0], old[6], old[13], old[19]] > > then just use the new list. If you really need to modify the old list in > place (perhaps because other parts of the code need to see the same > change) then you can do a slice-assignment: > > old[:] = new # note the [:] slice > I certainly agree with Steven's comments here that there are much less convulated ways to replace a list with a new list containing a subset of its elements. I would also like to add, though, that I'm not sure if what you're doing makes sense from a mathematical/geometrical viewpoint. It's not totally clear to me from your original post what you're trying to do. I can think of two interpretations: 1) You have a Bezier curver consisting of 20 control points and would like to approximate it with a simpler cubic Bezier curve consisting of only 4 points. I would call this "approximating a Bezier with a lower order Bezier". 2) You have a line that goes through 20 points and you would like to represent it as a cubic Bezier with 4 control points. I would call this "fitting a cubic Bezier to a sequence of points along a line". In either case I think that choosing 4 of the points and using them as a cubic Bezier is incorrect. For case 1) I don't think it's possible to approximate a Bezier using a subset of its control points. I'm not sure how to prove it but I think that typically a significantly higher order Bezier will have control points that are closer to the curve than an equivalent lower order Bezier. For case 2) it's not appropriate to think of a Bezier as interpolating its control points because it doesn't go through it's control points (except for the two at the ends). In either case I would expect a good method to use information from all of the original sequence of points rather than ignoring all but a small subset. Oscar From wayne at waynewerner.com Mon Sep 17 15:47:49 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Mon, 17 Sep 2012 08:47:49 -0500 (CDT) Subject: [Tutor] Resources to create a form filler In-Reply-To: References: Message-ID: On Mon, 17 Sep 2012, DM wrote: > Hi I've learned a little python via MIT's 6.01SC and would like to > gain experience with personal projects. I'd like to make a web form > filler for the desktop. I'd appreciate it if someone could suggest > what resources I would need to build it. Thanks! Do you mean something like AutoFill/autocomplete in Google Chrome? What operating system are you using? -W From emile at fenx.com Mon Sep 17 17:23:36 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 17 Sep 2012 08:23:36 -0700 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: <50569640.4080807@pearwood.info> References: <50566D8F.9090709@davea.name> <50569640.4080807@pearwood.info> Message-ID: On 9/16/2012 8:17 PM Steven D'Aprano said... > On 17/09/12 10:56, Scurvy Scott wrote: > >> Why would you use an underscore rather than a letter or name like I've >> always seen. I've never seen an underscore used before. > > An underscore on its own is often used to mean "don't care". Like a > scratch variable to hold a result when you don't actually need the result. > So in a for-loop: > > for _ in range(20): > ... > > > the idea is to tell the reader we don't actually care about the indexes > 0, 1, 2, ... but only care that the loop happens 20 times. Be sure you don't at some point depend on _ having a specific value however, as return values of functions are given the _ name in the absense of a designated label for the returned value: ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def test(): return True ... >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> test() True >>> _ True >>> Emile From oscar.j.benjamin at gmail.com Mon Sep 17 17:46:10 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Sep 2012 15:46:10 +0000 (UTC) Subject: [Tutor] How to run this block of code dozens of times References: <50566D8F.9090709@davea.name> <50569640.4080807@pearwood.info> Message-ID: On 2012-09-17, Emile van Sebille wrote: > > Be sure you don't at some point depend on _ having a specific value > however, as return values of functions are given the _ name in the > absense of a designated label for the returned value: > > ActivePython 2.6.6.15 (ActiveState Software Inc.) based on > Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> def test(): return True > ... > >>> _ > Traceback (most recent call last): > File "", line 1, in > NameError: name '_' is not defined > >>> test() > True > >>> _ > True > >>> This only happens as a convenience in interactive mode. In scripts or modules the _ identifier has no significance except for the convention that it is a value you don't care about. $ cat tmp.py def test(): return True test() _ $ python tmp.py Traceback (most recent call last): File "tmp.py", line 3, in _ NameError: name '_' is not defined Oscar From sntshkmr60 at gmail.com Mon Sep 17 18:04:05 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Mon, 17 Sep 2012 21:34:05 +0530 Subject: [Tutor] Trying to get next item from a list Message-ID: Here is the script: alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] i = input("Press any English alphabet: ") current = alphabets.index(i) print(current) next = current+1 print(next) print(alphabets.index(next)) I am getting a ValueError. And as you can see, I just trying to get the next item. So is there any way I can get same functionality in less line of codes? From joel.goldstick at gmail.com Mon Sep 17 18:14:06 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 17 Sep 2012 12:14:06 -0400 Subject: [Tutor] Trying to get next item from a list In-Reply-To: References: Message-ID: On Mon, Sep 17, 2012 at 12:04 PM, Santosh Kumar wrote: > Here is the script: > > alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', > 'z'] > i = input("Press any English alphabet: ") You ask for a letter, but you are using it as an index. In ascii, the letter 'a' is represented by the number 97. The rest of the alphabet goes up from there. First you want to be sure that you are getting a lower case letter. Look in the documentation for string methods to see how that is done. Make sure that i is lower case. then using the ord('a') function you will get 97. If you subtract ord('a') from ord(i) you will get the index that you call current. But be careful because if your user choses 'z', you will end up with a character that is out of range in your list. You could either say that is the end, or wrap back around to a > current = alphabets.index(i) > print(current) > next = current+1 > print(next) > print(alphabets.index(next)) > > I am getting a ValueError. > > And as you can see, I just trying to get the next item. So is there > any way I can get same functionality in less line of codes? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From tvssarma.omega9 at gmail.com Mon Sep 17 18:18:06 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Mon, 17 Sep 2012 12:18:06 -0400 Subject: [Tutor] Trying to get next item from a list In-Reply-To: References: Message-ID: On 17 September 2012 12:04, Santosh Kumar wrote: > Here is the script: > > alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', > 'z'] > i = input("Press any English alphabet: ") > current = alphabets.index(i) > print(current) > next = current+1 > print(next) > print(alphabets.index(next)) > > I am getting a ValueError. > > And as you can see, I just trying to get the next item. So is there > any way I can get same functionality in less line of codes? > > When you access index the second time you are trying to do so with the value of the index. -- 0 1 0 0 0 1 1 1 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Mon Sep 17 18:19:47 2012 From: crawlzone at gmail.com (Ray Jones) Date: Mon, 17 Sep 2012 09:19:47 -0700 Subject: [Tutor] How to run this block of code dozens of times In-Reply-To: References: <50566D8F.9090709@davea.name> <50569640.4080807@pearwood.info> Message-ID: <50574DA3.1000604@gmail.com> On 09/17/2012 02:46 AM, eryksun wrote: > On Sun, Sep 16, 2012 at 11:17 PM, Steven D'Aprano wrote: >> Other uses are: >> >> * a single leading underscore usually means "private, don't touch" >> >> * double leading and trailing underscore names have special meaning >> to Python, e.g.: > There's also the _() function for I18N: Hey, I've been on that freeway - up around Chicago, right? ;) From bala.biophysics at gmail.com Mon Sep 17 19:11:18 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 17 Sep 2012 19:11:18 +0200 Subject: [Tutor] combining c and python Message-ID: Friends, I code in python and so far able to write simple scripts for my needs. Now i want to try the combination of c and python. 1) could someone please suggest me some good documentation on how python and C can be combined. Some tutorials with simple examples. 2) If i know that a specific part (loop in my case) within my python script consumes more processing time, is it possible to implement/use 'c' only for that part. Precisely using C within python ? Any link for documentation on such implementation would be of great help to me. Thanks, Bala From oscar.j.benjamin at gmail.com Mon Sep 17 19:20:26 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Sep 2012 17:20:26 +0000 (UTC) Subject: [Tutor] combining c and python References: Message-ID: On 2012-09-17, Bala subramanian wrote: > Friends, > I code in python and so far able to write simple scripts for my needs. > Now i want to try the combination of c and python. > > 1) could someone please suggest me some good documentation on how > python and C can be combined. Some tutorials with simple examples. > > 2) If i know that a specific part (loop in my case) within my python > script consumes more processing time, is it possible to implement/use > 'c' only for that part. Precisely using C within python ? Any link for > documentation on such implementation would be of great help to me. > I would use cython for this: http://www.cython.org/ Cython allows you to write something that looks a lot like a python module but that gets translated into c, compiled with a c compiler and then turned into an extension module. Once compiled the extension module can be used from other scripts/modules just like an ordinary python module. But the code that was written in that module will often run a lot faster than ordinary python code particularly if you have an intensive but simple inner loop. Oscar From cfuller084 at thinkingplanet.net Mon Sep 17 19:43:30 2012 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 17 Sep 2012 12:43:30 -0500 Subject: [Tutor] combining c and python In-Reply-To: References: Message-ID: <201209171243.31319.cfuller084@thinkingplanet.net> The official documentation covers this in some detail: http://docs.python.org/extending/ http://docs.python.org/c-api/ Cython is an alternate implementation of Python. It's more of a blending of Python and C. It won't, in general, run Python source code or your favorite third-party library. To run C alongside Python, you need to use the API. You can interface Cython with straight C, of course, but not in a way that will work with the standard interpreter. Cheers On Monday 17 September 2012, Bala subramanian wrote: > Friends, > I code in python and so far able to write simple scripts for my needs. > Now i want to try the combination of c and python. > > 1) could someone please suggest me some good documentation on how > python and C can be combined. Some tutorials with simple examples. > > 2) If i know that a specific part (loop in my case) within my python > script consumes more processing time, is it possible to implement/use > 'c' only for that part. Precisely using C within python ? Any link for > documentation on such implementation would be of great help to me. > > Thanks, > Bala > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wprins at gmail.com Mon Sep 17 20:43:15 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 17 Sep 2012 19:43:15 +0100 Subject: [Tutor] combining c and python In-Reply-To: <201209171243.31319.cfuller084@thinkingplanet.net> References: <201209171243.31319.cfuller084@thinkingplanet.net> Message-ID: Hi Chris, On 17 September 2012 18:43, Chris Fuller wrote: > To run C alongside Python, you need to use the API. > > You can interface Cython with straight C, of course, but not in a way that > will work with the standard interpreter. Just to be clear, one of the main reasons for Cython's existence is to allow for the easy writing of CPython extension modules in a more or less Python like language which then gets compiled down to C for you (rather than you having to write the C yourself.) Another is to allow you to easily wrap C libraries in such a way as to allow you to make them accessible from CPython. Walter From computer_dude15 at hotmail.com Mon Sep 17 22:09:14 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Mon, 17 Sep 2012 16:09:14 -0400 Subject: [Tutor] simple random string generator In-Reply-To: References: Message-ID: thanks for everyone that gave me a hand...i think i got most of the program done... now i just need to time how long it takes to run each anagramSolution functions to see which one is faster...now i think i might have got it done but for some reason both lines are pretty close to the same.... http://pastie.org/4741560 thats my code...could someone let me know if i used time.time right to get accurate timing...to me it looks like it should be right but the one line i think is supposed to increas exponentially thanks :) _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaronpil at gmail.com Mon Sep 17 23:24:46 2012 From: aaronpil at gmail.com (Aaron Pilgrim) Date: Mon, 17 Sep 2012 14:24:46 -0700 Subject: [Tutor] Tutor Digest, Vol 103, Issue 82 In-Reply-To: References: Message-ID: > Message: 7 > Date: Mon, 17 Sep 2012 21:34:05 +0530 > From: Santosh Kumar > To: tutor > Subject: [Tutor] Trying to get next item from a list > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > Here is the script: > > alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', > 'z'] > i = input("Press any English alphabet: ") > current = alphabets.index(i) > print(current) > next = current+1 > print(next) > print(alphabets.index(next)) > > I am getting a ValueError. > > And as you can see, I just trying to get the next item. So is there > any way I can get same functionality in less line of codes? > > > ------------------------------ Hello, I am new to python. Here is what I wrote. my lower() function does not work and it can not take capital letters. def func3(): alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] i = input("Press any English alphabet: ") i.strip().lower() current = alphabets.index(i) print("current index value: ", current) next = (current + 1) % 26 print("next index value: ", next) print("The next letter is...", alphabets[next]) From d at davea.name Mon Sep 17 23:25:16 2012 From: d at davea.name (Dave Angel) Date: Mon, 17 Sep 2012 17:25:16 -0400 Subject: [Tutor] simple random string generator In-Reply-To: References: Message-ID: <5057953C.80801@davea.name> On 09/17/2012 04:09 PM, Matthew Dalrymple wrote: > thanks for everyone that gave me a hand...i think i got most of the program done... now i just need to time how long it takes to run each anagramSolution functions to see which one is faster...now i think i might have got it done but for some reason both lines are pretty close to the same.... http://pastie.org/4741560 thats my code...could someone let me know if i used time.time right to get accurate timing...to me it looks like it should be right but the one line i think is supposed to increas exponentially > thanks :) > > > Did you look for bugs before trying to time it? For example, did you intend that it test the sizes from 10 thru 195 in steps of 5, or did you intend from 10 to 100, as you stated in your first post? Would you care to add a docstring to those functions to indicate what they're intended to do? i think maybe the anagramSolutionX functions are supposed to return True if the two strings contain the same letters (including the same number of duplicates) in an arbitrary order. Are you interested in faster algorithms for such a comparison? I think that function could be implemented in two lines of Python, using only builtin functions. And that includes the def line. Did you intend to put the timings for anagramSolution2 into solu1, and the timings for anagramSolution1 into solu2, and thus print them out in reverse order? it makes it hard to see what difference incremental changes might make. -- DaveA From computer_dude15 at hotmail.com Mon Sep 17 23:40:26 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Mon, 17 Sep 2012 17:40:26 -0400 Subject: [Tutor] simple random string generator In-Reply-To: <5057953C.80801@davea.name> References: , <5057953C.80801@davea.name> Message-ID: > > > > > > Did you look for bugs before trying to time it? For example, did you > intend that it test the sizes from 10 thru 195 in steps of 5, or did you > intend from 10 to 100, as you stated in your first post? > > Would you care to add a docstring to those functions to indicate what > they're intended to do? i think maybe the anagramSolutionX functions > are supposed to return True if the two strings contain the same letters > (including the same number of duplicates) in an arbitrary order. > > Are you interested in faster algorithms for such a comparison? I think > that function could be implemented in two lines of Python, using only > builtin functions. And that includes the def line. > > Did you intend to put the timings for anagramSolution2 into solu1, and > the timings for anagramSolution1 into solu2, and thus print them out in > reverse order? it makes it hard to see what difference incremental > changes might make. > > > > -- > > DaveA > its for a class...we were given the anagramSolutionX functions...we have to comapre those using time.time() and get accurate reading by running each function at least 10000 times to each word from 10 to 100 in steps of 5. i went up to 200 just to see if one would increase faster as the number increased but it didn't...also i realized i had the solutions labled wrong so i was starting to switch them and didnt finish :S sorry... before i started trying to time it, it ran creating words from 10-100 in steps of 5... make sense? the assignment we were given was to create a mkword(n) function and get it to generate the strings from 10-100 in steps of 5 and check to see which solution would be faster... -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Mon Sep 17 23:50:28 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 18 Sep 2012 09:50:28 +1200 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: <50569841.2090006@pearwood.info> Message-ID: > 1) You have a Bezier curver consisting of 20 control points and would like > to > approximate it with a simpler cubic Bezier curve consisting of only 4 > points. > I would call this "approximating a Bezier with a lower order Bezier". > > Hi Oscar. Thanks for your reply. This one above is the one that I am trying to do. It is true that choosing arbitrary points evenly selected from the original points is not ideal, it is good enough for my purposes in most cases. When I have a bit more time I am going to try to implement the Ramer?Douglas?Peucker algorithm to improve the accuracy of my curve simplification: http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm Thanks Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen at averagesecurityguy.info Mon Sep 17 23:59:17 2012 From: stephen at averagesecurityguy.info (Stephen Haywood) Date: Mon, 17 Sep 2012 17:59:17 -0400 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: <50569841.2090006@pearwood.info> Message-ID: Someone has already tried. https://github.com/sebleier/RDP On Mon, Sep 17, 2012 at 5:50 PM, Pete O'Connell wrote: > When I have a bit more time I am going to try to implement the > Ramer?Douglas?Peucker algorithm to improve the accuracy of my curve > simplification: > > http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm > > > -- Stephen Haywood Information Security Consultant CISSP, GPEN, OSCP T: @averagesecguy W: averagesecurityguy.info -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Sep 18 00:11:44 2012 From: d at davea.name (Dave Angel) Date: Mon, 17 Sep 2012 18:11:44 -0400 Subject: [Tutor] Tutor Digest, Vol 103, Issue 82 In-Reply-To: References: Message-ID: <5057A020.7070704@davea.name> On 09/17/2012 05:24 PM, Aaron Pilgrim wrote: Why are you replying to a digest? Reply to one of the messages on the thread you're responding to, and it'll get the subject line right. It'll also thread it together. >> Message: 7 >> Date: Mon, 17 Sep 2012 21:34:05 +0530 >> From: Santosh Kumar >> To: tutor >> Subject: [Tutor] Trying to get next item from a list >> Message-ID: >> >> Content-Type: text/plain; charset=UTF-8 >> >> Here is the script: >> >> alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', >> 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', >> 'z'] >> i = input("Press any English alphabet: ") >> current = alphabets.index(i) >> print(current) >> next = current+1 >> print(next) >> print(alphabets.index(next)) >> >> I am getting a ValueError. >> >> And as you can see, I just trying to get the next item. So is there >> any way I can get same functionality in less line of codes? >> >> >> ------------------------------ > Hello, I am new to python. > Here is what I wrote. > my lower() function does not work and it can not take capital letters. > > def func3(): > alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', > 'z'] > i = input("Press any English alphabet: ") > i.strip().lower() What makes you think lower() doesn't work? You haven't used it yet. Try i = i.strip().lower() > current = alphabets.index(i) > print("current index value: ", current) > next = (current + 1) % 26 > print("next index value: ", next) > print("The next letter is...", alphabets[next]) > -- DaveA From emile at fenx.com Tue Sep 18 00:16:08 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 17 Sep 2012 15:16:08 -0700 Subject: [Tutor] Tutor Digest, Vol 103, Issue 82 In-Reply-To: References: Message-ID: On 9/17/2012 2:24 PM Aaron Pilgrim said... > Hello, I am new to python. > Here is what I wrote. > my lower() function does not work and it can not take capital letters. > > def func3(): > alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', > 'z'] > i = input("Press any English alphabet: ") > i.strip().lower() the preceeding line doesn't change i like you expect. Try it as i = i.strip().lower() HTH, Emile > current = alphabets.index(i) > print("current index value: ", current) > next = (current + 1) % 26 > print("next index value: ", next) > print("The next letter is...", alphabets[next]) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From d at davea.name Tue Sep 18 00:19:50 2012 From: d at davea.name (Dave Angel) Date: Mon, 17 Sep 2012 18:19:50 -0400 Subject: [Tutor] simple random string generator In-Reply-To: References: , <5057953C.80801@davea.name> Message-ID: <5057A206.2080502@davea.name> On 09/17/2012 05:40 PM, Matthew Dalrymple wrote: > > >>> >>> >> >> Did you look for bugs before trying to time it? For example, did you >> intend that it test the sizes from 10 thru 195 in steps of 5, or did you >> intend from 10 to 100, as you stated in your first post? >> >> Would you care to add a docstring to those functions to indicate what >> they're intended to do? i think maybe the anagramSolutionX functions >> are supposed to return True if the two strings contain the same letters >> (including the same number of duplicates) in an arbitrary order. >> >> Are you interested in faster algorithms for such a comparison? I think >> that function could be implemented in two lines of Python, using only >> builtin functions. And that includes the def line. >> >> Did you intend to put the timings for anagramSolution2 into solu1, and >> the timings for anagramSolution1 into solu2, and thus print them out in >> reverse order? it makes it hard to see what difference incremental >> changes might make. >> >> >> >> -- >> >> DaveA >> its for a class...we were given the anagramSolutionX functions...we have to comapre those using time.time() and get accurate reading by running each function at least 10000 times to each word from 10 to 100 in steps of 5. i went up to 200 just to see if one would increase faster as the number increased but it didn't...also i realized i had the solutions labled wrong so i was starting to switch them and didnt finish :S sorry... before i started trying to time it, it ran creating words from 10-100 in steps of 5... make sense? the assignment we were given was to create a mkword(n) function and get it to generate the strings from 10-100 in steps of 5 and check to see which solution would be faster... > > Do you realize the the difference between open-ended and closed? When you put the 200 there, the last one it'll do is 195. Likewise, if you said range(10, 100, 5), it would stop at 95. That's why Steven had the +1 in his first message. -- DaveA From computer_dude15 at hotmail.com Tue Sep 18 00:22:00 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Mon, 17 Sep 2012 18:22:00 -0400 Subject: [Tutor] simple random string generator In-Reply-To: <5057A206.2080502@davea.name> References: , <5057953C.80801@davea.name> , <5057A206.2080502@davea.name> Message-ID: oh :S ok im sorry...i will change that thenthanks > Date: Mon, 17 Sep 2012 18:19:50 -0400 > From: d at davea.name > To: computer_dude15 at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] simple random string generator > > On 09/17/2012 05:40 PM, Matthew Dalrymple wrote: > > > > > >>> > >>> > >> > >> Did you look for bugs before trying to time it? For example, did you > >> intend that it test the sizes from 10 thru 195 in steps of 5, or did you > >> intend from 10 to 100, as you stated in your first post? > >> > >> Would you care to add a docstring to those functions to indicate what > >> they're intended to do? i think maybe the anagramSolutionX functions > >> are supposed to return True if the two strings contain the same letters > >> (including the same number of duplicates) in an arbitrary order. > >> > >> Are you interested in faster algorithms for such a comparison? I think > >> that function could be implemented in two lines of Python, using only > >> builtin functions. And that includes the def line. > >> > >> Did you intend to put the timings for anagramSolution2 into solu1, and > >> the timings for anagramSolution1 into solu2, and thus print them out in > >> reverse order? it makes it hard to see what difference incremental > >> changes might make. > >> > >> > >> > >> -- > >> > >> DaveA > >> its for a class...we were given the anagramSolutionX functions...we have to comapre those using time.time() and get accurate reading by running each function at least 10000 times to each word from 10 to 100 in steps of 5. i went up to 200 just to see if one would increase faster as the number increased but it didn't...also i realized i had the solutions labled wrong so i was starting to switch them and didnt finish :S sorry... before i started trying to time it, it ran creating words from 10-100 in steps of 5... make sense? the assignment we were given was to create a mkword(n) function and get it to generate the strings from 10-100 in steps of 5 and check to see which solution would be faster... > > > > > > Do you realize the the difference between open-ended and closed? When > you put the 200 there, the last one it'll do is 195. Likewise, if you > said range(10, 100, 5), it would stop at 95. That's why Steven had the > +1 in his first message. > > > > -- > > DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 18 01:54:56 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Sep 2012 23:54:56 +0000 (UTC) Subject: [Tutor] combining c and python References: <201209171243.31319.cfuller084@thinkingplanet.net> Message-ID: On 2012-09-17, Walter Prins wrote: > Hi Chris, > > On 17 September 2012 18:43, Chris Fuller > wrote: >> To run C alongside Python, you need to use the API. >> >> You can interface Cython with straight C, of course, but not in a way that >> will work with the standard interpreter. > > Just to be clear, one of the main reasons for Cython's existence is to > allow for the easy writing of CPython extension modules in a more or > less Python like language which then gets compiled down to C for you > (rather than you having to write the C yourself.) Another is to allow > you to easily wrap C libraries in such a way as to allow you to make > them accessible from CPython. Yeah, as a regular Cython user I'm not sure if I really understand Chris' comments there. Cython uses precisely that C-API to create the extension modules it makes. If you've ever used the same C-API manually you'll understand why Cython exists to make it easier. Also, Cython *only* works with the standard interpreter (the latest release claims alpha quality support for PyPy but I haven't tested that myself). Oscar From steve at pearwood.info Tue Sep 18 03:59:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Sep 2012 11:59:47 +1000 Subject: [Tutor] simple random string generator In-Reply-To: References: Message-ID: <5057D593.2040709@pearwood.info> On 18/09/12 06:09, Matthew Dalrymple wrote: > > thanks for everyone that gave me a hand...i think i got most of the program >done... now i just need to time how long it takes to run each >anagramSolution functions to see which one is faster...now i think i might >have got it done but for some reason both lines are pretty close to the >same.... http://pastie.org/4741560 thats my code...could someone let me know > if i used time.time right to get accurate timing... Look at what your timing code does: start = time.time() for i in range(10000): anagramSolution2(word,word) end1 = time.time() solu2 = end1 - start Translated into English: * start the timer * iteration 1 begins * call the anagram function * grab the ending time * calculate the difference in time * iteration 2 begins * call the anagram function * grab the ending time * calculate the difference in time * iteration 3 begins * call the anagram function * grab the ending time * calculate the difference in time ... and so on ... * iteration 10000 begins * call the anagram function * grab the ending time * calculate the difference in time and finally you are done. Do you see what you have done? You calculate the time difference 10000 times instead of once. What you want is: * start the timer * iteration 1 begins * call the anagram function * iteration 2 begins * call the anagram function * iteration 3 begins * call the anagram function ... and so on ... * iteration 10000 begins * call the anagram function * grab the ending time * calculate the difference in time You should calculate the difference in time ONCE, not 10000 times. > to me it looks like it should be right but the one line i think >is supposed to increas exponentially I'm not sure why you think that. I'm not saying that it shouldn't, but I honestly can't tell. The code is so convoluted that I'm not sure what it does without detailed study, but at a quick glance I can't see anything that would make one of the anagram functions take O(N**2) time. -- Steven From scott.yamamoto at yahoo.com Tue Sep 18 05:11:06 2012 From: scott.yamamoto at yahoo.com (Scott Yamamoto) Date: Mon, 17 Sep 2012 20:11:06 -0700 (PDT) Subject: [Tutor] Input handling? Message-ID: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> I've been trying to find possible erros with input(such as NameError or SyntaxError) to handle them with an except clause. however, I've found that hitting enter/return while prompted without inputting creates some kind of problem. >>>username = raw_input("Input a username: ") Input a username: #hits enter, encounter problem here. Loops forever or something Using python for ios -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.yamamoto at yahoo.com Tue Sep 18 05:33:18 2012 From: scott.yamamoto at yahoo.com (Scott Yamamoto) Date: Mon, 17 Sep 2012 20:33:18 -0700 (PDT) Subject: [Tutor] Input handling? Message-ID: <1347939198.62209.YahooMailMobile@web164005.mail.gq1.yahoo.com> Didnt show up at first. Result was an eof error (using input not raw_input) Found with interactive interpreter -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Sep 18 06:04:22 2012 From: d at davea.name (Dave Angel) Date: Tue, 18 Sep 2012 00:04:22 -0400 Subject: [Tutor] Input handling? In-Reply-To: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> References: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> Message-ID: <5057F2C6.6000806@davea.name> On 09/17/2012 11:11 PM, Scott Yamamoto wrote: > I've been trying to find possible erros with input(such as NameError or SyntaxError) to handle them with an except clause. however, I've found that hitting enter/return while prompted without inputting creates some kind of problem. >>>> username = raw_input("Input a username: ") > Input a username: #hits enter, encounter problem here. Loops forever or something > > Using python for ios > Somehow you managed to put your other message in its own thread, instead of adding to this one. What version of Python are you running? If it's 2.x, and if you're using input(), then you're doing a (hazardous) eval on whatever the user types. So if the user doesn't type a valid expression, or if that expression doesn't evaluate to a number, you'll get some exception. Clearly, you want raw_input(), which is looking for a string, and doesn't mind empty strings from the user. It would be useful (in the future) if you clearly stated what version of Python you're using, what exactly was included in your script, and what exception you got, with full traceback. Much more useful to diagnose than a vague - "some kind of problem." -- DaveA From scott.yamamoto at yahoo.com Tue Sep 18 06:19:41 2012 From: scott.yamamoto at yahoo.com (Scott Yamamoto) Date: Mon, 17 Sep 2012 21:19:41 -0700 (PDT) Subject: [Tutor] Input handling? Message-ID: <1347941981.53659.YahooMailMobile@web164005.mail.gq1.yahoo.com> 2.7.2 on python for ios(platform is darwin) problem reoccured Script: import random username = "" def playername(): global username Mlist = ["name1","name2","name3"] Flist = ["name4","name5", "name6"] Llist = ["Lname1","Lname2","Lname3"] username = raw_input("input your desired username: ") if username == "": username = random.choice(Mlist) + " " + random.choice(Llist) playername() Doesnt return the error during run Attempting implementation of try results in indentation errors in later lines -------------- next part -------------- An HTML attachment was scrubbed... URL: From computer_dude15 at hotmail.com Tue Sep 18 06:22:14 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Tue, 18 Sep 2012 00:22:14 -0400 Subject: [Tutor] simple random string generator In-Reply-To: <5057D593.2040709@pearwood.info> References: , , <5057D593.2040709@pearwood.info> Message-ID: > Look at what your timing code does: > > start = time.time() > for i in range(10000): > anagramSolution2(word,word) > end1 = time.time() > solu2 = end1 - start > > > Translated into English: > > * start the timer > * iteration 1 begins > * call the anagram function > * grab the ending time > * calculate the difference in time > * iteration 2 begins > * call the anagram function > * grab the ending time > * calculate the difference in time > * iteration 3 begins > * call the anagram function > * grab the ending time > * calculate the difference in time > ... and so on ... > * iteration 10000 begins > * call the anagram function > * grab the ending time > * calculate the difference in time > > and finally you are done. Do you see what you have done? You calculate > the time difference 10000 times instead of once. What you want is: > > * start the timer > * iteration 1 begins > * call the anagram function > * iteration 2 begins > * call the anagram function > * iteration 3 begins > * call the anagram function > ... and so on ... > * iteration 10000 begins > * call the anagram function > * grab the ending time > * calculate the difference in time > > You should calculate the difference in time ONCE, not 10000 times. so what should be done then would be to make sure that the start and end time are like this? for n in range(10, 101, 5): word = mkword(n) start = time.time() for i in range(10000): anagramSolutionX(word,word, end1 = time.time() solu2 = end1 - start is that right?sorry if im making this harder than it should be to me that would make sense because you would be asking it to do it 10000 times before it would move on to the end time? thanks again for all the help guysit means a lot > > > > to me it looks like it should be right but the one line i think > >is supposed to increas exponentially > > I'm not sure why you think that. I'm not saying that it shouldn't, > but I honestly can't tell. The code is so convoluted that I'm not > sure what it does without detailed study, but at a quick glance I > can't see anything that would make one of the anagram functions > take O(N**2) time. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Sep 18 07:15:49 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Sep 2012 06:15:49 +0100 Subject: [Tutor] simple random string generator In-Reply-To: References: , , <5057D593.2040709@pearwood.info> Message-ID: @Matthew Dalrymple I don't know what is happening but that's at least two messages from you that show precisely nothing, just original comments from others. Anyone else seeing the same thing? I'm reading through gmane on Windows Vista with Thunderbird. -- Cheers. Mark Lawrence. From d at davea.name Tue Sep 18 07:24:46 2012 From: d at davea.name (Dave Angel) Date: Tue, 18 Sep 2012 01:24:46 -0400 Subject: [Tutor] simple random string generator In-Reply-To: References: , , <5057D593.2040709@pearwood.info> Message-ID: <5058059E.7080705@davea.name> On 09/18/2012 01:15 AM, Mark Lawrence wrote: > @Matthew Dalrymple I don't know what is happening but that's at least > two messages from you that show precisely nothing, just original > comments from others. Anyone else seeing the same thing? I'm reading > through gmane on Windows Vista with Thunderbird. > I had already sent Matthew a message advising him to hit enter (to get a blank line), so that his remarks aren't just mixed in with the ones he's replying to. If you look closely, you can find his remarks beginning with the phrase "so what should be done..." You can recognize it the lack of capitalization or paragraph boundaries. -- DaveA From steve at pearwood.info Tue Sep 18 08:12:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Sep 2012 16:12:22 +1000 Subject: [Tutor] Input handling? In-Reply-To: <5057F2C6.6000806@davea.name> References: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> <5057F2C6.6000806@davea.name> Message-ID: <20120918061221.GA31290@ando> On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote: > On 09/17/2012 11:11 PM, Scott Yamamoto wrote: > > I've been trying to find possible erros with input(such as NameError or SyntaxError) to handle them with an except clause. however, I've found that hitting enter/return while prompted without inputting creates some kind of problem. > >>>> username = raw_input("Input a username: ") > > Input a username: #hits enter, encounter problem here. Loops forever or something > > > > Using python for ios > > > > Somehow you managed to put your other message in its own thread, instead > of adding to this one. Not all mail clients support threading, either when receiving or sending. But my mail client, mutt, shows Scott's emails threaded correctly. Perhaps your mail client is broken? What are you using? > What version of Python are you running? If it's 2.x, and if you're > using input(), Given that the OP clearly shows username = raw_input("Input a username: ") I think that we can safely assume that he is not using 2.x's input :) -- Steven From steve at pearwood.info Tue Sep 18 08:21:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Sep 2012 16:21:50 +1000 Subject: [Tutor] Input handling? In-Reply-To: <1347941981.53659.YahooMailMobile@web164005.mail.gq1.yahoo.com> References: <1347941981.53659.YahooMailMobile@web164005.mail.gq1.yahoo.com> Message-ID: <20120918062150.GB31290@ando> On Mon, Sep 17, 2012 at 09:19:41PM -0700, Scott Yamamoto wrote: > 2.7.2 on python for ios(platform is darwin) > problem reoccured What problem? Your code works for me. Please describe: 1) what you expect to happen 2) what actually happens 3) if there is a traceback, COPY AND PASTE the ENTIRE traceback, do not summarise or abbreviate it. > Script: > > import random > username = "" > def playername(): > global username > Mlist = ["name1","name2","name3"] > Flist = ["name4","name5", "name6"] > Llist = ["Lname1","Lname2","Lname3"] > username = raw_input("input your desired username: ") > if username == "": > username = random.choice(Mlist) + " " + random.choice(Llist) > playername() > Doesnt return the error during run > Attempting implementation of try results in indentation errors in later lines That's because your attempt to implement try is broken. But why are you using a try? If your function has a bug, FIX THE BUG, don't just cover it up with a try...except. -- Steven From d at davea.name Tue Sep 18 08:33:13 2012 From: d at davea.name (Dave Angel) Date: Tue, 18 Sep 2012 02:33:13 -0400 Subject: [Tutor] Input handling? In-Reply-To: <20120918061221.GA31290@ando> References: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> <5057F2C6.6000806@davea.name> <20120918061221.GA31290@ando> Message-ID: <505815A9.7060703@davea.name> On 09/18/2012 02:12 AM, Steven D'Aprano wrote: > On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote: >> On 09/17/2012 11:11 PM, Scott Yamamoto wrote: >>> I've been trying to find possible erros with input(such as NameError or SyntaxError) to handle them with an except clause. however, I've found that hitting enter/return while prompted without inputting creates some kind of problem. >>>>>> username = raw_input("Input a username: ") >>> Input a username: #hits enter, encounter problem here. Loops forever or something >>> >>> Using python for ios >>> >> Somehow you managed to put your other message in its own thread, instead >> of adding to this one. > Not all mail clients support threading, either when receiving or > sending. > > But my mail client, mutt, shows Scott's emails threaded correctly. > Perhaps your mail client is broken? What are you using? > > I'm using Thunderbird 14 on Linux, and I'd love help in diagnosing why some messages get properly threaded, and some do not. For example, I've seen several of your replies (not a very big fraction) apparently start new threads. And I've seen many other messages which didn't get in the proper place in the thread, appearing at the same level as the message they were replies to. I will be upgrading to latest Thunderbird, but I'm planning on installing a new Linux on a new hard disk, and haven't really gotten started yet. >> What version of Python are you running? If it's 2.x, and if you're >> using input(), > Given that the OP clearly shows > > username = raw_input("Input a username: ") > > I think that we can safely assume that he is not using 2.x's input :) > His first message showed one line, typed in the interpreter, with no clear statement of environment or problem. However, the statement did mention the input function. I'd have disbelieved it except that... His second message specifically changes to input. Here it is again, for our confusion: """Didnt show up at first. Result was an eof error (using input not raw_input) Found with interactive interpreter """ I would have been replying to that one, except that it apparently started a new thread, as did his third message. That third one went back to using raw_input, but it was a reply to my message stating the hazards of input on Python 2.x -- DaveA From wescpy at gmail.com Tue Sep 18 09:25:50 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 18 Sep 2012 00:25:50 -0700 Subject: [Tutor] combining c and python In-Reply-To: References: Message-ID: another option that no one has mentioned yet is the use of 'ctypes' with existing C libraries: http://docs.python.org/library/ctypes cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com From pedrooconnell at gmail.com Tue Sep 18 09:47:01 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 18 Sep 2012 19:47:01 +1200 Subject: [Tutor] reducing a list evenly when deleting elements by index In-Reply-To: References: <50569841.2090006@pearwood.info> Message-ID: Thanks Stephen. That looks like nice clean code too! Cheers Pete On Tue, Sep 18, 2012 at 9:59 AM, Stephen Haywood < stephen at averagesecurityguy.info> wrote: > Someone has already tried. https://github.com/sebleier/RDP > > > On Mon, Sep 17, 2012 at 5:50 PM, Pete O'Connell wrote: > >> When I have a bit more time I am going to try to implement the >> Ramer?Douglas?Peucker algorithm to improve the accuracy of my curve >> simplification: >> >> http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm >> >> >> > -- > Stephen Haywood > Information Security Consultant > CISSP, GPEN, OSCP > T: @averagesecguy > W: averagesecurityguy.info > > -- - -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 18 11:02:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Sep 2012 10:02:06 +0100 Subject: [Tutor] Input handling? In-Reply-To: <20120918061221.GA31290@ando> References: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> <5057F2C6.6000806@davea.name> <20120918061221.GA31290@ando> Message-ID: On Sep 18, 2012 7:14 AM, "Steven D'Aprano" wrote: > > On Tue, Sep 18, 2012 at 12:04:22AM -0400, Dave Angel wrote: > > Somehow you managed to put your other message in its own thread, instead > > of adding to this one. > > Not all mail clients support threading, either when receiving or > sending. > > But my mail client, mutt, shows Scott's emails threaded correctly. > Perhaps your mail client is broken? What are you using? Mutt goes above and beyond a correct implementation of threading by using heuristics to fix broken threads. I know it parses the subject line but I'm not sure what else it uses. The upshot is that if you use mutt you won't see the same thing that would be shown in a client that has a strict interpretation of threading (unless you disable the heuristics in your muttrc). Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 18 11:05:27 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Sep 2012 10:05:27 +0100 Subject: [Tutor] Input handling? In-Reply-To: References: <1347937866.60757.YahooMailMobile@web164003.mail.gq1.yahoo.com> <5057F2C6.6000806@davea.name> <20120918061221.GA31290@ando> Message-ID: On Sep 18, 2012 10:02 AM, "Oscar Benjamin" wrote: > > > On Sep 18, 2012 7:14 AM, "Steven D'Aprano" wrote: > > Apologies for gmail screwing up your name. I wish I could use mutt on this machine. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 18 12:02:29 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 18 Sep 2012 06:02:29 -0400 Subject: [Tutor] simple random string generator In-Reply-To: <5058059E.7080705@davea.name> References: <5057D593.2040709@pearwood.info> <5058059E.7080705@davea.name> Message-ID: On Tue, Sep 18, 2012 at 1:24 AM, Dave Angel wrote: > On 09/18/2012 01:15 AM, Mark Lawrence wrote: >> @Matthew Dalrymple I don't know what is happening but that's at least >> two messages from you that show precisely nothing, just original >> comments from others. Anyone else seeing the same thing? I'm reading >> through gmane on Windows Vista with Thunderbird. > > I had already sent Matthew a message advising him to hit enter (to get a > blank line), so that his remarks aren't just mixed in with the ones he's > replying to. If you look closely, you can find his remarks beginning > with the phrase "so what should be done..." You can recognize it the > lack of capitalization or paragraph boundaries. It's HTML:
 =3B
so what should be done then would be to make sure that the start and end time are like this?
 =3B
for n in range(10=2C 101=2C 5):
 =3B =3B =3B word =3D mkword(n)
 =3B =3B =3B start =3D time.time()
 =3B =3B =3B for i in range(10000):
 =3B =3B =3B  =3B =3B =3B =3B anagramSolutionX(word=2Cword=2C
 =3B =3B =3B end1 =3D time.time()
 =3B =3B =3B solu2 =3D end1 - start
 =3B
is that right?
sorry if im making this harder than it should be
 =3B
to me that would make sense because you would be asking it to do it 10000 times before it would move on to the end time?
 =3B
thanks again for all the help guys
it means a lot From mjldehoon at yahoo.com Tue Sep 18 16:14:26 2012 From: mjldehoon at yahoo.com (Michiel de Hoon) Date: Tue, 18 Sep 2012 07:14:26 -0700 (PDT) Subject: [Tutor] Storing information as attributes or in a dictionary Message-ID: <1347977666.50257.YahooMailClassic@web164005.mail.gq1.yahoo.com> Dear all, Suppose I have a parser that parses information stored in e.g. an XML file. I would like to design a Python class to store the information contained in this XML file. One option is to create a class like this: class Record(object): pass and store the information in the XML file as attributes of objects of this class, as in >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record.name "John Doe" >>> record.birthday "February 1, 1920" Alternatively I could subclass the dictionary class: class Record(dict): pass and have something like >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record['name'] "John Doe" >>> record['birthday'] "February 1, 1920" I can see some advantage to using a dictionary, because it allows me to use the same strings as keys in the dictionary as in used in the XML file itself. But are there some general guidelines for when to use a dictionary-like class, and when to use attributes to store information? In particular, are there any situations where there is some advantage in using attributes? Thanks, -Michiel. From computer_dude15 at hotmail.com Tue Sep 18 16:38:48 2012 From: computer_dude15 at hotmail.com (Matthew Dalrymple) Date: Tue, 18 Sep 2012 10:38:48 -0400 Subject: [Tutor] simple random string generator In-Reply-To: References: , , , , <5057D593.2040709@pearwood.info>, , Message-ID: I wanna apologize about the emails...idk y some people can't see what I was saying...I'm just using my hotmail account...I did try to bold what I was saying but I guess that converts it to HTML I appreciate u guys being patient with me and I'm sorry for any trouble that had occurred due to this Thanks for all of your help Matt > To: tutor at python.org > From: breamoreboy at yahoo.co.uk > Date: Tue, 18 Sep 2012 06:15:49 +0100 > Subject: Re: [Tutor] simple random string generator > > @Matthew Dalrymple I don't know what is happening but that's at least > two messages from you that show precisely nothing, just original > comments from others. Anyone else seeing the same thing? I'm reading > through gmane on Windows Vista with Thunderbird. > > -- > Cheers. > > Mark Lawrence. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Sep 18 16:49:08 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Sep 2012 15:49:08 +0100 Subject: [Tutor] Storing information as attributes or in a dictionary In-Reply-To: <1347977666.50257.YahooMailClassic@web164005.mail.gq1.yahoo.com> References: <1347977666.50257.YahooMailClassic@web164005.mail.gq1.yahoo.com> Message-ID: On 18 September 2012 15:14, Michiel de Hoon wrote: > Dear all, > > Suppose I have a parser that parses information stored in e.g. an XML > file. I would like to design a Python class to store the information > contained in this XML file. > > One option is to create a class like this: > > class Record(object): > pass > > and store the information in the XML file as attributes of objects of this > class, as in > > >>> handle = open("myxmlfile.xml") > >>> record = parse(handle) # returns a Record object > >>> record.name > "John Doe" > >>> record.birthday > "February 1, 1920" > > Alternatively I could subclass the dictionary class: > > class Record(dict): > pass > > and have something like > > >>> handle = open("myxmlfile.xml") > >>> record = parse(handle) # returns a Record object > >>> record['name'] > "John Doe" > >>> record['birthday'] > "February 1, 1920" > > I can see some advantage to using a dictionary, because it allows me to > use the same strings as keys in the dictionary as in used in the XML file > itself. But are there some general guidelines for when to use a > dictionary-like class, and when to use attributes to store information? In > particular, are there any situations where there is some advantage in using > attributes? > Some people find attribute access a bit "nicer" when they are using an object. Attributes have the disadvantage that they're a bit awkward if they aren't valid identifiers, where as any string is ok for a dictionary key. A valid identifier is any string... 1) consisting only of alphanumeric characters (a-z, A-Z, 0-9) and the underscore (_) 2) that does not begin with a numeric character (0-9). 3) and that is not a Python keyword (is, not, and, def, class, ...). To see what happens otherwise: >>> class A(object): pass ... >>> a = A() >>> a.class = 'some value' File "", line 1 a.class = 'some value' ^ SyntaxError: invalid syntax Also if your objects are instances of a class that has any methods you'll need to ensure that the method names don't conflict with the XML keys as well. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.yamamoto at yahoo.com Tue Sep 18 19:23:39 2012 From: scott.yamamoto at yahoo.com (Scott Yamamoto) Date: Tue, 18 Sep 2012 10:23:39 -0700 (PDT) Subject: [Tutor] Input handling? Message-ID: <1347989019.78203.YahooMailMobile@web164002.mail.gq1.yahoo.com> 0) using mobile yahoo mail 1) expect: raw_input to assign the variable to "" 2)No output to stderr; has a loading symbol after hitting enter without input (tried both input and raw_input) Doesn't affect active interpreter. Only affects the screen with the run option. 3) def simulation(): ? import random ? from random import randrange ? from time import sleep ? print "Welcome to The World." ? sleep(1) ? print "Now Loading..." ? sleep(1.5) ? #Intro page ? print ? gender = raw_input("Gender: male/female \n") ? if gender != "male" or "female": ? ? gender = "male" ? Mlist = ["Jacob", "Mason", "William", "Jayden", "Noah", "Michael", "Ethan", "Alexander", "Aiden", "Daniel", "Anthony", "Matthew", "Elijah", "Joshua", "Liam", "Andrew", "James", "David", "Benjamin", "Logan"] ? Flist = ["Sophia", "Isabella", "Emma", "Olivia", "Ava", "Emily", "Abigail", "Madison", "Mia", "Chloe", "Elizabeth", "Ella", "Addison", "Natalie", "Lily", "Grace", "Samantha", "Avery", "Sofia", "Aubrey"] ? Llist = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Pavis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson"] ? username = raw_input("Input your full name: \n") ? if username == "": ? ? if gender == "male": ? ? ? username = random.choice(Mlist) + " " + random.choice(Llist) ? ? else: ? ? ? username = random.choice(Flist) + " " + random.choice(Llist) ? print ? print "Username: %s. Gender: %s." % (username,gender) simulation() -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 18 21:48:46 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 18 Sep 2012 15:48:46 -0400 Subject: [Tutor] Input handling? In-Reply-To: <1347989019.78203.YahooMailMobile@web164002.mail.gq1.yahoo.com> References: <1347989019.78203.YahooMailMobile@web164002.mail.gq1.yahoo.com> Message-ID: On Tue, Sep 18, 2012 at 1:23 PM, Scott Yamamoto wrote: > > 1) expect: raw_input to assign the variable to "" > 2)No output to stderr; has a loading symbol after hitting enter without input > (tried both input and raw_input) > Doesn't affect active interpreter. Only affects the screen with the run option. > 3) Except for a bug your code worked for me in Python 2.7.3. > def simulation(): > import random > from random import randrange > from time import sleep You're not using randrange, plus you should move the imports to the top of your module. > gender = raw_input("Gender: male/female \n") > if gender != "male" or "female": > gender = "male" This is the bug. You have the test expression "expr1 or expr2" where expr1 is "gender != male" and expr2 is "female". A non-empty string is always True by definition, so your test amounts to "expr1 or True", which means the "if" block always executes. > Mlist = ["Jacob", "Mason", "William", ...] > Flist = ["Sophia", "Isabella", "Emma", ...] > Llist = ["Smith", "Johnson", "Williams", ...] Consider moving these lists out of the function. They can all go nicely in a dict, which you can set as a default argument. > username = raw_input("Input your full name: \n") > if username == "": > if gender == "male": > username = random.choice(Mlist) + " " + random.choice(Llist) > else: > username = random.choice(Flist) + " " + random.choice(Llist) Using a dict for the names eliminates the need to test gender here. For example: import random import time names = { "male": [ "Jacob", "Mason", "William", "Jayden", "Noah", "Michael", "Ethan", "Alexander", "Aiden", "Daniel", "Anthony", "Matthew", "Elijah", "Joshua", "Liam", "Andrew", "James", "David", "Benjamin", "Logan", ], "female": [ "Sophia", "Isabella", "Emma", "Olivia", "Ava", "Emily", "Abigail", "Madison", "Mia", "Chloe", "Elizabeth", "Ella", "Addison", "Natalie", "Lily", "Grace", "Samantha", "Avery", "Sofia", "Aubrey", ], "last": [ "Smith", "Johnson", "Williams", "Jones", "Brown", "Pavis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson", ], } def simulation(names=names): print "Welcome to The World." time.sleep(1) print "Now Loading..." time.sleep(1.5) # Intro page gender = raw_input("\nGender [male|female]:\n").strip() if gender not in ("male", "female"): gender = "male" username = raw_input("Input your full name:\n") if not username: username = " ".join( random.choice(n) for n in (names[gender], names["last"])) print "\nUsername: %s. Gender: %s." % (username, gender) From scott.yamamoto at yahoo.com Wed Sep 19 00:46:09 2012 From: scott.yamamoto at yahoo.com (Scott Yamamoto) Date: Tue, 18 Sep 2012 15:46:09 -0700 (PDT) Subject: [Tutor] Input handling? Message-ID: <1348008369.41054.YahooMailMobile@web164002.mail.gq1.yahoo.com> Thanks for everything. I'll keep this in mind as I continue coding. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnj091405 at gmail.com Wed Sep 19 02:12:53 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Tue, 18 Sep 2012 17:12:53 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. Message-ID: I teach at a college and I'm trying to use Python (2.6 because I'm running my tool in ArcGIS) to unzip a .zip file that contains one folder full of student folders, each with 1 or more submissions (zipfiles) that represent student submissions to weekly lab assignments. It all starts with an originalzip.zip (for example) that has a single folder (originalfolder) Within the 'originalfolder' folder there are anywhere from 1 - 40 folders (that are not zipped). (these are the students userid folders) Within each of the (1-40) student userid folders is anywhere from 1-10 zipfiles and perhaps a .pdf or .docx (if for example they submitted more than one revision of the assignment, there are more than 1) Folder Structure originalzip.zip --originalfolder --folder1 (w/ two zip folders) --internalzip1_a.zip --internalfolder1_a --files --folders --internalzip1_b.zip --internalfolder1_b --files --folders --folder2 (w/1 zip folder) --internalzip2.zip --internalfolder2 --files --folders --etc.... My goal is to: a) Unzip the 'originalzip.zip' b) go to the 'originalfolder' (the unzipped version of the originalzip.zip) c) go into the first folder (folder1) in the original folder and unzip any and all zipfiles within it d) go to the second folder (folder2) in the original folder and unzip any and all zipfiles within it e) continue until all folders within originalfolders have been checked for internalzips ### Note, I am a beginner both with this tutor environment and in python. I apologize in advance if my code below is 'not up to par' but I am trying to keep it simple in nature and use ample comments to keep track of what I am doing. I also don't know if I should post sample data (zipfile of a folder of folders with zipfiles), and if so, where? I have some code that works to extract the 'originalzip.zip', to an 'originalfolder' but it won't go to the folders (folder1, folder2, etc.) to unzip the zipfiles within them. It gets hung up on access to the first student folder and won't unzip it. I think it's a simple fix, but I've been messing with it for quite a while and can't figure it out. Code below: #1 Required imports. import os, os.path, zipfile, arcpy #2 I'm Utilizing 'GetParameterAsText' so that this code can be run as a tool in ArcGIS #2.1 in_zip is a variable for "What zipfile (LAB) do you want to extract?" in_Zip = arcpy.GetParameterAsText(0) cZ = in_Zip #2.2 outDir is a variable for "What is your output Directory?" outDir = os.getcwd() #3 Extracting the initial zipfolder: #3.1 Opening the original zipfile z = zipfile.ZipFile(cZ) #4 Extracting the cZ (original zipfile)into the output directory. z.extractall(outDir) #5 Getting a list of contents of the original zipfile zipContents = z.namelist() #6 Unzipping the Inner Zips: #6.1 Looping through the items that were in the original zipfile, and now in a folder... # ...For each item in the zipContents.... for item in zipContents: #6.2 Get the location (note the location is the 'outDir' plus what namelist() gave me) #(have never used 'os.sep', had to look it up, when someone suggested it) itemLoc = outDir + os.sep + item #6.3 Opens the first (2nd, 3rd, etc files) of the internal zip file (*.zip) z = zipfile.ZipFile(itemLoc) #6.4 Extract all files in *.zip in the same folder as the zipfile z.extractall(os.path.split(itemLoc)[0]) #6.5 determining the list of items in each students' folder student_lab = z.namelist() #7 THE END. Thank you for any and all suggestions/ fixes, constructive criticism and assistance with my beginner code! If you'd like to email me directly it's gwlgis at uw.edu Regards, Greg Lund From ajoshi at flash.net Wed Sep 19 02:44:22 2012 From: ajoshi at flash.net (Alok Joshi) Date: Tue, 18 Sep 2012 17:44:22 -0700 (PDT) Subject: [Tutor] Border width of Canvas widget in tkinter Message-ID: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> I am using Python 3.x ? I am unable to remove the border in a Canvas widget with bd=0 or borderwidth=0. Can someone please explain how one can do this? ? I give below my program ? class Avatar(Frame): ??? def __init__(self,parent=None,width=100,height=100,ovalness=1,bgFrameColor='Blue',bgCanvasColor='Black'): ??????? Frame.__init__(self,parent,width=width,height=height,bg=bgFrameColor) ??????? self.grid() ??????? #self.grid_propagate(0) ??????? ??????? self.width=width ??????? self.height=height ??????? self.ovalness=ovalness ??????? self.bgFrameColor=bgFrameColor ??????? self.bgCanvasColor=bgCanvasColor ??????? ??????? self.canvas1=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0) ??????? self.canvas1.grid(row=0,column=0,ipadx=0,ipady=0,padx=0,pady=0) ??????? self.canvas1.grid_propagate(0) ??????? self.canvas2=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0) ??????? self.canvas2.grid(row=1,column=1,ipadx=0,ipady=0,padx=0,pady=0) ??????? self.canvas2.grid_propagate(0) ??????? ??????? self.draw() ??? def draw(self): ??????? pass ??? if __name__=='__main__': ??? root=Tk() ??? x=Avatar(parent=root) ??? x.mainloop() ? when I run this program I can see a gray border on the two canvas objects. ? Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivisionary507 at gmail.com Wed Sep 19 03:21:41 2012 From: ivisionary507 at gmail.com (Lamar iVisionary) Date: Tue, 18 Sep 2012 20:21:41 -0500 Subject: [Tutor] stored variable Message-ID: Trying to write the following in Python. "Hi, my name is Bob!", .What is your name? print " Hi," + "my name is Bob!, strname= raw_input ("What is your name?") Hi #######, nice to meet you! I'm 18. How old are you? I cant figure out to get the stored variable / (Name) to appear when I respond Hi ####, nice to meet you. Any help with this would be great. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Sep 19 06:09:30 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Sep 2012 14:09:30 +1000 Subject: [Tutor] stored variable In-Reply-To: References: Message-ID: <20120919040930.GA6068@ando> On Tue, Sep 18, 2012 at 08:21:41PM -0500, Lamar iVisionary wrote: > I cant figure out to get the stored variable / (Name) to appear when I > respond Hi ####, nice to meet you. name = raw_input("Good day stranger, to whom do I have the honour of addressing? ") print "Greetings and salutations %s, I hope you are well!" % name -- Steven From paradox at pobox.com Wed Sep 19 06:12:11 2012 From: paradox at pobox.com (Paradox) Date: Wed, 19 Sep 2012 12:12:11 +0800 Subject: [Tutor] stored variable :p: In-Reply-To: References: Message-ID: <5059461B.8040403@pobox.com> On 09/19/2012 09:21 AM, Lamar iVisionary wrote: > > Trying to write the following in Python. > > "Hi, my name is Bob!", > > .What is your name? > > > print " Hi," + "my name is Bob!, > > strname= raw_input ("What is your name?") > > > > > Hi #######, nice to meet you! > I'm 18. How old are you? > > > > > > I cant figure out to get the stored variable / (Name) to appear when I > respond Hi ####, nice to meet you. > > Any help with this would be great. > > > > > Just a beginner here myself but I think you could just use a string substitution to accomplish what you want. For example: sayWord = "Ni!" print "The knights who say %s" % sayWord Will produce: The knights who say Ni! You can do it directly too but usually replacing with a variable gives more flexibility. thomas -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Sep 19 06:48:46 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Sep 2012 14:48:46 +1000 Subject: [Tutor] Storing information as attributes or in a dictionary In-Reply-To: <1347977666.50257.YahooMailClassic@web164005.mail.gq1.yahoo.com> References: <1347977666.50257.YahooMailClassic@web164005.mail.gq1.yahoo.com> Message-ID: <20120919044846.GB6068@ando> On Tue, Sep 18, 2012 at 07:14:26AM -0700, Michiel de Hoon wrote: > Dear all, > > Suppose I have a parser that parses information stored in e.g. an XML file. You mean like the XML parsers that already come with Python? http://docs.python.org/library/markup.html http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/ Or powerful third-party libraries that already exist? http://lxml.de/index.html Please don't waste your time re-inventing the wheel :) > I would like to design a Python class to store the information > contained in this XML file. > > One option is to create a class like this: > > class Record(object): > pass > > and store the information in the XML file as attributes of objects of > this class That is perfectly fine if you have a known set of attribute names, and none of them clash with Python reserved words (like "class", "del", etc.) or are otherwise illegal identifiers (e.g. "2or3"). In general, I prefer to use a record-like object if and only if I have a pre-defined set of field names, in which case I prefer to use namedtuple: py> from collections import namedtuple as nt py> Record = nt("Record", "north south east west") py> x = Record(1, 2, 3, 4) py> print x Record(north=1, south=2, east=3, west=4) py> x.east 3 > Alternatively I could subclass the dictionary class: > > class Record(dict): > pass Why bother subclassing it? You don't add any functionality. Just return a dict, it will be lighter-weight and faster. > I can see some advantage to using a dictionary, because it allows me > to use the same strings as keys in the dictionary as in used in the > XML file itself. But are there some general guidelines for when to use > a dictionary-like class, Yes. You should prefer a dictionary when you have one or more of these: - your field names could be illegal as identifiers (e.g. "field name", "foo!", etc.) - you have an unknown and potentially unlimited number of field names - each record could have a different set of field names - or some fields may be missing - you expect to be programmatically inspecting field names that aren't known until runtime, e.g.: name = get_name_of_field() value = record[name] # is cleaner than getattr(record, name) - you expect to iterate over all field names You might prefer to use attributes of a class if you have one or more of these: - all field names are guaranteed to be legal identifiers - you have a fixed set of field names, known ahead of time - you value the convenience of writing record.field instead of record['field'] > and when to use attributes to store > information? In particular, are there any situations where there is > some advantage in using attributes? Not so much. Attributes are convenient, because you save three characters: obj.spam obj['spam'] but otherwise attributes are just a more limited version of dict keys. Anything that can be done with attributes can be done with a dict, since attributes are usually implemented with a dict. -- Steven From __peter__ at web.de Wed Sep 19 09:15:17 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2012 09:15:17 +0200 Subject: [Tutor] Border width of Canvas widget in tkinter References: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> Message-ID: Alok Joshi wrote: > I am using Python 3.x > > I am unable to remove the border in a Canvas widget with bd=0 or > borderwidth=0. Can someone please explain how one can do this? > > I give below my program > > class Avatar(Frame): > def > __init__(self,parent=None,width=100,height=100,ovalness=1,bgFrameColor='Blue',bgCanvasColor='Black'): > Frame.__init__(self,parent,width=width,height=height,bg=bgFrameColor) > self.grid() #self.grid_propagate(0) > > self.width=width > self.height=height > self.ovalness=ovalness > self.bgFrameColor=bgFrameColor > self.bgCanvasColor=bgCanvasColor > > self.canvas1=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0) > self.canvas1.grid(row=0,column=0,ipadx=0,ipady=0,padx=0,pady=0) > self.canvas1.grid_propagate(0) > self.canvas2=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0) > self.canvas2.grid(row=1,column=1,ipadx=0,ipady=0,padx=0,pady=0) > self.canvas2.grid_propagate(0) > > self.draw() > def draw(self): > pass > > if __name__=='__main__': > root=Tk() > x=Avatar(parent=root) > x.mainloop() > > when I run this program I can see a gray border on the two canvas objects. After some experimentation I could identify "highlightthickness" as the culprit: import Tkinter as tk root = tk.Tk() frame = tk.Frame(root, bg="yellow") frame.pack(fill="both", expand=True) for i in range(2): canvas = tk.Canvas(frame, width=100, height=100, highlightthickness=0, bg="black") canvas.grid(row=i, column=i) root.mainloop() To get there I usually throw something like print list(canvas).config()) and look for promising candidates. From __peter__ at web.de Wed Sep 19 12:58:11 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2012 12:58:11 +0200 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. References: Message-ID: Gregory Lund wrote: > I teach at a college and I'm trying to use Python (2.6 because I'm > running my tool in ArcGIS) to unzip a .zip file that contains one > folder full of student folders, each with 1 or more submissions > (zipfiles) that represent student submissions to weekly lab > assignments. Your lack of response in the previous thread http://mail.python.org/pipermail/tutor/2012-August/090742.html is not a big motivation to answer this one. > It all starts with an originalzip.zip (for example) that has a single > folder (originalfolder) > Within the 'originalfolder' folder there are anywhere from 1 - 40 > folders (that are not zipped). (these are the students userid folders) > Within each of the (1-40) student userid folders is anywhere from 1-10 > zipfiles and perhaps a .pdf or .docx (if for example they submitted > more than one revision of the assignment, there are more than 1) > > Folder Structure > > originalzip.zip > --originalfolder > --folder1 (w/ two zip folders) > --internalzip1_a.zip > --internalfolder1_a > --files > --folders > --internalzip1_b.zip > --internalfolder1_b > --files > --folders > --folder2 (w/1 zip folder) > --internalzip2.zip > --internalfolder2 > --files > --folders > --etc.... > > My goal is to: > a) Unzip the 'originalzip.zip' > b) go to the 'originalfolder' (the unzipped version of the > originalzip.zip) c) go into the first folder (folder1) in the original > folder and unzip any and all zipfiles within it > d) go to the second folder (folder2) in the original folder and unzip > any and all zipfiles within it > e) continue until all folders within originalfolders have been checked > for internalzips > > > ### Note, I am a beginner both with this tutor environment and in python. > I apologize in advance if my code below is 'not up to par' but I am > trying to keep it simple in nature and use ample comments to keep > track of what I am doing. I also don't know if I should post sample > data (zipfile of a folder of folders with zipfiles), and if so, where? > > I have some code that works to extract the 'originalzip.zip', to an > 'originalfolder' but it won't go to the folders (folder1, folder2, > etc.) to unzip the zipfiles within them. > It gets hung up on access to the first student folder and won't unzip it. Hm, I would have expeced an exception. Perhaps you should omit the ArcGIS integration until everything else works. > I think it's a simple fix, but I've been messing with it for quite a > while and can't figure it out. > > Code below: > > #1 Required imports. Excessive comments impair readability. Comments stating the obvious are particularly bad. > import os, os.path, zipfile, arcpy > > #2 I'm Utilizing 'GetParameterAsText' so that this code can be run as > a tool in ArcGIS > > #2.1 in_zip is a variable for "What zipfile (LAB) do you want to extract?" > in_Zip = arcpy.GetParameterAsText(0) > cZ = in_Zip Why two names for one value? > #2.2 outDir is a variable for "What is your output Directory?" > outDir = os.getcwd() > > #3 Extracting the initial zipfolder: > #3.1 Opening the original zipfile > z = zipfile.ZipFile(cZ) > > #4 Extracting the cZ (original zipfile)into the output directory. > z.extractall(outDir) > > #5 Getting a list of contents of the original zipfile > zipContents = z.namelist() > > #6 Unzipping the Inner Zips: > > #6.1 Looping through the items that were in the original zipfile, and > now in a folder... > # ...For each item in the zipContents.... > for item in zipContents: You make no attempt to filter out the contents that are not zipfiles. That will cause an exception further down where you try to unzip. > #6.2 Get the location (note the location is the 'outDir' plus what > namelist() gave me) > #(have never used 'os.sep', had to look it up, when someone suggested > #it) > itemLoc = outDir + os.sep + item The standard way (which is also more robust) is to use os.path.join(): itemLoc = os.path.join(outDir, item) > #6.3 Opens the first (2nd, 3rd, etc files) of the internal zip file > #(*.zip) > z = zipfile.ZipFile(itemLoc) > > #6.4 Extract all files in *.zip in the same folder as the zipfile > z.extractall(os.path.split(itemLoc)[0]) The zip files's contents will probably end up in the same folder as the zipfile. Is that what you want? > > #6.5 determining the list of items in each students' folder > student_lab = z.namelist() Unused variable alert. > > #7 THE END. > > Thank you for any and all suggestions/ fixes, constructive criticism > and assistance with my beginner code! Have you considered the simpler code I gave in http://mail.python.org/pipermail/tutor/2012-August/090743.html before prodding on? From ajoshi at flash.net Wed Sep 19 13:55:15 2012 From: ajoshi at flash.net (Alok Joshi) Date: Wed, 19 Sep 2012 04:55:15 -0700 (PDT) Subject: [Tutor] Fw: Border width of Canvas widget in tkinter In-Reply-To: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> References: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> Message-ID: <1348055715.57959.YahooMailNeo@web181705.mail.ne1.yahoo.com> Thanks very much Peter for your explanation and specially for your hint as to how I might debug these kinds of issues. ? This is my first time asking a question on tutor mailing list and getting a reply. I hope this reply will correctly tie up as a response to your posting. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Wed Sep 19 14:39:05 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 19 Sep 2012 08:39:05 -0400 Subject: [Tutor] Fw: Border width of Canvas widget in tkinter In-Reply-To: <1348055715.57959.YahooMailNeo@web181705.mail.ne1.yahoo.com> References: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> <1348055715.57959.YahooMailNeo@web181705.mail.ne1.yahoo.com> Message-ID: On Wed, Sep 19, 2012 at 7:55 AM, Alok Joshi wrote: > Thanks very much Peter for your explanation and specially for your hint as > to how I might debug these kinds of issues. > > This is my first time asking a question on tutor mailing list and getting a > reply. I hope this reply will correctly tie up as a response to your > posting. > Just as a brief note, even though there are very knowledgeable, and qualified individuals to answer on this list, you might find the Tkinter mailing list a little more helpful. I try to ask my questions in specific forums/mailing lists, and you usually get better responses from a specific list just for that topic. Here's the link: http://mail.python.org/mailman/listinfo/tkinter-discuss -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Wed Sep 19 14:45:51 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 19 Sep 2012 08:45:51 -0400 Subject: [Tutor] Fw: Border width of Canvas widget in tkinter In-Reply-To: References: <1348015462.52680.YahooMailNeo@web181701.mail.ne1.yahoo.com> <1348055715.57959.YahooMailNeo@web181705.mail.ne1.yahoo.com> Message-ID: Also, you might find the tkdocs handy: http://www.tkdocs.com/tutorial/canvas.html -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From gnj091405 at gmail.com Wed Sep 19 17:10:53 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Wed, 19 Sep 2012 08:10:53 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: Message-ID: > > Your lack of response in the previous thread > > http://mail.python.org/pipermail/tutor/2012-August/090742.html > > is not a big motivation to answer this one. I didn't have any response to post, I got the basics to work using a hint from a colleague in and was able to grade the assignment, however it seems as though the way the files are NOW saved in the Learning Management System are not as I prepared my testing situation. I wasn't able to use what Peter provided because I didn't understand it (again, rookie/neophyte). To an intermediate user, you most likely answered my questions, but I didn't understand what you were saying/writing/typing. It was full of code that I didn't (don't) understand (sys.argv, glob, $ tree, etc.) I had to go with what I could understand or at least work with. I tried studying up on sys.argv, glob, etc. and got lost in the details) Again, a colleague was able to help enough to get it to work using my simplified code. (or at least code I could read). >> >> originalzip.zip >> --originalfolder >> --folder1 (w/ two zip folders) >> --internalzip1_a.zip >> --internalfolder1_a >> --files >> --folders >> --internalzip1_b.zip >> --internalfolder1_b >> --files >> --folders >> --folder2 (w/1 zip folder) >> --internalzip2.zip >> --internalfolder2 >> --files >> --folders >> --etc.... I attempted to replicate Peter's 'Folder Structure' diagram above, he did a better job 'drawing it' but the one above is my data situation. Using my sample data, this is what the folder structure resembles below. |__ Student_Work_Sample_use (a folder I create before running the script, the original zip is placed in this folder before running the script) |__originalzip.zip (entire class all zipped up into one) (THIS NEEDS TO BE UNZIPPED IN THE CODE) |__Lab_2 (a folder that is the contents of originalzip.zip unzipped) |__aforker (unzipped folder that comes in Lab_2) |__aforker_lab_2.zip (student username 'aforker''s' lab) (THIS NEEDS TO BE UNZIPPED IN THE CODE) |__aforker_lab_writeup.docx (a docx file that may or may not come in with the lab submission (it may or may not be zipped, if it's not zipped, no need to deal with it) |__aforker_lab_2 (a folder that is the contents of aforker_lab_2.zip, unzipped) |__ datafolder (unzipped folders within aforkers lab folder) (no need to worry about, just here for reference) |__ mapsfolder (unzipped folders within aforkers lab folder) (no need to worry about, just here for reference) |__awilliams (unzipped folder that comes in Lab_2) |__awilliams_lab_2.zip (student username 'awilliams''s' lab) (THIS NEEDS TO BE UNZIPPED IN THE CODE) |__awilliams_lab_2 (a folder that is the contents of awilliams_lab_2.zip, unzipped) |__ datafolder (unzipped folders within awilliams lab folder) (no need to worry about, just here for reference) |__ mapsfolder (unzipped folders within awilliams lab folder) (no need to worry about, just here for reference) |__awilliams_lab_2_RESUB.zip (student username 'awilliams''s' lab) (THIS NEEDS TO BE UNZIPPED IN THE CODE) |__awilliams_lab_2_RESUB (a folder that is the contents of awilliams_lab_2_RESUB.zip, unzipped) |__ datafolder (unzipped folders within awilliams lab folder) (no need to worry about, just here for reference) |__ mapsfolder (unzipped folders within awilliams lab folder) (no need to worry about, just here for reference) |__jsmith (unzipped folder that comes in Lab_2) |__jsmith_lab_2.zip (student username 'jsmith''s' lab) (THIS NEEDS TO BE UNZIPPED IN THE CODE) |__jsmith_lab_2 (a folder that is the contents of jsmith_lab_2.zip, unzipped) |__ datafolder (unzipped folders within jsmith lab folder) (no need to worry about, just here for reference) |__ mapsfolder (unzipped folders within jsmith lab folder) (no need to worry about, just here for reference) |__ etc. etc. etc. up to 40 students..... >> >> My goal is to: >> a) Unzip the 'originalzip.zip' >> b) go to the 'originalfolder' (the unzipped version of the >> originalzip.zip) c) go into the first folder (folder1) in the original >> folder and unzip any and all zipfiles within it >> d) go to the second folder (folder2) in the original folder and unzip >> any and all zipfiles within it >> e) continue until all folders within originalfolders have been checked >> for internalzips >> >> >> I have some code that works to extract the 'originalzip.zip', to an >> 'originalfolder' but it won't go to the folders (folder1, folder2, >> etc.) to unzip the zipfiles within them. >> It gets hung up on access to the first student folder and won't unzip it. > > Hm, I would have expeced an exception. Perhaps you should omit the ArcGIS > integration until everything else works. Fair enough, although the ArcGIS integration is simple. Setting it up, is all in an Arc GUI. > > Excessive comments impair readability. Comments stating the obvious are > particularly bad. Point taken, however 'obvious to neophytes' is quite different than 'obvious to experts' . (I still need comments- :-0) #super short Code below, without comments: (and using the two fixes suggested thus far by Peter (no os.sep and two names for one value issue) import os, os.path, zipfile, arcpy in_Zip = arcpy.GetParameterAsText(0) outDir = os.getcwd() z = zipfile.ZipFile(in_Zip) z.extractall(outDir) zipContents = z.namelist() for item in zipContents: itemLoc = outDir + os.sep + item z = zipfile.ZipFile(itemLoc) z.extractall(os.path.split(itemLoc)[0]) student_lab = z.namelist() >> #2.1 in_zip is a variable for "What zipfile (LAB) do you want to extract?" >> in_Zip = arcpy.GetParameterAsText(0) >> cZ = in_Zip > > Why two names for one value? Rookie Mistake. I thought I'd need the raw in_Zip in some instances and then cZ in others. (Fixed Now, above) > You make no attempt to filter out the contents that are not zipfiles. That > will cause an exception further down where you try to unzip. True, and that's what happened. My code does not show it above. I tried... but it messed things up further (worse) so reverted back to what was 'working' the most. I tried some 'While' statements and some 'If' statements, both gave me alphabet soup in return. Again, I'm a neophyte. > >> #6.2 Get the location (note the location is the 'outDir' plus what >> namelist() gave me) >> #(have never used 'os.sep', had to look it up, when someone suggested >> #it) >> itemLoc = outDir + os.sep + item > > The standard way (which is also more robust) is to use os.path.join(): > > itemLoc = os.path.join(outDir, item) > Thank you, I changed that above >> #6.3 Opens the first (2nd, 3rd, etc files) of the internal zip file >> #(*.zip) >> z = zipfile.ZipFile(itemLoc) >> >> #6.4 Extract all files in *.zip in the same folder as the zipfile >> z.extractall(os.path.split(itemLoc)[0]) > > The zip files's contents will probably end up in the same folder as the > zipfile. Is that what you want? Yes, that is exactly what I want. my desire is to get them to end up in their respective 'username' folders. folder1, folder2 etc are all 'usernames' I need to keep all of the submissions separated by username Which is the way they come from the Learning Management System. That's how I keep the individual assignment straight. Originally, doing this all manually: I had to unzip the originalzip.zip (relatively simple and not time consuming) Open the resulting folder (Lab_2 in this example) Open each non-zipped folder (a folder for each student) within Lab_2 (this was a time consuming task (if you figure 9 labs throughout the quarter and ... 40 students (40 folders)!) THEN unzip each of the zipfiles in each of those non-zipped folders that the students submitted (very, very time consuming!) >> >> #6.5 determining the list of items in each students' folder >> student_lab = z.namelist() > > Unused variable alert. Whoops, this was part of my attempt to unzip the second round of folders, putting them into a list. > >> >> Thank you for any and all suggestions/ fixes, constructive criticism >> and assistance with my beginner code! > > Have you considered the simpler code I gave in > > http://mail.python.org/pipermail/tutor/2012-August/090743.html > > before prodding on? Yes, I did consider it, but I didn't understand it enough to 'run with it'. If it worked perfectly I still wouldn't of understood it, and it I needed to tweak it, there would have been no way for me to figure out what to do to make it fit my scenario. While it may be 'simpler' for the experienced python coder, Not being familiar with Python, it wasn't simpler for me, I could hardly read any of it. I even printed it out and saved, but I couldn't understand it and didn't want to bother you with it any more (felt like an idiot, to be honest) (you would of had to explain everything, as I didn't understand hardly any of it) A Colleague gave me some tips (for example: "itemLoc = outDir + os.sep + item" and that worked at the time... so I went with it. Absolutely no disrespect intended Peter! I just couldn't decipher what you meant, whereas my colleague's help fixed what I had, so I went with it. And again, since I didn't understand what you wrote, I didn't want to bother you with it anymore. For reference, this is the error I get: : [Errno 13] Permission denied: 'D:\\D_Drive_Documents\\Student_Work_Sample_use\\Lab_2/aforker/' Failed to execute (unzipsZipOfZips) 'Student_Work_Sample_use' is a folder that housed my small test data set (originalzip.zip). 'Lab_2' is the correct 'answer' for the first unzip process (I used my Spring 2012 students Lab_2 as the sample dataset) This part worked and still works. 'aforker' is an actual student from the class (his/her username) I see that there is an issue with the slashes in the folder path, despite numerous attempts, I can't resolve that. Thank you again Peter and the rest of this maillist! Greg > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Wed Sep 19 17:43:28 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Sep 2012 01:43:28 +1000 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: Message-ID: <5059E820.2070904@pearwood.info> Hi Gregory, On 20/09/12 01:10, Gregory Lund wrote: >> >> Your lack of response in the previous thread >> >> http://mail.python.org/pipermail/tutor/2012-August/090742.html >> >> is not a big motivation to answer this one. > > I didn't have any response to post, I got the basics to work using a > hint from a colleague in and was able to grade the assignment, [...] > To an intermediate user, you most likely answered my questions, but I > didn't understand what you were saying/writing/typing. > It was full of code that I didn't (don't) understand (sys.argv, glob, > $ tree, etc.) That's fine and nothing to be ashamed of. But don't be shy about asking for explanations of what code does. If you're here to learn, you have to ask questions! -- Steven From steve at pearwood.info Wed Sep 19 18:01:24 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Sep 2012 02:01:24 +1000 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: Message-ID: <5059EC54.6040804@pearwood.info> Further comments below: On 20/09/12 01:10, Gregory Lund wrote: >> Have you considered the simpler code I gave in >> >> http://mail.python.org/pipermail/tutor/2012-August/090743.html >> >> before prodding on? > > Yes, I did consider it, but I didn't understand it enough to 'run with it'. > If it worked perfectly I still wouldn't of understood it, and it I > needed to tweak it, there would have been no way for me to figure out > what to do to make it fit my scenario. > While it may be 'simpler' for the experienced python coder, Not being > familiar with Python, it wasn't simpler for me, I could hardly read > any of it. > I even printed it out and saved, but I couldn't understand it and > didn't want to bother you with it any more (felt like an idiot, to be > honest) (you would of had to explain everything, as I didn't > understand hardly any of it) That's what we're here for! Don't be shy about asking questions. However, I have to say Peter was a bit optimistic in his assumptions about your general level of expertise. He mixed Python code and (probably) Linux shell commands and output, which probably didn't help. Using Peter's code, if you create a plain text file called "unzip_twice.py" containing: import glob import os import sys import zipfile source_file = sys.argv[1] dest_folder = sys.argv[2] zipfile.ZipFile(source_file).extractall(dest_folder) inner_zips_pattern = os.path.join(dest_folder, "*.zip") for filename in glob.glob(inner_zips_pattern): inner_folder = filename[:-4] zipfile.ZipFile(filename).extractall(inner_folder) and then run it from the shell like this: python unzip_twice.py NAME-OF-ZIP-FILE NAME-OF-FOLDER-TO-EXTRACT-TO (the folder must already exist), it may do what you want. Make sure you test it on a sample set of data, not the real thing. You'll also need to make sure that you have write permission to the folder, and read permission to the zip file. If you get Permission Denied errors, check the permissions. I see that you're using Windows. I don't have Windows myself, but I think you'll probably have fewer problems with pathnames if you use forward slashes instead of backslashes. So: D:/D_Drive_Documents/Student_Work_Sample_use/Lab_2/aforker/ Good luck and don't worry about asking dumb questions, the only dumb question is "Was it you or your brother that was killed in the war?" :-) -- Steven From gnj091405 at gmail.com Wed Sep 19 18:29:37 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Wed, 19 Sep 2012 09:29:37 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: <5059EC54.6040804@pearwood.info> References: <5059EC54.6040804@pearwood.info> Message-ID: > Using Peter's code, if you create a plain text file called "unzip_twice.py" > containing: > > > import glob > import os > import sys > import zipfile > > source_file = sys.argv[1] > dest_folder = sys.argv[2] > > zipfile.ZipFile(source_file).extractall(dest_folder) > > inner_zips_pattern = os.path.join(dest_folder, "*.zip") > for filename in glob.glob(inner_zips_pattern): > inner_folder = filename[:-4] > zipfile.ZipFile(filename).extractall(inner_folder) > Consider it done, i have a new .py file saved as 'unzip_twice.py' pasted below: import glob import os import sys import zipfile source_file = sys.argv[1] dest_folder = sys.argv[2] zipfile.ZipFile(source_file).extractall(dest_folder) inner_zips_pattern = os.path.join(dest_folder, "*.zip") for filename in glob.glob(inner_zips_pattern): inner_folder = filename[:-4] zipfile.ZipFile(filename).extractall(inner_folder) > > and then run it from the shell like this: > > python unzip_twice.py NAME-OF-ZIP-FILE NAME-OF-FOLDER-TO-EXTRACT-TO > In the IDLE 2.6.5 shell I typed (exactly what is in quotes, without quotes of course): "python unzip_twice.py 2012-09-18 Lab_2.zip Student_Work_Sample_usecopy1" where '2012-09-18 Lab_2.zip' was/is the original zipfile and 'Student_Work_Sample_usecopy1' is the folder in which I want it all housed/extracted I got what is in quotes below: "IDLE 2.6.5 >>> python unzip_twice.py 2012-09-18 Lab_2.zip Student_Work_Sample_usecopy1 SyntaxError: invalid syntax" (unzip_twice) was the highlighted invalid syntax I tried again: In the IDLE 2.6.5 shell I typed (exactly what is in quotes, without quotes of course): "unzip_twice.py 2012-09-18 Lab_2.zip Student_Work_Sample_usecopy1" where '2012-09-18 Lab_2.zip' was/is the original zipfile and 'Student_Work_Sample_usecopy1' is the folder in which it exists and I want it all housed/extracted I got what is in quotes below: "IDLE 2.6.5 >>> unzip_twice.py 2012-09-18 Lab_2.zip Student_Work_Sample_usecopy1 SyntaxError: invalid syntax" (2012) was the highlighted 'invalid syntax' Maybe its the version of Python? Maybe I didn't read what you wrote to type into the shell properly? Maybe it's the spaces and dashes in the zipfile name? (the LMS does that (learning Management system) > (the folder must already exist), it may do what you want. Make sure > you test it on a sample set of data, not the real thing. I created copies of my original test data and folders: 'Student_Work_Sample_usecopy1' was the folder and w/in it: the actual zipfile. > > I see that you're using Windows. I don't have Windows myself, but I > think you'll probably have fewer problems with pathnames if you use > forward slashes instead of backslashes. So: > > D:/D_Drive_Documents/Student_Work_Sample_use/Lab_2/aforker/ > yes, Windows 7, but I didn't type out the slashes, they were coming in via what the code was running. I couldn't figure out where to ensure that they were forward (or double backslashes). > Good luck and don't worry about asking dumb questions, the only dumb > question is "Was it you or your brother that was killed in the war?" Thanks, as you can tell, I need it! Greg From gnj091405 at gmail.com Wed Sep 19 18:43:08 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Wed, 19 Sep 2012 09:43:08 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: more info: > Consider it done, i have a new .py file saved as 'unzip_twice.py' but it would be easier (the whole purpose of this task) is to have a stand alone script that would work without having to open up the shell. In ArcGIS, I call the script by double clicking on my tool, selecting the .zip in a GUI and it runs, extracting the first zipfile, but hangs on the next, supposedly because of 'permissions' but 'permissions' were not really an issue. I think it's the "is it a .zip or is it not a zip" issue. Permissions were not an issue in the original task, which worked (but had flawed data structure (my fault)). > Maybe its the version of Python? > Maybe I didn't read what you wrote to type into the shell properly? > Maybe it's the spaces and dashes in the zipfile name? (the LMS does > that (learning Management system) Maybe it's the location of the unzip_twice.py script? >> (the folder must already exist), it may do what you want. Make sure >> you test it on a sample set of data, not the real thing. yes, folder existed >> Good luck and don't worry about asking dumb questions, the only dumb >> question is "Was it you or your brother that was killed in the war?" > > Thanks, as you can tell, I need it! Thanks again, I really do need it! (oh sorry, was that obvious? haha!) Greg From __peter__ at web.de Wed Sep 19 19:20:15 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2012 19:20:15 +0200 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. References: <5059EC54.6040804@pearwood.info> Message-ID: Gregory Lund wrote: >> Using Peter's code, if you create a plain text file called >> "unzip_twice.py" containing: >> >> >> import glob >> import os >> import sys >> import zipfile >> >> source_file = sys.argv[1] >> dest_folder = sys.argv[2] >> >> zipfile.ZipFile(source_file).extractall(dest_folder) >> >> inner_zips_pattern = os.path.join(dest_folder, "*.zip") >> for filename in glob.glob(inner_zips_pattern): >> inner_folder = filename[:-4] >> zipfile.ZipFile(filename).extractall(inner_folder) >> > Consider it done, i have a new .py file saved as 'unzip_twice.py' > pasted below: > > import glob > import os > import sys > import zipfile > > source_file = sys.argv[1] > dest_folder = sys.argv[2] > > zipfile.ZipFile(source_file).extractall(dest_folder) > > inner_zips_pattern = os.path.join(dest_folder, "*.zip") > for filename in glob.glob(inner_zips_pattern): > inner_folder = filename[:-4] > zipfile.ZipFile(filename).extractall(inner_folder) > >> >> and then run it from the shell like this: >> >> python unzip_twice.py NAME-OF-ZIP-FILE NAME-OF-FOLDER-TO-EXTRACT-TO >> > In the IDLE 2.6.5 shell I typed (exactly what is in quotes, without Don't use Idle, follow the instructions on http://www.windows7hacker.com/index.php/2009/08/how-to-open-dos-prompt-command-here-in-windows-7-and-more/ If you see the ugly little black window you are there an can type in your command. From jim7fl at ideas4you.com Wed Sep 19 17:56:34 2012 From: jim7fl at ideas4you.com (Jim Smith Sr.) Date: Wed, 19 Sep 2012 11:56:34 -0400 Subject: [Tutor] interface with libreoffice calc spreadsheet to export pdf reports Message-ID: <5059EB32.6070204@ideas4you.com> I have a spreadsheet with a named range "pdfReport" to export to pdf in the default location. The data changed based on student number input to another named range "_pid". Assumptions: the spreadsheet is already open and on the correct sheet. This doesn't matter, as we will be selecting the cell and the print range anyway. So I need to do something similar to: howmany = 16 # number of students to process for c from 1 to howmany # begin loop select _pid typein c and press enter # this changes the data in the report select _filename # this is a cell which has a new filename for each report copy cell # this gives me the filename to paste later select pdfReport # select the range to export # the menu choices are File>Export as PDF> # then the next dialog box gives choices but the only # choice I want is in General (default tab) # Range has All selected, I want Selection selected # then Export or Enter pressed #This is followed by a prompt for file name Paste filename from above Export next c ideally, my first task would be to copy a cell or pass a variable containing the number "howmany" so this would work for any of my classes. Thanks in advance for getting me started with this. I'm in the process of learning python from the excellent tutorial at Learn Pyton the Hard Way Although, it is not really the hard way, but rather quite simple but time consuming for someone unfamiliar with Python and the UNO Basic dispatch of both OpenOffice and LibreOffice. Best Regards, Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Sep 19 19:40:26 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2012 19:40:26 +0200 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. References: <5059EC54.6040804@pearwood.info> Message-ID: Steven D'Aprano wrote: > That's what we're here for! Don't be shy about asking questions. Indeed. Also, Gregory, don't expect anything to work directly. Programming is mostly an iterative process where you write just a little bit of code before you have to stop to fix a host of bugs. Repeat until you have something that almost does what you intended... > However, I have to say Peter was a bit optimistic in his assumptions about > your general level of expertise. He mixed Python code and (probably) Linux > shell commands and output, which probably didn't help. Gregory introduced himself as a university lecturer, so I tacitly assumed that he had seen a shell window on a linux box or a mac, and would appreciate if he could use something familiar (globbing) in a new environment (python). I make similar assumptions about questioners' skills level all the time -- and sometimes fail in a big way ;) From gnj091405 at gmail.com Wed Sep 19 20:00:41 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Wed, 19 Sep 2012 11:00:41 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: >>> and then run it from the shell like this: On Wed, Sep 19, 2012 at 10:20 AM, Peter Otten <__peter__ at web.de> wrote: > Gregory Lund wrote: >>> and then run it from the shell like this: ahh, windows shell, not python shell. from the directions Peter linked to, I shift-right clicked on the folder where my script resided (hope that was right) then after D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts> I typed:python unzip_twice.py 2012-09-18 Lab_2.zip Student_Work_Sample_usecopy1 where: unzip_twice.py is the script name as suggested by Steve 2012-09-18 Lab_2.zip is the zipfile Student_Work_Sample_usecopy1 is the folder the zipfile resides and where I want the info extracted to. Lucky me... NOT...:-) I got: "'python' is not recognized as an internal or external command, operable program or batch file" (without the quotes of course) I am still worried that none of this will transfer to my GUI after I get it working. Is there a way to do this using the code that I started so that it will work without the command prompt? I got part of it to work, as detailed earlier, but... not the second round of zips. Maybe it can't be done? Thanks for the continued help. either way, once I get it to finally work, it will save me time. Greg From gnj091405 at gmail.com Wed Sep 19 20:09:38 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Wed, 19 Sep 2012 11:09:38 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On Wed, Sep 19, 2012 at 10:40 AM, Peter Otten <__peter__ at web.de> wrote: > Steven D'Aprano wrote: > >> That's what we're here for! Don't be shy about asking questions. > > Indeed. Also, Gregory, don't expect anything to work directly. Programming > is mostly an iterative process where you write just a little bit of code > before you have to stop to fix a host of bugs. Repeat until you have > something that almost does what you intended... Believe me, I don't expect it to work directly, that's for sure. I have just that, a little bit of code that extracts the first zip, and am now working on a little bit of code to extract the zips within it. > >> However, I have to say Peter was a bit optimistic in his assumptions about >> your general level of expertise. He mixed Python code and (probably) Linux >> shell commands and output, which probably didn't help. > > Gregory introduced himself as a university lecturer, so I tacitly assumed > that he had seen a shell window on a linux box or a mac, and would > appreciate if he could use something familiar (globbing) in a new > environment (python). You were correct, I have seen a shell window on a Windows box. Correct Assumption. However, I did not know it was that, to which you were referencing, and it wouldn't of worked where I want it to: In a GUI via ArcGIS. > > I make similar assumptions about questioners' skills level all the time -- > and sometimes fail in a big way ;) Sorry, tried to emphasize the 'neophyte' from the get go. Definition of crazy? Doing the same thing over and over again while expecting different results? Perhaps the code can not be written to run in a python shell (from which I could use in my Esri ArcGIS GUI. (again, I have a spot to put in one link to the .py code, the GUI asks me (in a way) "which zipfile", I navigate to it and click I have no need for shortened code or running in the cmd window, it's such a short operation, it doesn't matter if it takes me 100 to 1000 lines of 'baby' or 'rookie' code to write, as long as it works. With only one starting zip and within it up to 40 folders each containing (usually) one zipfile (max of 5), the matter of time it takes to run is not an issue. I just need to have one .py file that does it all, or calls upon other .py files I guess in order to work. I do appreciate the help, and am learning in this process. again, maybe I want python to do something that can't be done? Greg From ashish.makani at gmail.com Wed Sep 19 20:47:03 2012 From: ashish.makani at gmail.com (ashish makani) Date: Thu, 20 Sep 2012 00:17:03 +0530 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . Message-ID: Hi PyTutor Folks Here is my situation 1. I have two machines. Lets call them *local & remote.* Both run ubuntu & both have python installed 2. I have a python script, *local.py*, running on *local *which needs to pass arguments ( 3/4 string arguments, containing whitespaces like spaces, etc ) to a python script, *remote.py* running on *remote* (the remote machine). I have the following questions: 1. What's the best way to accomplish my task ? I have researched quite a bit & so far found really conflicting & complex workarounds. I googled & found people using several libraries to accomplish ssh to remote machine & execute a command on remote machine. paramiko ( now forked into the ssh moduke), fabric , pushy,etc People who have used any of these libraries, which one would you recommend, as the most apt (simple & easy to use, lightweight, best performance, etc) for my situation ? 2. I would prefer a solution, which does NOT require the installation of extra libraries on the local & remote machines. If installing external librar 3. Has anybody been able to do this using os.system ? I tried this >>> import os >>> *os.system ("ssh remoteuser at remote python remote.py arg1 arg2 arg3")* * * This worked, but if the arguments i tried to pass, had spaces, i was not able to 'escape' the spaces. Any & all explanations/links/code snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor community would be greatly appreciated. Thanks a ton cheers ashish email : ashish.makani domain:gmail.com *?The only way to do great work is to love what you do. If you haven?t found it yet, keep looking. Don?t settle. As with all matters of the heart, you?ll know when you find it.? - Steve Jobs (1955 - 2011)* -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Sep 19 21:24:22 2012 From: d at davea.name (Dave Angel) Date: Wed, 19 Sep 2012 15:24:22 -0400 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: <505A1BE6.2000108@davea.name> On 09/19/2012 02:47 PM, ashish makani wrote: > Hi PyTutor Folks > > Here is my situation > > 1. I have two machines. Lets call them *local & remote.* > Both run ubuntu & both have python installed > > 2. I have a python script, *local.py*, running on *local *which needs to > pass arguments ( 3/4 string arguments, containing whitespaces like spaces, > etc ) to a python script, *remote.py* running on *remote* (the remote > machine). > > I have the following questions: > > 1. What's the best way to accomplish my task ? > I have researched quite a bit & so far found really conflicting & complex > workarounds. > > I googled & found people using several libraries to accomplish ssh to > remote machine & execute a command on remote machine. > paramiko ( now forked into the ssh > moduke), > fabric , > pushy,etc > > People who have used any of these libraries, which one would you recommend, > as the most apt (simple & easy to use, lightweight, best performance, etc) > for my situation ? > > 2. I would prefer a solution, which does NOT require the installation of > extra libraries on the local & remote machines. > If installing external librar > > 3. Has anybody been able to do this using os.system ? > > I tried this >>>> import os >>>> *os.system ("ssh remoteuser at remote python remote.py arg1 arg2 arg3")* > * > * > This worked, but if the arguments i tried to pass, had spaces, i was not > able to 'escape' the spaces. > > Any & all explanations/links/code > snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor > community would be greatly appreciated. > > Thanks a ton > > cheers > ashish > > email : > ashish.makani > domain:gmail.com > > *?The only way to do great work is to love what you do. If you haven?t > found it yet, keep looking. Don?t settle. As with all matters of the heart, > you?ll know when you find it.? - Steve Jobs (1955 - 2011)* > > Since you prefer not installing any optional libraries, I'll just talk about your os.system() mechanism. Is that adequate for you, other than the problem with spaces? If so, then why not test it with the real ssh, to figure out where the quotes need to be to handle the spaces. Then once you have it working, use single quotes around the whole thing when calling os.exec(). Something like (all untested): os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 has spaces" arg3') Or, more likely, build the arguments in separate variables, and use os.system( 'ssh remoteuser at remote python remote.py "%s" "%s" "%s"' % (arg1, arg2, arg3) ) that will fail if the argn already has quotes in it. You can get much fancier with encoding, which will add backslashes in front of some characters, etc. But keep it simple if you can. I ought to give the obligatory: use the multiprocess module instead of os.exec, but if something works for you, I'm not going to argue. -- DaveA From ashish.makani at gmail.com Wed Sep 19 21:45:19 2012 From: ashish.makani at gmail.com (ashish makani) Date: Thu, 20 Sep 2012 01:15:19 +0530 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: <505A1BE6.2000108@davea.name> References: <505A1BE6.2000108@davea.name> Message-ID: Thanks a ton for the prompt reply & the great suggestions, Dave. 1. A colleague gave this exact same suggestion os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 has spaces" arg3') I was thinking spaces is my problem, so i initially tested the following (no ssh) os.system('python remote.py arg1 "arg 2 has spaces" arg3') & it works :) But sadly, os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 has spaces" arg3') does not :( 2. Also, you mentioned os.exec Which would you recommend ? os.system or os.exec ? Thanks a lot, cheers ashish On Thu, Sep 20, 2012 at 12:54 AM, Dave Angel wrote: > On 09/19/2012 02:47 PM, ashish makani wrote: > > Hi PyTutor Folks > > > > Here is my situation > > > > 1. I have two machines. Lets call them *local & remote.* > > Both run ubuntu & both have python installed > > > > 2. I have a python script, *local.py*, running on *local *which needs to > > pass arguments ( 3/4 string arguments, containing whitespaces like > spaces, > > etc ) to a python script, *remote.py* running on *remote* (the remote > > machine). > > > > I have the following questions: > > > > 1. What's the best way to accomplish my task ? > > I have researched quite a bit & so far found really conflicting & complex > > workarounds. > > > > I googled & found people using several libraries to accomplish ssh to > > remote machine & execute a command on remote machine. > > paramiko ( now forked into the ssh > > moduke), > > fabric , > > pushy,etc > > > > People who have used any of these libraries, which one would you > recommend, > > as the most apt (simple & easy to use, lightweight, best performance, > etc) > > for my situation ? > > > > 2. I would prefer a solution, which does NOT require the installation of > > extra libraries on the local & remote machines. > > If installing external librar > > > > 3. Has anybody been able to do this using os.system ? > > > > I tried this > >>>> import os > >>>> *os.system ("ssh remoteuser at remote python remote.py arg1 arg2 arg3")* > > * > > * > > This worked, but if the arguments i tried to pass, had spaces, i was not > > able to 'escape' the spaces. > > > > Any & all explanations/links/code > > snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python > tutor > > community would be greatly appreciated. > > > > Thanks a ton > > > > cheers > > ashish > > > > email : > > ashish.makani > > domain:gmail.com > > > > *?The only way to do great work is to love what you do. If you haven?t > > found it yet, keep looking. Don?t settle. As with all matters of the > heart, > > you?ll know when you find it.? - Steve Jobs (1955 - 2011)* > > > > > > Since you prefer not installing any optional libraries, I'll just talk > about your os.system() mechanism. Is that adequate for you, other than > the problem with spaces? > > If so, then why not test it with the real ssh, to figure out where the > quotes need to be to handle the spaces. Then once you have it working, > use single quotes around the whole thing when calling os.exec(). > > Something like (all untested): > > os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 has > spaces" arg3') > > > Or, more likely, build the arguments in separate variables, and use > > os.system( 'ssh remoteuser at remote python remote.py "%s" "%s" "%s"' % > (arg1, arg2, arg3) ) > > that will fail if the argn already has quotes in it. You can get much > fancier with encoding, which will add backslashes in front of some > characters, etc. But keep it simple if you can. > > I ought to give the obligatory: use the multiprocess module instead of > os.exec, but if something works for you, I'm not going to argue. > > > > > -- > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Sep 19 21:57:55 2012 From: d at davea.name (Dave Angel) Date: Wed, 19 Sep 2012 15:57:55 -0400 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: <505A1BE6.2000108@davea.name> Message-ID: <505A23C3.3040201@davea.name> On 09/19/2012 03:45 PM, ashish makani wrote: > Thanks a ton for the prompt reply & the great suggestions, Dave. > Please don't top post. In this mailing list, the convention is to put your remarks after the part you're quoting (which usually isn't the entire message). That way, if the context gets complex, it's easier to see who wrote what, and in what order. > 1. A colleague gave this exact same suggestion > os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 has spaces" > arg3') > > I was thinking spaces is my problem, so i initially tested the following > (no ssh) > os.system('python remote.py arg1 "arg 2 has spaces" arg3') & it works :) > > But sadly, os.system ('ssh remoteuser at remote python remote.py arg1 "arg 2 > has spaces" arg3') does not :( Did you try it the way I suggested above? Make it work in ssh, then worry about how python can build that command string. > > 2. Also, you mentioned os.exec > Which would you recommend ? > os.system or os.exec ? Since there's no os.exec, it was just an brain-hiccup on my part. So, back to the problem. Once you've got it working in ssh, then we can figure how to make os.exec, or other python execution mechanism, work. -- DaveA From senrabc at gmail.com Wed Sep 19 22:00:48 2012 From: senrabc at gmail.com (Christopher Barnes) Date: Wed, 19 Sep 2012 16:00:48 -0400 Subject: [Tutor] RTF ( Rich Text) module for Python Message-ID: Hi All, Thanks in advance for any help or suggestions. I'm new to python. Does anyone have any suggestions for a RTF ( RichText) python module to use to create RTF documents. I have tried to use PyRTF, but am struggling. It seems the PyRTF project hasn't had any updates in a while and Ive had a difficult time following the examples. Anyhow, if you have any thoughts I'm glad to hear them. Thanks, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 20 00:13:46 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 19 Sep 2012 18:13:46 -0400 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: On Wed, Sep 19, 2012 at 2:47 PM, ashish makani wrote: > > I tried this >>>> import os >>>> os.system ("ssh remoteuser at remote python remote.py arg1 arg2 arg3") > > This worked, but if the arguments i tried to pass, had spaces, i was not > able to 'escape' the spaces. Presuming "remote" has an SSH server running, and that a firewall isn't blocking port 22, and that you've enabled logging in without a password (i.e. ssh-keygen), try the following: import sys import subprocess user = remoteuser hostname = remote cmd = 'python remote.py "%s" "%s" "%s"' % (arg1, arg2, arg3) try: out = subprocess.check_output(['ssh', '%s@%s' % (user, hostname), cmd]) except subprocess.CalledProcessError as e: print >>sys.stderr, str(e) # handle/log the error, retry From oscar.j.benjamin at gmail.com Thu Sep 20 01:40:49 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Sep 2012 00:40:49 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On 19 September 2012 19:00, Gregory Lund wrote: > >>> and then run it from the shell like this: > On Wed, Sep 19, 2012 at 10:20 AM, Peter Otten <__peter__ at web.de> wrote: > > Gregory Lund wrote: > > >>> and then run it from the shell like this: > ahh, windows shell, not python shell. > > from the directions Peter linked to, I shift-right clicked on the > folder where my script resided > (hope that was right) > then after > D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts> > I typed:python unzip_twice.py 2012-09-18 Lab_2.zip > Student_Work_Sample_usecopy1 > where: > unzip_twice.py is the script name as suggested by Steve > 2012-09-18 Lab_2.zip is the zipfile > Student_Work_Sample_usecopy1 is the folder the zipfile resides and > where I want the info extracted to. > > Lucky me... NOT...:-) > I got: > "'python' is not recognized as an internal or external command, > operable program or batch file" (without the quotes of course) > You need to add the folder where python.exe is to your PATH variable. First you need to find the folder where python is on your computer. You can do this from within a python script using the following two lines: import sys print sys.executable Once you've found the folder containing python.exe, add that folder to your PATH variable: http://code.google.com/p/tryton/wiki/AddingPythonToWindowsPath http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 20 12:25:07 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 06:25:07 -0400 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: On Wed, Sep 19, 2012 at 6:13 PM, eryksun wrote: > > cmd = 'python remote.py "%s" "%s" "%s"' % (arg1, arg2, arg3) > > try: > out = subprocess.check_output(['ssh', '%s@%s' % (user, hostname), cmd]) I forgot you need to escape special characters in the arguments. You can add quoting and escape special characters at the same time with the undocumented function pipes.quote: import pipes args = tuple(pipes.quote(arg) for arg in (arg1, arg2, arg3)) cmd = 'python test.py %s %s %s' % args Notice there are no longer quotes around each %s in cmd. Python 3.3 will have shlex.quote: http://docs.python.org/dev/library/shlex.html#shlex.quote Also, if you don't care about the output, use subprocess.check_call() instead. However, the connection still waits for the remote shell's stdout to close. If remote.py is long-running, redirect its stdout to a log file or /dev/null and start the process in the background (&). For example: cmd = 'python remote.py %s %s %s >/dev/null &' % args With this command remote.py is put in the background, stdout closes, the forked sshd daemon on the server exits, and ssh on the client immediately returns. From fomcl at yahoo.com Thu Sep 20 13:58:31 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 20 Sep 2012 04:58:31 -0700 (PDT) Subject: [Tutor] "bisect" vs "in" Message-ID: <1348142311.95653.YahooMailNeo@web110701.mail.gq1.yahoo.com> Hi, ? I want to repeatedly search a list to test whether that list contains a given element X. Of course, I can use membership testing using "in" (list._contains__). But how is this method implemented? It seems to just walk through the whole list from beginning to end (see timeit code below). Is it faster to do a binary search on a sorted list, given that this task has to be done repeatedly? Can such a program be scaled to lists that do not fit into memory (maybe using shelve?)? ? This is the function I made: ? import bisect def binarySearch(haystack, needle): ?return haystack[bisect.bisect_right(haystack, needle) - 1] == needle ? # needle is at the beginning of the sequence >>> t = timeit.Timer("""import bisect def binarySearch(haystack, needle): ?return haystack[bisect.bisect_right(haystack, needle) - 1] == needle binarySearch(range(10**7), 0)""") >>> t.timeit(100) 16.737915573068676 >>> t2 = timeit.Timer("0 in range(10**7)") >>> t2.timeit(100) 16.304621956142682 >>> # needle is at the end of the sequence >>> t = timeit.Timer("""import bisect def binarySearch(haystack, needle): ?return haystack[bisect.bisect_right(haystack, needle) - 1] == needle binarySearch(range(10**7), 10**7-1)""") >>> t.timeit(100) 16.954997632380582 >>> t2 = timeit.Timer("10**7-1 in range(10**7)") >>> t2.timeit(100) 36.3686376341127 Thank you in advance! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From ashish.makani at gmail.com Thu Sep 20 14:17:43 2012 From: ashish.makani at gmail.com (ashish makani) Date: Thu, 20 Sep 2012 17:47:43 +0530 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 3:43 AM, eryksun wrote: > On Wed, Sep 19, 2012 at 2:47 PM, ashish makani > wrote: > > > > I tried this > >>>> import os > >>>> os.system ("ssh remoteuser at remote python remote.py arg1 arg2 arg3") > > > > This worked, but if the arguments i tried to pass, had spaces, i was not > > able to 'escape' the spaces. > > Presuming "remote" has an SSH server running, and that a firewall > isn't blocking port 22, and that you've enabled logging in without a > password (i.e. ssh-keygen), try the following: > > import sys >> import subprocess >> user = remoteuser >> hostname = remote >> cmd = 'python remote.py "%s" "%s" "%s"' % (arg1, arg2, arg3) >> try: >> out = subprocess.check_output(['ssh', '%s@%s' % (user, >> hostname), cmd]) >> except subprocess.CalledProcessError as e: >> print >>sys.stderr, str(e) # handle/log the error, retry > > This worked like a charm. Thank you so much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 20 14:19:33 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 08:19:33 -0400 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 6:25 AM, eryksun wrote: > > I forgot you need to escape special characters in the arguments. You > can add quoting and escape special characters at the same time with > the undocumented function pipes.quote: > > import pipes > > args = tuple(pipes.quote(arg) for arg in (arg1, arg2, arg3)) > cmd = 'python test.py %s %s %s' % args FYI, here's what pipes.quote does. If the string has any special characters, it first replaces any single quotes in the string with '"'"' and then wraps the string in single quotes. For example "abc'def" becomes "'abc'\"'\"'def'". The shell doesn't use special characters ($`\) in single-quoted strings. Source: def quote(file): """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break else: if not file: return "''" return file # use single quotes, and put single quotes into double quotes # the string $'b is then quoted as '$'"'"'b' return "'" + file.replace("'", "'\"'\"'") + "'" From __peter__ at web.de Thu Sep 20 14:58:49 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Sep 2012 14:58:49 +0200 Subject: [Tutor] "bisect" vs "in" References: <1348142311.95653.YahooMailNeo@web110701.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > I want to repeatedly search a list to test whether that list contains a > given element X. Of course, I can use membership testing using "in" > (list._contains__). But how is this method implemented? It seems to just > walk through the whole list from beginning to end (see timeit code below). Indeed. > Is it faster to do a binary search on a sorted list, given that this task > has to be done repeatedly? Much faster. You don't see that in your timings because you include the creation of the range(10**7) list in your measurement. If you used a set instead of a list you could use "in", and it would be even faster than bisect. > Can such a program be scaled to lists that do > not fit into memory (maybe using shelve?)? That would slowdown things a lot. Disk access is *much* slower than RAM. From eryksun at gmail.com Thu Sep 20 15:05:40 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 09:05:40 -0400 Subject: [Tutor] "bisect" vs "in" In-Reply-To: <1348142311.95653.YahooMailNeo@web110701.mail.gq1.yahoo.com> References: <1348142311.95653.YahooMailNeo@web110701.mail.gq1.yahoo.com> Message-ID: On Thu, Sep 20, 2012 at 7:58 AM, Albert-Jan Roskam wrote: > > Can such a program be scaled to lists that do not fit into memory (maybe > using shelve?)? shelve uses a database (e.g. gdbm) based on hashing. It's an unordered mapping. Unlike a dict, the keys must be strings. http://docs.python.org/library/shelve GNU dbm: http://www.gnu.org.ua/software/gdbm/manual/html_node/Intro.html#SEC2 Hash tables: http://en.wikipedia.org/wiki/Hash_table From ghashsnaga at gmail.com Thu Sep 20 16:41:19 2012 From: ghashsnaga at gmail.com (Ara Kooser) Date: Thu, 20 Sep 2012 08:41:19 -0600 Subject: [Tutor] Populating a list with object to be called by a class Message-ID: Morning, I dug out some old code from 5 years ago to clean up and get in working order. It's a simple agent based model. I have class called Ant which contains all the ant-like functions. I have a list that tracks the ants but I did this is a very crude way. I basically copied and pasted everything in there like this: ants = [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"), Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"), .......] I couldn't figure out how to populate the list from a user input. Say if the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which is not an elegant solution. I went back to work on this over the past couple of days but still can't figure out how to populate the list so I end up with Red_1 then Red_2 etc... What would be a good python way to do this? Thank you for your time. ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Sep 20 17:00:16 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 20 Sep 2012 08:00:16 -0700 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: On 9/20/2012 7:41 AM Ara Kooser said... > Morning, > > I dug out some old code from 5 years ago to clean up and get in > working order. It's a simple agent based model. I have class called Ant > which contains all the ant-like functions. > > I have a list that tracks the ants but I did this is a very crude way. I > basically copied and pasted everything in there like this: > > ants = > [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), > > Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), > > Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"), > > Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"), > .......] > > I couldn't figure out how to populate the list from a user input. Say if > the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 > which is not an elegant solution. So, say the desired COUNT is 50, you could do: ants = zip( [ Ant("Red_%s" % c ,"Red","yellow_food") for c in range(COUNT) ], [ Ant("Yellow_%s" % c ,"Yellow","red_food") for c in range(COUNT) ]) Emile From oscar.j.benjamin at gmail.com Thu Sep 20 17:01:23 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Sep 2012 16:01:23 +0100 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: On 20 September 2012 15:41, Ara Kooser wrote: > Morning, > > I dug out some old code from 5 years ago to clean up and get in working > order. It's a simple agent based model. I have class called Ant which > contains all the ant-like functions. > > I have a list that tracks the ants but I did this is a very crude way. I > basically copied and pasted everything in there like this: > > ants = > [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), > > Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), > > Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"), > > Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"), > .......] > > I couldn't figure out how to populate the list from a user input. Say if > the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which > is not an elegant solution. > > I went back to work on this over the past couple of days but still can't > figure out how to populate the list so I end up with Red_1 then Red_2 etc... > > What would be a good python way to do this? > How about this: numants = 500 ants = [] for i in range(1, numants+1): ants.append(Ant('red_%i' % i, 'Red', 'yellow_food')) ants.append(Ant('yellow_%i' % i, 'Yellow', 'red_food')) Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From ghashsnaga at gmail.com Thu Sep 20 17:08:16 2012 From: ghashsnaga at gmail.com (Ara Kooser) Date: Thu, 20 Sep 2012 09:08:16 -0600 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: Oscar, Thanks for that. I feel a bit silly. I forgot about the % which was hanging me up. I am trying to be a better coder. More work ahead for me! ara On Thu, Sep 20, 2012 at 9:01 AM, Oscar Benjamin wrote: > On 20 September 2012 15:41, Ara Kooser wrote: > >> Morning, >> >> I dug out some old code from 5 years ago to clean up and get in working >> order. It's a simple agent based model. I have class called Ant which >> contains all the ant-like functions. >> >> I have a list that tracks the ants but I did this is a very crude way. I >> basically copied and pasted everything in there like this: >> >> ants = >> [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), >> >> Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), >> >> Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"), >> >> Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"), >> .......] >> >> I couldn't figure out how to populate the list from a user input. Say if >> the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which >> is not an elegant solution. >> >> I went back to work on this over the past couple of days but still can't >> figure out how to populate the list so I end up with Red_1 then Red_2 etc... >> >> What would be a good python way to do this? >> > > How about this: > > numants = 500 > > ants = [] > for i in range(1, numants+1): > ants.append(Ant('red_%i' % i, 'Red', 'yellow_food')) > ants.append(Ant('yellow_%i' % i, 'Yellow', 'red_food')) > > Oscar > -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 20 18:25:35 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 12:25:35 -0400 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 10:41 AM, Ara Kooser wrote: > > I have a list that tracks the ants but I did this is a very crude way. I > basically copied and pasted everything in there like this: > > ants = > [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), > Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), Having the type as instance data is limiting. Consider creating the subclasses RedAnt and YellowAnt, instead. For example, "red_food" can be a default argument for YellowAnt. You can also use a class counter variable that gets incremented for each new ant. Then the names can be automatic, too, but with the option to use a specific name. class Ant(object): _count = 0 def __init__(self, name=None, food='food'): cls = self.__class__ if cls == Ant: raise NotImplementedError cls._count += 1 if name is None: self.name = "%s_%s" % (cls.__name__, cls._count) else: self.name = name self.food = food def __repr__(self): clsname = self.__class__.__name__ name = repr(self.name) food = repr(self.food) return "%s(%s, %s)" % (clsname, name, food) def __str__(self): return str(self.name) class RedAnt(Ant): def __init__(self, name=None, food="yellow_food"): super(RedAnt, self).__init__(name, food) class YellowAnt(Ant): def __init__(self, name=None, food="red_food"): super(YellowAnt, self).__init__(name, food) For example: >>> ants = [cls() for i in range(2) for cls in (RedAnt, YellowAnt)] >>> ants [RedAnt('RedAnt_1', 'yellow_food'), YellowAnt('YellowAnt_1', 'red_food'), RedAnt('RedAnt_2', 'yellow_food'), YellowAnt('YellowAnt_2', 'red_food')] >>> print ', '.join(str(a) for a in ants) RedAnt_1, YellowAnt_1, RedAnt_2, YellowAnt_2 >>> Ant() Traceback (most recent call last): File "", line 1, in File "", line 8, in __init__ NotImplementedError >>> RedAnt('Tom', 'mice') RedAnt('Tom', 'mice') >>> YellowAnt('Jerry', 'cheese') YellowAnt('Jerry', 'cheese') >>> RedAnt._count, YellowAnt._count, Ant._count (3, 3, 0) From eryksun at gmail.com Thu Sep 20 18:57:57 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 12:57:57 -0400 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 12:25 PM, eryksun wrote: > > cls._count += 1 I forgot the obligatory warning about class variables. The subclass gets a shallow copy of the parent class namespace. The in-place addition above works because numbers are immutable. However, an in-place operation on a mutable object would modify the value shared by the parent and all other subclasses. Simple example: >>> class X(object): data = [] >>> class Y(X): pass >>> Y.data += [1] >>> X.data # modified parent, too [1] But rebinding the attribute name is OK: >>> Y.data = Y.data + [2] # creates new list >>> Y.data [1, 2] >>> X.data [1] From eryksun at gmail.com Thu Sep 20 19:18:58 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 13:18:58 -0400 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 12:57 PM, eryksun wrote: > > I forgot the obligatory warning about class variables. The subclass > gets a shallow copy of the parent class namespace. The in-place ^^^^^^^^^^^^^^^^^^^ > >>> Y.data += [1] > >>> X.data # modified parent, too > [1] > >>> Y.data = Y.data + [2] # creates new list To clarify, it's not an actual dict.copy in the subclass. In fact, the atrribute is initially only in the parent __dict__, where it's found by object.__getattribute__. In the 2nd example, Y.data on the right-hand side is actually found in the parent class X, then the expression creates a new list which is stored back to Y. From __peter__ at web.de Thu Sep 20 20:35:14 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Sep 2012 20:35:14 +0200 Subject: [Tutor] Populating a list with object to be called by a class References: Message-ID: Ara Kooser wrote: > Morning, > > I dug out some old code from 5 years ago to clean up and get in working > order. It's a simple agent based model. I have class called Ant which > contains all the ant-like functions. > > I have a list that tracks the ants but I did this is a very crude way. I > basically copied and pasted everything in there like this: > > ants = > [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"), > > Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"), > > Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"), > > Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"), > .......] > > I couldn't figure out how to populate the list from a user input. Say if > the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which > is not an elegant solution. > > I went back to work on this over the past couple of days but still can't > figure out how to populate the list so I end up with Red_1 then Red_2 > etc... How boooring. Would you like to be called homo_sapiens_853212547? > What would be a good python way to do this? import os import posixpath import random import urllib import textwrap class Ant: def __init__(self, name): self.name = name def fullname(self): return self.name + " " + self.family def __repr__(self): return self.fullname() class RedAnt(Ant): family = "McAnt" class YellowAnt(Ant): family = "O'Ant" NAMES_URL = "http://www.gro-scotland.gov.uk/files1/stats/pop-names-07-t4.csv" NAMES_FILENAME = posixpath.basename(NAMES_URL) if not os.path.exists(NAMES_FILENAME): urllib.urlretrieve(NAMES_URL, NAMES_FILENAME) names = [] with open(NAMES_FILENAME) as f: for line in f: names += line.split(",")[0::3] names = filter(bool, names) ants = [random.choice((RedAnt, YellowAnt))(name) for name in random.sample(names, 20)] print textwrap.fill(str(ants), 50) Let's do a sample run of the script: $ python ants.py [Sharon McAnt, Shreeram O'Ant, John-Michael McAnt, Patricia McAnt, Lorne McAnt, Kelso O'Ant, Muryam O'Ant, Keilee O'Ant, Timothy O'Ant, Anastacia O'Ant, Zhong O'Ant, Lyndsay O'Ant, Michal McAnt, Emily McAnt, Juwairiyah McAnt, Sukhveer McAnt, Philippa McAnt, Mcbride McAnt, Kaidan McAnt, Sasha O'Ant] > Thank you for your time. You're welcome ;) From ranveer.raghu at gmail.com Thu Sep 20 20:58:36 2012 From: ranveer.raghu at gmail.com (ranveer raghuwanshi) Date: Fri, 21 Sep 2012 00:28:36 +0530 Subject: [Tutor] Understanding cProfile output Message-ID: Hi, I am trying to understand the output of cProfile when run against my python code. The code is: from math import floor,sqrt count = int(floor(sqrt(100000))) max_check = range(2,count+1) original_list = range(2,100001) for j in max_check: temp_list=[] for i in original_list: if i%j==0 and j). *I understand fine that it took around *0.320s for method append.* So, is 16.374 the total time my scripts takes but according to profiler the total time is 16.705. -- Ranveer Raghuwanshi -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Thu Sep 20 21:25:59 2012 From: modulok at gmail.com (Modulok) Date: Thu, 20 Sep 2012 13:25:59 -0600 Subject: [Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine . In-Reply-To: References: Message-ID: > I forgot you need to escape special characters in the arguments. You > can add quoting and escape special characters at the same time with > the undocumented function pipes.quote: > > import pipes > > args = tuple(pipes.quote(arg) for arg in (arg1, arg2, arg3)) > cmd = 'python test.py %s %s %s' % args > > Notice there are no longer quotes around each %s in cmd. Python 3.3 > will have shlex.quote: > > http://docs.python.org/dev/library/shlex.html#shlex.quote Why is ``pipes.quote`` undocumented? It's useful. -Modulok- From steve at pearwood.info Thu Sep 20 21:39:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 21 Sep 2012 05:39:44 +1000 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: <505B7100.7050100@pearwood.info> On 21/09/12 02:57, eryksun wrote: > On Thu, Sep 20, 2012 at 12:25 PM, eryksun wrote: >> >> cls._count += 1 > > I forgot the obligatory warning about class variables. Python is not Java. In Python, classes are first-class objects (no pun intended) and can be assigned to variables the same as any other type. x = something_that_returns_a_float() # x is a float variable s = something_that_returns_a_string() # s is a string variable C = something_that_returns_a_class() # C is a class variable Preferred terminology is attribute, not variable. Class attributes live in the class and are shared across all instances. Instance attributes live in the instance and are not shared. > The subclass gets a shallow copy of the parent class namespace. Not so much. py> class C(object): ... x = 1 ... py> class D(C): pass ... py> D.__dict__ == C.__dict__ False py> 'x' in D.__dict__ False -- Steven From eryksun at gmail.com Thu Sep 20 21:48:05 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 15:48:05 -0400 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: <505B7100.7050100@pearwood.info> References: <505B7100.7050100@pearwood.info> Message-ID: On Thu, Sep 20, 2012 at 3:39 PM, Steven D'Aprano wrote: > On 21/09/12 02:57, eryksun wrote: >> >> On Thu, Sep 20, 2012 at 12:25 PM, eryksun wrote: > > Preferred terminology is attribute, not variable. Class attributes live > in the class and are shared across all instances. Instance attributes > live in the instance and are not shared. That's correct. I try to be careful about terminology, but I slip up from time to time. My first OO language was Java. >> The subclass gets a shallow copy of the parent class namespace. > > > Not so much. > > py> class C(object): > ... x = 1 > ... > py> class D(C): pass > ... > py> D.__dict__ == C.__dict__ > False > py> 'x' in D.__dict__ > False If you didn't notice, I followed up with a correction. But thanks. From steve at pearwood.info Thu Sep 20 21:56:12 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 21 Sep 2012 05:56:12 +1000 Subject: [Tutor] Understanding cProfile output In-Reply-To: References: Message-ID: <505B74DC.1090108@pearwood.info> On 21/09/12 04:58, ranveer raghuwanshi wrote: > Hi, > > I am trying to understand the output of cProfile when run against my python > code. The code is: [...] > What the above code does is it counts the number of prime numbers less than > 1,00,000. > > Now when I profile this code using *python -m cProfile -s time > countPrime.py. *The output I get is http://sprunge.us/SOEj. The output is 13 lines. Please don't waste our time, and yours, publishing it on the web. For trivially small amounts of text like that, just paste it into the body of your email, like this: #result9592 90414 function calls in 16.705 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 16.374 16.374 16.705 16.705 countPrime.py:1() 90407 0.320 0.000 0.320 0.000 {method 'append' of 'list' objects} 2 0.011 0.005 0.011 0.005 {range} 1 0.000 0.000 0.000 0.000 {math.sqrt} 1 0.000 0.000 0.000 0.000 {math.floor} 1 0.000 0.000 0.000 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} This ensures that: * even when the pastebin expires, or the website is shut down, the email archives will include the information necessary to understand your question * people who have access to email but not the web (or their web access is restricted) can still understand your question, or respond > Now what I > don't understand is what it means by *tottime=16.374 for function > countPrime.py:1(). *I understand fine that it took around *0.320s > for method append.* > > So, is 16.374 the total time my scripts takes but according to profiler the > total time is 16.705. I'm not entirely sure, I'd need to look at the source code of the profiler, but I expect that the discrepancy is probably due to the difference between elapsed wall-clock time and processor time. In other words: * it took 16.705 seconds of actual, physical time (as measured by a clock on the wall) to run your script; * but only 16.374 seconds of that was time spent by the processor actually executing your code; the other 0.331 was probably taken up by other processes running on your system, or the operating system itself. -- Steven From steve at pearwood.info Thu Sep 20 21:56:46 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 21 Sep 2012 05:56:46 +1000 Subject: [Tutor] Populating a list with object to be called by a class In-Reply-To: References: Message-ID: <505B74FE.3040200@pearwood.info> On 21/09/12 03:18, eryksun wrote: > On Thu, Sep 20, 2012 at 12:57 PM, eryksun wrote: >> >> I forgot the obligatory warning about class variables. The subclass >> gets a shallow copy of the parent class namespace. The in-place > ^^^^^^^^^^^^^^^^^^^ >> >>> Y.data += [1] >> >>> X.data # modified parent, too >> [1] >> >>> Y.data = Y.data + [2] # creates new list > > To clarify, it's not an actual dict.copy in the subclass. Ah, I didn't notice you had corrected yourself before sending my own correction. > In fact, the > atrribute is initially only in the parent __dict__, where it's found > by object.__getattribute__. In the 2nd example, Y.data on the > right-hand side is actually found in the parent class X, then the > expression creates a new list which is stored back to Y. Pretty much. Inheritance couldn't work correctly if subclasses made copies of their parent namespaces. -- Steven From d at davea.name Thu Sep 20 22:46:02 2012 From: d at davea.name (Dave Angel) Date: Thu, 20 Sep 2012 16:46:02 -0400 Subject: [Tutor] Understanding cProfile output In-Reply-To: <505B74DC.1090108@pearwood.info> References: <505B74DC.1090108@pearwood.info> Message-ID: <505B808A.8010403@davea.name> On 09/20/2012 03:56 PM, Steven D'Aprano wrote: > On 21/09/12 04:58, ranveer raghuwanshi wrote: >> Hi, >> >> I am trying to understand the output of cProfile when run against my >> python >> code. The code is: > [...] >> What the above code does is it counts the number of prime numbers >> less than >> 1,00,000. >> >> Now when I profile this code using *python -m cProfile -s time >> countPrime.py. > > > #result9592 > 90414 function calls in 16.705 seconds > > Ordered by: internal time > > ncalls tottime percall cumtime percall filename:lineno(function) > 1 16.374 16.374 16.705 16.705 countPrime.py:1() > 90407 0.320 0.000 0.320 0.000 {method 'append' of > 'list' objects} > 2 0.011 0.005 0.011 0.005 {range} > 1 0.000 0.000 0.000 0.000 {math.sqrt} > 1 0.000 0.000 0.000 0.000 {math.floor} > 1 0.000 0.000 0.000 0.000 {len} > 1 0.000 0.000 0.000 0.000 {method 'disable' of > '_lsprof.Profiler' objects} > > > > >> Now what I >> don't understand is what it means by *tottime=16.374 for function >> countPrime.py:1(). *I understand fine that it took around >> *0.320s >> for method append.* >> >> So, is 16.374 the total time my scripts takes but according to >> profiler the >> total time is 16.705. > I don't know the Python profiler, but I've worked with many others over the years (and even written one). It looks like it follows very reasonable conventions in its output. tottime is the total time spent in that function, including the functions it calls. cumtime is the cumulative time spent in that function, after deducting for any functions it may have called. So in approximate numbers, 16.705 = 16.374 + .320 + .011 Both columns are very useful, as is the ncalls column. However, the net result is you didn't learn very much about the efficiency of your algorithm. Are you looking for suggestions for speeding it up? Or suggestions for getting more interesting results from profiling? -- DaveA From ranveer.raghu at gmail.com Thu Sep 20 23:15:26 2012 From: ranveer.raghu at gmail.com (ranveer raghuwanshi) Date: Fri, 21 Sep 2012 02:45:26 +0530 Subject: [Tutor] Understanding cProfile output In-Reply-To: <505B808A.8010403@davea.name> References: <505B74DC.1090108@pearwood.info> <505B808A.8010403@davea.name> Message-ID: Thanks for the input everyone. @Dave, I basically implemented the sieve of eratosthenes to fiind the number of prime numbers in a given range. So, yes I am looking for suggestions to speed it up. On Fri, Sep 21, 2012 at 2:16 AM, Dave Angel wrote: > On 09/20/2012 03:56 PM, Steven D'Aprano wrote: > > On 21/09/12 04:58, ranveer raghuwanshi wrote: > >> Hi, > >> > >> I am trying to understand the output of cProfile when run against my > >> python > >> code. The code is: > > [...] > >> What the above code does is it counts the number of prime numbers > >> less than > >> 1,00,000. > >> > >> Now when I profile this code using *python -m cProfile -s time > >> countPrime.py. > > > > > > #result9592 > > 90414 function calls in 16.705 seconds > > > > Ordered by: internal time > > > > ncalls tottime percall cumtime percall filename:lineno(function) > > 1 16.374 16.374 16.705 16.705 countPrime.py:1() > > 90407 0.320 0.000 0.320 0.000 {method 'append' of > > 'list' objects} > > 2 0.011 0.005 0.011 0.005 {range} > > 1 0.000 0.000 0.000 0.000 {math.sqrt} > > 1 0.000 0.000 0.000 0.000 {math.floor} > > 1 0.000 0.000 0.000 0.000 {len} > > 1 0.000 0.000 0.000 0.000 {method 'disable' of > > '_lsprof.Profiler' objects} > > > > > > > > > >> Now what I > >> don't understand is what it means by *tottime=16.374 for function > >> countPrime.py:1(). *I understand fine that it took around > >> *0.320s > >> for method append.* > >> > >> So, is 16.374 the total time my scripts takes but according to > >> profiler the > >> total time is 16.705. > > > I don't know the Python profiler, but I've worked with many others over > the years (and even written one). It looks like it follows very > reasonable conventions in its output. > > tottime is the total time spent in that function, including the > functions it calls. cumtime is the cumulative time spent in that > function, after deducting for any functions it may have called. So in > approximate numbers, 16.705 = 16.374 + .320 + .011 > > Both columns are very useful, as is the ncalls column. However, the net > result is you didn't learn very much about the efficiency of your > algorithm. > > Are you looking for suggestions for speeding it up? Or suggestions for > getting more interesting results from profiling? > > > > -- > > DaveA > > -- Ranveer Raghuwanshi -------------- next part -------------- An HTML attachment was scrubbed... URL: From bardockarngrim at hotmail.com Fri Sep 21 00:31:14 2012 From: bardockarngrim at hotmail.com (Brett Dailey) Date: Thu, 20 Sep 2012 18:31:14 -0400 Subject: [Tutor] Help Message-ID: I'm having trouble with a small project. Here's what it needs to do: Has variables for window width and window height and creates a window of that size. Has variables which control the number of columns and number of rows. From this, create a checkboard pattern which evenly fills the window. On approximately 10% of the squares (chosen at random) draw an image which is sized to just fit inside a checkboard square (use the smallest dimension). Keep the program open for 3 seconds and then quit. I've attached the code I have so far. "Pic" is just a place holder for an actual image. Not sure what to do with the while statements that are empty in the code. Thanks for the help, Brett -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: game_board.py Type: text/x-python-script Size: 676 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Sep 21 00:54:59 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Sep 2012 22:54:59 +0000 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> People on this list are not all receiving this via email. It is recommended that you post 1. plain text (instead of Rich Text or HTML) 2. Just include the code directly in the email if it is short (which this is) or post to a website like pastebin for large samples. I have included the code below for the benefit of readers that do not receive attachments. Brett Dailey wrote: > I'm having trouble with a small project. Here's what it needs to do: > > Has variables for window width and window height and creates a window of that > size. > Has variables which control the number of columns and number of rows. > From this, create a checkboard pattern which evenly fills the window. On > approximately 10% of the squares (chosen at random) draw an image which is > sized to just fit inside a checkboard square (use the smallest dimension). > Keep the program open for 3 seconds and then quit. > > I've attached the code I have so far. > "Pic" is just a place holder for an actual image. > Not sure what to do with the while statements that are empty in the code. > > > Thanks for the help, > Brett > # Lab 3: Game Board import pygame import time pygame.display.init() WinH = 600 WinW = 800 num_rows = 8 num_cols = 12 screen = pygame.display.set_mode((WinW,WinH)) screen.fill((128,128,128)) markSurf = pygame.image.load("#Pic") color = (0,0,0) cell_width = WinW/num_cols cell_height = WinH/num_rows while #... while #... pygame.draw.rect(screen, color, (cell_width,cell_height), 0) if color == (0,0,0): color = (0,255,0) else: color = (0,0,0) curRow = 0 while curRow < #....: if curRow %2 = 0: color = (0,0,0) else: color = (0,255,0) curRow +=1 pygame.display.update() time.sleep(3) pygame.display.quit() This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From eryksun at gmail.com Fri Sep 21 03:59:31 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 20 Sep 2012 21:59:31 -0400 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On Thu, Sep 20, 2012 at 6:31 PM, Brett Dailey wrote: > > From this, create a checkboard pattern which evenly fills the window. On > approximately 10% of the squares (chosen at random) draw an image which is > sized to just fit inside a checkboard square (use the smallest dimension). > Keep the program open for 3 seconds and then quit. Do you need to preserve the aspect ratio of the image? If so, should the image be scaled or scaled/cropped? From steve at pearwood.info Fri Sep 21 04:15:33 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 21 Sep 2012 12:15:33 +1000 Subject: [Tutor] Help In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> Message-ID: <505BCDC5.3080702@pearwood.info> On 21/09/12 08:54, Prasad, Ramit wrote: > People on this list are not all receiving this via email. They're not? How else can you receive this? Unlike the main python-list, this isn't (as far as I know) mirrored on Usenet. I wonder under what circumstances people could read this email without seeing any attachments. > It is > recommended that you post 1. plain text (instead of Rich Text or HTML) Agreed. > 2. Just include the code directly in the email if it is short (which this > is) Agreed. >or post to a website like pastebin for large samples. Not agreed. Pastebins expire, or their websites disappear. In three months or three years, code pasted to a bin will probably no longer exist and nobody reading this thread via the web archives will have any clue what is being talked about. Also, some people will be reading this thread via email but be behind a firewall that limits their access to the web so that they cannot reach the pastebin. -- Steven From d at davea.name Fri Sep 21 04:22:43 2012 From: d at davea.name (Dave Angel) Date: Thu, 20 Sep 2012 22:22:43 -0400 Subject: [Tutor] Understanding cProfile output In-Reply-To: References: <505B74DC.1090108@pearwood.info> <505B808A.8010403@davea.name> Message-ID: <505BCF73.6090402@davea.name> On 09/20/2012 05:15 PM, ranveer raghuwanshi wrote: > Thanks for the input everyone. > > @Dave, I basically implemented the sieve of eratosthenes to fiind the > number of prime numbers in a given range. So, yes I am looking for > suggestions to speed it up. > Please don't top-post on this forum. It puts your response out of order with the parts you quote. Put your remarks AFTER the quotes. There are some very clever algorithms out there, and probably the fastest is to download a list of primes from some website (I'm sure we could find it by searching) I don't pretend to know which is the best one. But if you just want your algorithm tweaked, I could suggest that you could greatly reduce the number of comparisons by doing the modulo only on the PRIMES below max_check. Reverse your two loops, so the inner loop is the one that loops over the divisors. Don't do all that list manipulation, just solve the problem. In the code below, your algorithm is prime1(). Then I have prime2() and prime3(), which are equivalent algorithms, yielding approximately 25- and 35-fold improvement. I'm sure there are better algorithms, and ones that don't involve such large lists. But these are true to the original concept, of the sieve. from math import floor,sqrt import time as timer def prime1(limit): count = int(floor(sqrt(100000))) max_check = range(2,count+1) original_list = range(2,100001) for j in max_check: temp_list=[] for i in original_list: if i%j==0 and j References: <5059EC54.6040804@pearwood.info> Message-ID: > > You need to add the folder where python.exe is to your PATH variable. > > First you need to find the folder where python is on your computer. You can > do this from within a python script using the following two lines: > import sys > print sys.executable > > Once you've found the folder containing python.exe, add that folder to your > PATH variable: > http://code.google.com/p/tryton/wiki/AddingPythonToWindowsPath > http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 Thanks, I'll give it a shot tomorrow morning. Brain is fried right now. Greg > > Oscar From daedae11 at 126.com Fri Sep 21 11:11:06 2012 From: daedae11 at 126.com (Dae James) Date: Fri, 21 Sep 2012 17:11:06 +0800 Subject: [Tutor] How can I convert a variable name to a string? Message-ID: <201209211711061661484@126.com> How can I convert a variable name to a string ? For example: testVariable = 1000; How can I get the string "testVariable" ? Thank you~ Dae James -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Sep 21 12:51:18 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 21 Sep 2012 03:51:18 -0700 (PDT) Subject: [Tutor] application whitelisting Message-ID: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> Hi, My company just started application whitelisting. Now a new version of a (benign!!) dll does not work as it (or rather, its file hash, if I understood it correctly) is not whitelisted. Is there any way I can use the same dll of a newer version? I know this sounds like a hacking request, but my intentions are sincere. My only purpose is to use ctypes to use the functions that are present in the new, but not the old, dll version. The code below is probably simplistic/naive, but it's a product of my frustration + curiosity. The strategy was to generate a dll that has the same file hash as the original dll by right-padding it with zero until the desired checksum is found. Why a zero? No idea. ;-) PS: I guess virtual environment also cannot be used for this, right? import hashlib import contextlib def generateFile(infile, desired_hash, hashtype="md5"): ??? outfile = infile[:-4] + "_adjusted.dll" ??? hashlib_ = hashlib.new(hashtype) ??? with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in, f_out): ??????? observed_hash = hashlib_(f_in.read()) ??????? found = observed_hash.hexdigest() == desired_hash ??????? counter = 0 ??????? while True: ??????????? counter += 1 ??????????? observed_hash.update("0") ??????????? if found: ??????????????? f_out.write(f_in.read() + (counter * "0")) ??????????????? print "Got it: '%s'" f_out.name ??????????????? break infile = r"D:\temp\myown.dll" generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9') ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Sep 21 13:26:07 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 21 Sep 2012 13:26:07 +0200 Subject: [Tutor] How can I convert a variable name to a string? In-Reply-To: <201209211711061661484@126.com> References: <201209211711061661484@126.com> Message-ID: On Fri, Sep 21, 2012 at 11:11 AM, Dae James wrote: > ** > How can I convert a variable name to a string ? > For example: > testVariable = 1000; > How can I get the string "testVariable" ? > Thank you~ > > Well, the locals() dictionary will have a "testVariable" entry in it.. but if I may ask, why would you want to do this? I see no reason this would ever be necessary. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Sep 21 14:04:03 2012 From: d at davea.name (Dave Angel) Date: Fri, 21 Sep 2012 08:04:03 -0400 Subject: [Tutor] application whitelisting In-Reply-To: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: <505C57B3.5040309@davea.name> On 09/21/2012 06:51 AM, Albert-Jan Roskam wrote: > Hi, > > My company just started application whitelisting. Now a new version of a (benign!!) dll does not work as it (or rather, its file hash, if I understood it correctly) is not whitelisted. Is there any way I can use the same dll of a newer version? I know this sounds like a hacking request, but my intentions are sincere. My only purpose is to use ctypes to use the functions that are present in the new, but not the old, dll version. > > > The code below is probably simplistic/naive, but it's a product of my frustration + curiosity. The strategy was to generate a dll that has the same file hash as the original dll by right-padding it with zero until the desired checksum is found. Why a zero? No idea. ;-) Two catches I can think of: 1) any decent white-lister would have both a hashcode and a size for each file it's protecting. 2) On the average, you'll be adding more bytes to that file than exist in all the disks of all the computers in the solar system, MANY times over. (The number in decimal has something like 40 digits in it) > PS: I guess virtual environment also cannot be used for this, right? > Not as far as I know, but there are many others much more familiar with python virtual environment. If this were my problem, and if i had sufficient rights on the machine, I'd install a Virtual Machine, and run things there. But of course you'd have to get that past the white-listers. > import hashlib > import contextlib > > def generateFile(infile, desired_hash, hashtype="md5"): > outfile = infile[:-4] + "_adjusted.dll" > hashlib_ = hashlib.new(hashtype) > with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in, f_out): > observed_hash = hashlib_(f_in.read()) > found = observed_hash.hexdigest() == desired_hash > counter = 0 > while True: > counter += 1 > observed_hash.update("0") > if found: > f_out.write(f_in.read() + (counter * "0")) This limits file size to what will fit in memory in a single string. Assuming you have millions of petabytes of disk space and only a few gigabytes of available RAM, you should write a loop for the counter bytes, perhaps chunking it for compromise between memory and speed. If the numbers weren't SO huge, and if you were running on Linux, perhaps a sparse file would save both a lot of time and a lot of actual disk space. I have no experience with them, however -- it'd be fun to learn. > print "Got it: '%s'" f_out.name > break > > infile = r"D:\temp\myown.dll" > generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9') > There are known ways to break md5; it's no longer considered cryptographically secure. But a trial and error method will take way too long and this particular trial and error method will also take way too much disk space. Still, I'm surprised the creators of the whitelist didn't use sha1 or sha256. Two practical methods: 1) run it on your own machine, not under their control 2) convince them to add your particular dll to their whitelist. -- DaveA From __peter__ at web.de Fri Sep 21 14:19:12 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Sep 2012 14:19:12 +0200 Subject: [Tutor] application whitelisting References: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > Hi, > > My company just started application whitelisting. Now a new version of a > (benign!!) dll does not work as it (or rather, its file hash, if I > understood it correctly) is not whitelisted. Is there any way I can use > the same dll of a newer version? I know this sounds like a hacking > request, but my intentions are sincere. My only purpose is to use ctypes > to use the functions that are present in the new, but not the old, dll > version. > > > The code below is probably simplistic/naive, but it's a product of my > frustration + curiosity. The strategy was to generate a dll that has the > same file hash as the original dll by right-padding it with zero until the > desired checksum is found. Why a zero? No idea. ;-) > > PS: I guess virtual environment also cannot be used for this, right? > > > import hashlib > import contextlib > > def generateFile(infile, desired_hash, hashtype="md5"): > outfile = infile[:-4] + "_adjusted.dll" > hashlib_ = hashlib.new(hashtype) > with contextlib.nested(open(infile, "rb"), open(outfile, "wb")) as (f_in, > f_out): observed_hash = hashlib_(f_in.read()) > found = observed_hash.hexdigest() == desired_hash > counter = 0 > while True: > counter += 1 > observed_hash.update("0") > if found: > f_out.write(f_in.read() + (counter * "0")) > print "Got it: '%s'" f_out.name > break > > infile = r"D:\temp\myown.dll" > generateFile(infile, '4151e067c17a753fc5c4ec1c507d28c9') Here's a back-of-the-envelope calculation: '4151e067c17a753fc5c4ec1c507d28c9' is a hexadecimal number with 32 digits, otherwise known as 340282366920938463463374607431768211456L If you are trying to hit that number using random additions to your file you can expect success after (that number)/2 attempts. Assuming you try 10 million additions per second that will take about >>> (16**32//2)/(10**7 * 60 * 60 * 24 * 365) 539514153540300709448526L years. But you are lucky, md5 has been cracked. I don't know if there is a practical way to create a document with the same hash for any given hash though, so as a starting point I refer you to http://en.wikipedia.org/wiki/Md5 Looking forward to see your final script... Or you think a bit out of the box and ask for the required dll to be put on the whitelist. From hugo.yoshi at gmail.com Fri Sep 21 14:30:49 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 21 Sep 2012 14:30:49 +0200 Subject: [Tutor] application whitelisting In-Reply-To: References: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: On Fri, Sep 21, 2012 at 2:19 PM, Peter Otten <__peter__ at web.de> wrote: > > Here's a back-of-the-envelope calculation: > > '4151e067c17a753fc5c4ec1c507d28c9' is a hexadecimal number with 32 digits, > otherwise known as > > 340282366920938463463374607431768211456L > > If you are trying to hit that number using random additions to your file > you > can expect success after (that number)/2 attempts. Assuming you try 10 > million additions per second that will take about > > >>> (16**32//2)/(10**7 * 60 * 60 * 24 * 365) > 539514153540300709448526L > > years. > > But you are lucky, md5 has been cracked. I don't know if there is a > practical way to create a document with the same hash for any given hash > though, so as a starting point I refer you to As a short answer, there is no practical way to do this (there is a theoretical one, but it's still computationally infeasible). There is a way to generate two files (e.g. an innocent one and an evil one) with identical md5 hashes just by appending a few thousand bytes to each file. If you get the innocent file accepted into the whitelist both will work. At that point it's easier to just get the ctypes dll on the whitelist itself though, since it is innocent anyway. -------------- next part -------------- An HTML attachment was scrubbed... URL: From existentialleo at gmail.com Fri Sep 21 15:31:53 2012 From: existentialleo at gmail.com (Leo Degon) Date: Fri, 21 Sep 2012 09:31:53 -0400 Subject: [Tutor] Question about lists Message-ID: I'm trying to create a class where the main focus is creating a list whose elements are lists and the elements of those lists are collection of zeros and ones. I am trying to create functions to rotate the list ninety degrees, to reflect it. Having a few problems with the rotation. get TypeError: 'list' object is not callable def pset(n): for i in n: print(i) class board(): def make(self,size): b=[] for i in range(size[0]): b.append([]) for j in range(size[1]): b[i].append(0) return b def rotate(self,board,size): size[0],size[1]=size[1],size[0] new=board(size) lists=[] for j in range(size[1]): lists.append([]) for i in range(size[0]).__reversed__(): lists[j].append(board[i][j]) for i in range(size[1]): for j in range(size[0]): new.board[i,j]=lists[i,j] return(new.board) def __init__(self,size): self.size=size self.board=self.make(size) y=[7,7] x=board(y) pset(x.board) x.board[0][0]=1 print() pset(x.board) print() x.board=x.rotate(x.board,x.size) pset(x.board) print() -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Sep 21 15:53:30 2012 From: d at davea.name (Dave Angel) Date: Fri, 21 Sep 2012 09:53:30 -0400 Subject: [Tutor] Question about lists In-Reply-To: References: Message-ID: <505C715A.30000@davea.name> On 09/21/2012 09:31 AM, Leo Degon wrote: > I'm trying to create a class where the main focus is creating a list whose > elements are lists and the elements of those lists are collection of zeros > and ones. I am trying to create functions to rotate the list ninety > degrees, to reflect it. Having a few problems with the rotation. > get TypeError: 'list' object is not callable Where is the rest of the error message? And don't forget to mention which Python version you're using. > def pset(n): > for i in n: > print(i) > class board(): One Python convention which would have helped here is to use capital for the class name, Board Another one is to put __init__ first, since that tells us what instance attributes you'll be using, and how they're initialized. > def make(self,size): > b=[] > for i in range(size[0]): > b.append([]) > for j in range(size[1]): > b[i].append(0) > return b > > def rotate(self,board,size): You've now defined a new local called board, which shadows the class name board. Is there a reason you didn't use self.board ? As it's presently coded, this method doesn't seem to use any instance attributes. > size[0],size[1]=size[1],size[0] > new=board(size) > lists=[] > for j in range(size[1]): > lists.append([]) > for i in range(size[0]).__reversed__(): > lists[j].append(board[i][j]) > for i in range(size[1]): > for j in range(size[0]): > new.board[i,j]=lists[i,j] > return(new.board) > def __init__(self,size): > self.size=size > self.board=self.make(size) > y=[7,7] > x=board(y) > pset(x.board) > x.board[0][0]=1 > print() > pset(x.board) > print() > x.board=x.rotate(x.board,x.size) > pset(x.board) > print() > > -- DaveA From steve at pearwood.info Fri Sep 21 16:00:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Sep 2012 00:00:50 +1000 Subject: [Tutor] How can I convert a variable name to a string? In-Reply-To: <201209211711061661484@126.com> References: <201209211711061661484@126.com> Message-ID: <505C7312.8050101@pearwood.info> On 21/09/12 19:11, Dae James wrote: > How can I convert a variable name to a string ? > For example: > testVariable = 1000; > How can I get the string "testVariable" ? You can't. Any value could have zero, one or many names, and there is no way to go backwards from the object to the name. What are you trying to do that you think you need this? -- Steven From __peter__ at web.de Fri Sep 21 16:04:47 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Sep 2012 16:04:47 +0200 Subject: [Tutor] Question about lists References: Message-ID: Leo Degon wrote: > I'm trying to create a class where the main focus is creating a list whose > elements are lists and the elements of those lists are collection of zeros > and ones. I am trying to create functions to rotate the list ninety > degrees, to reflect it. Having a few problems with the rotation. > get TypeError: 'list' object is not callable > > def pset(n): > for i in n: > print(i) > class board(): > def make(self,size): > b=[] > for i in range(size[0]): > b.append([]) > for j in range(size[1]): > b[i].append(0) > return b > > def rotate(self,board,size): The local parameter "board" shades the class with the same name, > size[0],size[1]=size[1],size[0] > new=board(size) so here you are not making a new board instance but instead trying to call the board parameter which is a list. To fix this problem you have to rename the parameter or the class. I recommend that you rename the class to Board (by convention class names start with an uppercase letter). As to the parameter board, you actually don't need it at all -- you can instead make the board attribute of the new Board instance a rotated version of self.board. (There are more bugs in your code, but I suggest you tackle them one at a time. Come back here if you need help fixing them) > lists=[] > for j in range(size[1]): > lists.append([]) > for i in range(size[0]).__reversed__(): > lists[j].append(board[i][j]) > for i in range(size[1]): > for j in range(size[0]): > new.board[i,j]=lists[i,j] > return(new.board) > def __init__(self,size): > self.size=size > self.board=self.make(size) > y=[7,7] > x=board(y) > pset(x.board) > x.board[0][0]=1 > print() > pset(x.board) > print() > x.board=x.rotate(x.board,x.size) > pset(x.board) > print() From hugo.yoshi at gmail.com Fri Sep 21 16:07:04 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 21 Sep 2012 16:07:04 +0200 Subject: [Tutor] Question about lists In-Reply-To: References: Message-ID: On Fri, Sep 21, 2012 at 3:31 PM, Leo Degon wrote: > I'm trying to create a class where the main focus is creating a list whose > elements are lists and the elements of those lists are collection of zeros > and ones. I am trying to create functions to rotate the list ninety > degrees, to reflect it. Having a few problems with the rotation. > get TypeError: 'list' object is not callable > > def pset(n): > for i in n: > print(i) > class board(): > def make(self,size): > b=[] > for i in range(size[0]): > b.append([]) > for j in range(size[1]): > b[i].append(0) > return b > > def rotate(self,board,size): > size[0],size[1]=size[1],size[0] > new=board(size) > lists=[] > for j in range(size[1]): > lists.append([]) > for i in range(size[0]).__reversed__(): > lists[j].append(board[i][j]) > for i in range(size[1]): > for j in range(size[0]): > new.board[i,j]=lists[i,j] > return(new.board) > def __init__(self,size): > self.size=size > self.board=self.make(size) > y=[7,7] > x=board(y) > pset(x.board) > x.board[0][0]=1 > print() > pset(x.board) > print() > x.board=x.rotate(x.board,x.size) > pset(x.board) > print() > > Please always include a full traceback, it makes the error much more obvious. For example, running your code I get: >>> [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] () [1, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] () Traceback (most recent call last): File "C:/Users/hugo/Downloads/test.py", line 35, in x.board=x.rotate(x.board,x.size) File "C:/Users/hugo/Downloads/test.py", line 15, in rotate new=board(size) TypeError: 'list' object is not callable >>> This makes it fairly obvious what is going on. in the rotate function, you have an argument called board, and your class is also called board. You can't have the same name refer to two different things. What happens is that the argument "masks" the class, making it inaccessible. I should also say it is very confusing to have a class called board with an attribute that is also called board. You should think about naming your variables more clearly to minimize confusion. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Sep 21 16:33:57 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Sep 2012 14:33:57 +0000 Subject: [Tutor] Help In-Reply-To: <505BCDC5.3080702@pearwood.info> References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> Steven D'Aprano wrote: > On 21/09/12 08:54, Prasad, Ramit wrote: > > People on this list are not all receiving this via email. > > > They're not? How else can you receive this? Unlike the main python-list, > this isn't (as far as I know) mirrored on Usenet. > > I wonder under what circumstances people could read this email without > seeing any attachments. My mistake, I was under the impression it was mirrored on Usenet. > > > > It is > > recommended that you post 1. plain text (instead of Rich Text or HTML) > > Agreed. > > > 2. Just include the code directly in the email if it is short (which this > > is) > > Agreed. > > >or post to a website like pastebin for large samples. > > Not agreed. Pastebins expire, or their websites disappear. In three > months or three years, code pasted to a bin will probably no longer exist > and nobody reading this thread via the web archives will have any clue > what is being talked about. > > Also, some people will be reading this thread via email but be behind a > firewall that limits their access to the web so that they cannot reach > the pastebin. > Ironically, that describes me. So what is the preference for large code samples? Just always include it? What about for the main list? This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Fri Sep 21 16:41:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Sep 2012 00:41:31 +1000 Subject: [Tutor] application whitelisting In-Reply-To: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: <505C7C9B.2030507@pearwood.info> On 21/09/12 20:51, Albert-Jan Roskam wrote: > Hi, > > My company just started application whitelisting. Now a new version of >a (benign!!) dll does not work as it (or rather, its file hash, if I >understood it correctly) is not whitelisted. Then get it whitelisted. If your company doesn't have the ability to update the whitelist when your software updates, it's even more stupid than it seems. Application whitelisting is a poor idea. The first time you run a Windows update, *everything will break*. Unless of course you trust software from Microsoft -- or rather, you trust software that you *think* is from Microsoft. So right there you have a vulnerability: any malware that can steal a certificate, or sign up for a "legitimate" certificate, will be trusted. Whitelisting doesn't protect you from infected PDF files, buffer overflows, code injection attacks, XSS attacks, Flash, etc. It's yet another buzzword that *at best* will temporarily protect you from a few threats while doing absolutely nothing about solving the actual problem. > The code below is probably simplistic/naive, but it's a product of my >frustration + curiosity. The strategy was to generate a dll that has the >same file hash as the original dll by right-padding it with zero until >the desired checksum is found. Why a zero? No idea. ;-) It's worse than that. If the application whitelist is using md5 (and wanna bet that at least 50% of the commercial whitelist software out there is?), then it is already broken. An attacker can easily take an arbitrary application, and generate a new application with the same MD5 sum and the same length, differing by 128 bytes. http://www.mscs.dal.ca/~selinger/md5collision/ Is 128 bytes enough to compromise the application and turn it into an attack tool? I don't know, but probably. -- Steven From bala.biophysics at gmail.com Fri Sep 21 17:07:36 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Fri, 21 Sep 2012 17:07:36 +0200 Subject: [Tutor] np array.any() question Message-ID: Friends, May i know why do get a Valuerror if i check any value in a is between 3.0 to 5.0 ? >>> import numpy as np >>> a=np.array([ 2.5, 2.6, 3.0 , 3.5, 4.0 , 5.0 ]) >>> (a > 7).any() False >>> (a > 4).any() True >>> (3 < a < 5).any() Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Thanks, Bala From malaclypse2 at gmail.com Fri Sep 21 17:18:15 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 21 Sep 2012 11:18:15 -0400 Subject: [Tutor] Help In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Sep 21, 2012 at 10:33 AM, Prasad, Ramit wrote: > Ironically, that describes me. So what is the preference for large > code samples? Just always include it? What about for the main list? It's tricky. Ideally, you need to take your large code base, and reduce it into a short piece of sample code that is runnable and reproduces your issue. Yes, this can be hard to do, and yes, it can take a lot of time. It should be as short as possible, trimming out all of the extraneous functions and calls. It needs to be short enough that someone interested can actually read it and understand what you're trying to accomplish. It needs to be long enough to actually demonstrate the problem you're having. It's worth the trouble though -- anything longer than a page or two of code is going to get glossed over by many readers -- they just don't have time to read and understand your code, see where you're having a problem and diagnose the issue for you. You're much more likely to get help with a 10 or 20 line sample than with a 100 or 200 line one, much less something that's thousands of lines of code. The people here are volunteers -- the best way to engage them in your problem is to be respectful of their time. Often, that means spending extra time of your own to save their time. In many cases, the act of trimming your code down to that form will actually cause you to find the answer to your own question without even needing to send it. This process is sometimes known as "rubber ducking" -- http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html I can't count the number of times that I've had a problem, decided to send it to a mailing list for help, and in the process of fully describing the problem I'm having, come up with the solution without even having to send the email. -- Jerry From steve at pearwood.info Fri Sep 21 17:25:54 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Sep 2012 01:25:54 +1000 Subject: [Tutor] np array.any() question In-Reply-To: References: Message-ID: <505C8702.7040606@pearwood.info> On 22/09/12 01:07, Bala subramanian wrote: > Friends, > May i know why do get a Valuerror if i check any value in a is between > 3.0 to 5.0 ? >>>> import numpy as np >>>> a=np.array([ 2.5, 2.6, 3.0 , 3.5, 4.0 , 5.0 ]) >>>> (a> 7).any() > False This calculates an array of bools, then calls any() on it. py> a > 7 array([False, False, False, False, False, False], dtype=bool) py> (a > 7).any() False >>>> (a> 4).any() > True This also builds an array of bools, then calls any(): py> a > 4 array([False, False, False, False, False, True], dtype=bool) py> (a > 4).any() True >>>> (3< a< 5).any() > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() This tries to calculate: (3 < a) and (a < 5) py> 3 < a array([False, False, False, True, True, True], dtype=bool) py> a < 5 array([ True, True, True, True, True, False], dtype=bool) but combining them with the "and" operator is ambiguous: py> (3 < a) and (a < 5) Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Since the boolean "and" of the two arrays never gets calculated, the any method never gets called. You could do: py> (3 < a).any() and (a < 5).any() True which I think does what you want. -- Steven From oscar.j.benjamin at gmail.com Fri Sep 21 17:32:52 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 21 Sep 2012 16:32:52 +0100 Subject: [Tutor] np array.any() question In-Reply-To: References: Message-ID: On Sep 21, 2012 4:09 PM, "Bala subramanian" wrote: > > Friends, > May i know why do get a Valuerror if i check any value in a is between > 3.0 to 5.0 ? > >>> import numpy as np > >>> a=np.array([ 2.5, 2.6, 3.0 , 3.5, 4.0 , 5.0 ]) > >>> (a > 7).any() > False > >>> (a > 4).any() > True > >>> (3 < a < 5).any() > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() You need to use ((3 < a) & (a <5)).any() The problem is not with any(). The problem is that the multiple binary comparison needs to convert its intermediate results to bool. So (3 < a < 5) is processed as: (3 < a) and (a < 5) To process the 'and' operator python needs to know if the first expression is True. This means calling bool(3 < a). But, since (3 < a) is an array of booleans it cannot be said to be True or False. This is what gives the ValueError that you see. If you use bitwise-and '&' instead of logical-and 'and' it will perform the and operation separately on each element of each array which is what you want. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Sep 21 17:33:43 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Sep 2012 01:33:43 +1000 Subject: [Tutor] Help In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> Message-ID: <505C88D7.4050906@pearwood.info> On 22/09/12 01:18, Jerry Hill wrote: > On Fri, Sep 21, 2012 at 10:33 AM, Prasad, Ramit > wrote: >> Ironically, that describes me. So what is the preference for large >> code samples? Just always include it? What about for the main list? > > It's tricky. > > Ideally, you need to take your large code base, and reduce it into a > short piece of sample code that is runnable and reproduces your issue. +10000 on this. See also: http://sscce.org/ But, suppose you try really hard, and the shortest you can get your code down is 200 lines (for example). What then? There is no good answer. Speaking for myself, I would prefer that you attach the file to your email. But others will be unhappy if you do that, and will prefer that you use a pastebin. But if you use a pastebin, I will be unhappy (I am probably not the only one). So whatever you do, you will make somebody unhappy. Oh well, that's life. > In many cases, the act of trimming your code down to that form will > actually cause you to find the answer to your own question without > even needing to send it. This process is sometimes known as "rubber > ducking" -- http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html > > I can't count the number of times that I've had a problem, decided to > send it to a mailing list for help, and in the process of fully > describing the problem I'm having, come up with the solution without > even having to send the email. I second that. Just the other day, I was puzzling over how to do something in Python, involving the signal module. By the time I had written a *short* (less than twenty lines) example showing what I was trying to do, I had worked out how to do it and didn't need to send the email. This was not an unusual case. -- Steven From d at davea.name Fri Sep 21 17:37:23 2012 From: d at davea.name (Dave Angel) Date: Fri, 21 Sep 2012 11:37:23 -0400 Subject: [Tutor] np array.any() question In-Reply-To: <505C8702.7040606@pearwood.info> References: <505C8702.7040606@pearwood.info> Message-ID: <505C89B3.4030309@davea.name> On 09/21/2012 11:25 AM, Steven D'Aprano wrote: > On 22/09/12 01:07, Bala subramanian wrote: >> Friends, >> May i know why do get a Valuerror if i check any value in a is between >> 3.0 to 5.0 ? To summarize, with a numpy array called a, the OP is getting an error doing: (3 < a < 5).any() > This tries to calculate: > > (3 < a) and (a < 5) > > py> 3 < a > array([False, False, False, True, True, True], dtype=bool) > py> a < 5 > array([ True, True, True, True, True, False], dtype=bool) > > but combining them with the "and" operator is ambiguous: > > py> (3 < a) and (a < 5) > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element > is ambiguous. Use a.any() or a.all() > > Since the boolean "and" of the two arrays never gets calculated, > the any method never gets called. You could do: > > > py> (3 < a).any() and (a < 5).any() > True > > which I think does what you want. > I think not. The last expression you give will even return true if one of the values is > 3 and a DIFFERENT value is < 5. And i suspect the OP only wants a TRUE if at least one item in the array is between 3 and 5. I know nothing about numpy, but does it have a way to do an element-wise AND of two bool arrays of the same size? Maybe it's a function call and not 'and' Or maybe it's the & operator or something. I find the operator overloading i've seen in numpy to be very confusing, so I haven't tried to download it and try it out. Maybe if I read the docs directly, instead of just seeing examples and problems here, I'd think differently. -- DaveA From walksloud at gmail.com Fri Sep 21 18:07:59 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Fri, 21 Sep 2012 09:07:59 -0700 Subject: [Tutor] np array.any() question In-Reply-To: <505C89B3.4030309@davea.name> References: <505C8702.7040606@pearwood.info> <505C89B3.4030309@davea.name> Message-ID: > To summarize, > with a numpy array called a, the OP is getting an error doing: > > (3 < a < 5).any() > >> ... > > I think not. The last expression you give will even return true if one > of the values is > 3 and a DIFFERENT value is < 5. And i suspect the > OP only wants a TRUE if at least one item in the array is between 3 and 5. > > I know nothing about numpy, but does it have a way to do an element-wise > AND of two bool arrays of the same size? Maybe it's a function call and > not 'and' Or maybe it's the & operator or something. Yes, numpy does have a function like this: numpy.all() [ "and" function ] numpy.any() [ "or" function ] > I find the operator overloading i've seen in numpy to be very confusing, > so I haven't tried to download it and try it out. Maybe if I read the > docs directly, instead of just seeing examples and problems here, I'd > think differently. here you go :) http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html#numpy.all http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html#numpy.any you can ask if any satisfy the conditions and return true if 1+ are true: >>> a = numpy.array([ 7., 1., 1., 1., 2., 4., 0., 7., 6., 10.]) >>> numpy.any([ 3 < a, a < 5]) True >>> numpy.all([ 3 < a, a < 5]) False or you can ask for an array back telling you which are true and which false: >>> numpy.any([ 3 < a, a < 5], axis=0) array([ True, True, True, True, True, True, True, True, True, True], dtype=bool) >>> numpy.any([ 3 < a, a < 5], axis=0) array([False, False, False, False, False, True, False, False, False, False], dtype=bool) Note you are not limited to just comparing two arrays, but can compare as many as you like. To the OP: in this case, google (insert whatever search engine you like) is your friend. A good first bet is if there is some operation you like in python, other people like it also, and someone has taken the time to make a numpy version which acts element-wise on equal sized arrays. Andre From goknmuse at gmail.com Fri Sep 21 18:26:10 2012 From: goknmuse at gmail.com (Muse Gk) Date: Sat, 22 Sep 2012 00:26:10 +0800 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) Message-ID: Friends, I have the very similar problem like this guy except I want to install pycrypto ( https://www.dlitz.net/software/pycrypto/ ). http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid We had done enough researches on Google, still can not get a solution. Could some friends here give me or us a solution? Thanks in advance. BTW, English is not first language and I am not good at writing or speaking in English, however reading is not a problems. So hope no words make you confused. gk From eryksun at gmail.com Fri Sep 21 20:32:35 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Sep 2012 14:32:35 -0400 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: On Fri, Sep 21, 2012 at 12:26 PM, Muse Gk wrote: > > I have the very similar problem like this guy except I want to install > pycrypto ( https://www.dlitz.net/software/pycrypto/ ). > http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid Try MinGW-w64 running under Windows instead of Cygwin: website http://mingw-w64.sourceforge.net/ rubenvb toolchain http://sourceforge.net/projects/mingw-w64/files/ Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.7-release/ Shortened URL for the above: http://goo.gl/Igujs From apn06y at gmail.com Fri Sep 21 20:47:47 2012 From: apn06y at gmail.com (Pavel Andreev) Date: Fri, 21 Sep 2012 22:47:47 +0400 Subject: [Tutor] Generate array, different results Message-ID: Hello all A question from very beginner. I generate a simple example array and then print its elements on the screen. f=[[0]*3]*3 # array initialization for i in range(3): for j in range(3): f[i][j]=str(i)+str(j) # make simple example array print f[i][j], # print resulting elements print '\n' 00 01 02 10 11 12 20 21 22 So I generate element in loop and then print it and see all is ok. But after that if I print the whole generated array, I see different result with constant first number, as if "i" variable does not vary and equals to "2". What is wrong? >>> print f [['20', '21', '22'], ['20', '21', '22'], ['20', '21', '22']] I use python 2.7 From gnj091405 at gmail.com Fri Sep 21 21:10:01 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Fri, 21 Sep 2012 12:10:01 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: > > You need to add the folder where python.exe is to your PATH variable. I just realized the path we're heading down here isn't going to work. I need on .py file to be up an running so that I can add it to my tool in ArcGIS. > > Oscar I appreciate the help Oscar, and I believe it would work that way, but... I need on .py file to be up an running so that I can add it to my tool in ArcGIS. I would like to revise my question and add some more specifics. I must use Python 2.6! This is a task that I really want to automate, the situation is static and once I create this, I'll be golden (good). I must create one, stand alone script (in Idle, I hope) that will: 1. Unzip a single original zipfile (in_Zip) to the contents of the folder that the zipfile currently resides. 2. Go to the unique (NON ZIPPED) folders (actually student usernames 'aforker', 'allisw99', 'btaylor7', etc) that result from step 1. (there may be anywhere from 1 to 40 of these unique student folders) 3. Within each unique folder ('aforker', 'allisw99', 'btaylor7', etc) extract any and all (could be none, could be 3 or 4) .zip files within, to their relative aforementioned unique folders ('aforker', 'allisw99', 'btaylor7', etc), while 'navigating' i.e. not getting hung up on possible .pdf or docx files that may or may not reside in the unique folders ('aforker', 'allisw99', 'btaylor7', etc) This is what I've got so far: (and it 'works') (I'll modify later so that I do not need to hard-code the original zipfile (in_Zip)) --------------------------------------- import os, os.path, zipfile inZip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip' outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" z = zipfile.ZipFile(in_Zip,'a') z.extractall(outDir) zipContents = z.namelist() print zipContents z.close ---------------------------------------- It works, I get the following in the Python Shell: '>>> ================================ RESTART ================================' '>>>' ['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip', 'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip', 'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/', 'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/', 'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip', 'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/'] '>>> ' But, what I can't figure out is how to get 'into' each unique folder: aforker, allisw99, etc. and then extract any and all zips within 'aforker', 'allisw99', etc. I have no doubt that the suggestions posted here will work, but they all seem to get away from a single .py file and.... a) I can't get them to work, and b) it doesn't really help me because I need ONE stand alone .py file to make this all work in ArcGIS. I will be using this to create an ArcGIS 'tool' that requires one script (at least for me to comprehend it) :-) Thank you in advance for any and all suggestions, tips etc. For the record, I did try the following (to at least try something....) at the bottom of the code above: ----------------------- for item in zipContents: itemLoc = os.path.join(outDir,item) y = zipfile.ZipFile(itemLoc,'a') y.extractall(os.path.aplit(itemLoc)[0]) y.close ------------------------ but I get the following error: Traceback (most recent call last): File "D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts\unzip_a_zip.py", line 50, in y = zipfile.ZipFile(itemLoc,'a') File "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 687, in init self.fp = open(file, modeDict[mode]) IOError: [Errno 13] Permission denied: 'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\Lab_2/aforker/' I guess my first issue is to resolve the 'Permission denied' problem. And, I know I need an 'if' statement, somehow... thanks in advance for any and all input! Greg PS, neophyte/rookie, trying to keep it simple. This is not my normal daily task (good thing, right?) From eryksun at gmail.com Fri Sep 21 21:24:00 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Sep 2012 15:24:00 -0400 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On Fri, Sep 21, 2012 at 2:46 PM, Brett Dailey wrote: > > It just needs to be scaled to fit into each tile. You can just use one of your > choice as a place holder for now and I'll just put my own in later. I wrote up a version last night. Here's an image of the output: http://i.imgur.com/h4Wcd.png It scales the image (pygame.transform.smoothscale) by the largest of the two scale factors. Thus one dimension fits and the other is potentially oversized. This preserves the aspect ratio. It then crops an area the size of the cell out of the center by blit'ing to a new surface with the pygame.SRCALPHA flag set. mark_image = pygame.Surface(cell_size, flags=pygame.SRCALPHA) mark_image.blit(image, (0,0), areatl + areabr) This preserves transparency in the source image when you blit to a cell. I chose the randomly marked cells like this: num_marks = int(round(0.1 * num_cells)) marked_cells = set(random.sample(xrange(num_cells), num_marks)) To draw the grid, iterate over the rows and columns with a nested for loop. Pick the background color out of a list of 2 colors. The index is simply (row + col) % 2. As col increments in the inner loop, the value toggles between 0 and 1. Then when it gets to the next row (i.e. row += 1), the pattern shifts by 1. If the current cell number is in marked_cells, blit the image also. My implementation uses a Board class with the following methods: __init__, update, update_image, set_marks, and draw. It also has two class attributes: bgcolor and cell_colors. The image I chose is a standard Gnome emoticon. Here's the icon's path in my Debian installation: /usr/share/icons/gnome/256x256/emotes/face-cool.png From eryksun at gmail.com Fri Sep 21 21:44:49 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Sep 2012 15:44:49 -0400 Subject: [Tutor] Generate array, different results In-Reply-To: References: Message-ID: On Fri, Sep 21, 2012 at 2:47 PM, Pavel Andreev wrote: > > f=[[0]*3]*3 # array initialization The above isn't giving you what you want. All 3 sublists are the same object: >>> f = [[0]*3]*3 >>> map(id, f) [149391980, 149391980, 149391980] Do this instead: >>> f = [[0]*3 for i in range(3)] Each iteration in the comprehension creates a new list: >>> map(id, f) [149392364, 149392012, 149392428] From ramit.prasad at jpmorgan.com Fri Sep 21 21:55:50 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Sep 2012 19:55:50 +0000 Subject: [Tutor] Generate array, different results In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166BF095@SCACMX008.exchad.jpmchase.net> Pavel Andreev wrote: > Hello all > A question from very beginner. > I generate a simple example array and then print its elements on the screen. > > f=[[0]*3]*3 # array initialization Your problem is above. Let us rewrite the above line as a = [0]*3 f = [a]*3 Variable `a` is a new list with 3 copies of the contents in the list which is 0 (i.e. there are 3 zeros in the new list). There is no problem here because 0 is an immutable (cannot be changed) object. Now in the second line, the variable `f` is a new list with 3 copies of `a`. This basically boils down to the equivalent of: f = [ a for _ in xrange(3) ] # OR f = [ a, a, a ] You can see they are the same object by using is. >>> f[0] is f[1] True `f[0]` and `f[1]` are both bound to the same list object. Since lists are mutable objects, when you change `f[0]` you are actually changing the object underlying `f[1]`. You can fix your problem by the following instead. f = [ [0]*3 for _ in xrange(3) ] > for i in range(3): > for j in range(3): > f[i][j]=str(i)+str(j) # make simple example array > print f[i][j], # print resulting elements > print '\n' > > > 00 01 02 > > 10 11 12 > > 20 21 22 > > > So I generate element in loop and then print it and see all is ok. The reason your loop works initially is that you are setting the value you want immediately before you print it. With each iteration of `i` you are discarding the previous value. You can debug what is happening if you print `f` at each step in the loop instead of `f[i][j]`. It will probably make a lot more sense than my explanation. > But after that if I print the whole generated array, I see different > result with constant first number, as if "i" variable does not vary > and equals to "2". What is wrong? > > >>> print f > > [['20', '21', '22'], ['20', '21', '22'], ['20', '21', '22']] > > I use python 2.7 Feel free to ask for clarification if that explanation did not make sense. This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emile at fenx.com Fri Sep 21 22:24:52 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 21 Sep 2012 13:24:52 -0700 Subject: [Tutor] How can I convert a variable name to a string? In-Reply-To: <201209211711061661484@126.com> References: <201209211711061661484@126.com> Message-ID: On 9/21/2012 2:11 AM Dae James said... > How can I convert a variable name to a string ? > For example: > testVariable = 1000; > How can I get the string "testVariable" ? If what you're asking is 'how do I get the value associated with the the string "testVariable"?' then yuo can use something like: locals()["testVariable"] Emile From ginarf at comcast.net Sat Sep 22 01:34:55 2012 From: ginarf at comcast.net (Gina) Date: Fri, 21 Sep 2012 18:34:55 -0500 Subject: [Tutor] I don't know why this program doesn't run Message-ID: <505CF99F.7010306@comcast.net> I don't know why this program doesn't run, but if you know, please tell me. -thanks -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Car Salesperson.py URL: From stephen at averagesecurityguy.info Sat Sep 22 01:40:29 2012 From: stephen at averagesecurityguy.info (Stephen Haywood) Date: Fri, 21 Sep 2012 19:40:29 -0400 Subject: [Tutor] How can I convert a variable name to a string? In-Reply-To: <201209211711061661484@126.com> References: <201209211711061661484@126.com> Message-ID: <-1342608562947852008@unknownmsgid> On Sep 21, 2012, at 6:14 AM, Dae James wrote: How can I convert a variable name to a string ? For example: testVariable = 1000; How can I get the string "testVariable" ? Thank you~ Use a dictionary. vars['testVariable'] = 1000 for key in vars: print key print vars[key] ------------------------------ Dae James _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen at averagesecurityguy.info Sat Sep 22 01:44:16 2012 From: stephen at averagesecurityguy.info (Stephen Haywood) Date: Fri, 21 Sep 2012 19:44:16 -0400 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <505CF99F.7010306@comcast.net> References: <505CF99F.7010306@comcast.net> Message-ID: <-8404957734333529117@unknownmsgid> What doesn't work? What error message do you get? What have you done to fix the errors? What version of Python are you using? Stephen Haywood Information Security Consultant W: www.averagesecurityguy.info T: @averagesecguy On Sep 21, 2012, at 7:35 PM, Gina wrote: > I don't know why this program doesn't run, but if you know, please tell me. > -thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Sat Sep 22 01:47:10 2012 From: d at davea.name (Dave Angel) Date: Fri, 21 Sep 2012 19:47:10 -0400 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <505CF99F.7010306@comcast.net> References: <505CF99F.7010306@comcast.net> Message-ID: <505CFC7E.6020403@davea.name> On 09/21/2012 07:34 PM, Gina wrote: > I don't know why this program doesn't run, but if you know, please > tell me. > -thanks > So what happens when you try? "Doesn't run" covers a multitude of possibilities. First one: python Car Salesperson.py python: can't open file 'Car': [Errno 2] No such file or directory davea at think:~/temppython$ The fix for this one is to put quotes around the script name. Or to escape the blanks. Or even better to rename the file so it doesn't have spaces in it. Please be specific. You're running some OS, you launch some particular version of Python, you give it some commandline, and you get some unexpected result. Use a lot of copy/paste and it's not too painful. -- DaveA From breamoreboy at yahoo.co.uk Sat Sep 22 01:53:08 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Sep 2012 00:53:08 +0100 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <505CF99F.7010306@comcast.net> References: <505CF99F.7010306@comcast.net> Message-ID: On 22/09/2012 00:34, Gina wrote: > I don't know why this program doesn't run, but if you know, please tell me. > -thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > It helps us to help you if you give your OS, the complete error message that you get and your version of Python as well as the code. "This program doesn't run" isn't much to go on. Also putting a small piece of code inline rather than as an attachment is perfectly acceptable which I'll do now. #adds extra fees to the base price of a car. print( """ Car Salesman Totals the base price of a car with all other fees. Please enter the requested information, and don't include change. """ ) name = input("What kind of car is it?") base_price = input("What is the base price?") tax = base_price / 25 print("Tax: $", tax) license_fee = base_price // 50 print("The license fee: $", license_fee) maintenance = 45 print("The maintenance fee: $", maintenance) insurance = 100 print("The insurance: $", insurance) total = base_price + tax + license_fee + maintenance + insurance print("After tax, the license fee, the maintenance fee, and the " "insurance fee, the ", name, "costs $", total, ".") input("\n\nPress enter to exit.") I'll hazard a guess that you're running Python 2.x and you get What kind of car is it?Royce Traceback (most recent call last): File "C:\Users\Mark\Car Salesperson.py", line 14, in name = input("What kind of car is it?") File "", line 1, in NameError: name 'Royce' is not defined In which case change the input to raw_input and carry on to the next error :) -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Sat Sep 22 01:55:52 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Sep 2012 00:55:52 +0100 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <-8404957734333529117@unknownmsgid> References: <505CF99F.7010306@comcast.net> <-8404957734333529117@unknownmsgid> Message-ID: On 22/09/2012 00:44, Stephen Haywood wrote: > What doesn't work? What error message do you get? What have you done > to fix the errors? What version of Python are you using? > > Stephen Haywood > Information Security Consultant > W: www.averagesecurityguy.info > T: @averagesecguy > > On Sep 21, 2012, at 7:35 PM, Gina wrote: > >> I don't know why this program doesn't run, but if you know, please tell me. >> -thanks >> >> _______________________________________________ > Please don't top post on this list, thanks. -- Cheers. Mark Lawrence. From d at davea.name Sat Sep 22 02:17:59 2012 From: d at davea.name (Dave Angel) Date: Fri, 21 Sep 2012 20:17:59 -0400 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <505D01BC.2040802@comcast.net> References: <505CF99F.7010306@comcast.net> <505CFC7E.6020403@davea.name> <505D01BC.2040802@comcast.net> Message-ID: <505D03B7.1010604@davea.name> Hi, you forgot to do a reply-all, so it didn't go to the list. I'm correcting that now, so don't worry about it. if your email doesn't support reply-all, then just add a cc of tutor at python.org On 09/21/2012 08:09 PM, Gina wrote: > On 9/21/2012 6:47 PM, Dave Angel wrote: >> On 09/21/2012 07:34 PM, Gina wrote: >>> I don't know why this program doesn't run, but if you know, please >>> tell me. >>> -thanks >>> >> So what happens when you try? "Doesn't run" covers a multitude of >> possibilities. >> >> First one: >> >> python Car Salesperson.py >> python: can't open file 'Car': [Errno 2] No such file or directory >> davea at think:~/temppython$ >> >> The fix for this one is to put quotes around the script name. Or to >> escape the blanks. Or even better to rename the file so it doesn't have >> spaces in it. >> >> >> Please be specific. You're running some OS, you launch some particular >> version of Python, you give it some commandline, and you get some >> unexpected result. Use a lot of copy/paste and it's not too painful. >> > I have version 3 of python. > > it will let me type in the type of car and then enter > then i type in the base price and when i hit enter, it says error > The problem is in your input statement: base_price = input("What is the base price?") input (on Python version 3.x) always returns a string. Sometimes that's what you want, sometimes it's not. In this case, just change to: base_price = int(input("What is the base price?")) > This is the error message: > tax = base_price / 25 > TypeError: unsupported operand type(s) for /: 'str' and 'int' > > I tried adding int() in front of base_price but it still didn't work Again, please be specific. If you really tried this: tax = int() base_price /25 then it naturally won't work. But if you tried tax = int(base_price) / 25 it should have worked. What error did you get? Did it give the wrong answer, or another exception traceback? Anyway, I showed you my preference. Convert data to their final type as soon as possible after getting it from the user. Not later when you're trying to use it. -- DaveA From ginarf at comcast.net Sat Sep 22 02:31:22 2012 From: ginarf at comcast.net (Gina) Date: Fri, 21 Sep 2012 19:31:22 -0500 Subject: [Tutor] I don't know why this program doesn't run In-Reply-To: <505D03B7.1010604@davea.name> References: <505CF99F.7010306@comcast.net> <505CFC7E.6020403@davea.name> <505D01BC.2040802@comcast.net> <505D03B7.1010604@davea.name> Message-ID: <505D06DA.4040908@comcast.net> Thank you so much! That worked! On 9/21/2012 7:17 PM, Dave Angel wrote: > Hi, you forgot to do a reply-all, so it didn't go to the list. I'm > correcting that now, so don't worry about it. if your email doesn't > support reply-all, then just add a cc of tutor at python.org > > > On 09/21/2012 08:09 PM, Gina wrote: >> On 9/21/2012 6:47 PM, Dave Angel wrote: >>> On 09/21/2012 07:34 PM, Gina wrote: >>>> I don't know why this program doesn't run, but if you know, please >>>> tell me. >>>> -thanks >>>> >>> So what happens when you try? "Doesn't run" covers a multitude of >>> possibilities. >>> >>> First one: >>> >>> python Car Salesperson.py >>> python: can't open file 'Car': [Errno 2] No such file or directory >>> davea at think:~/temppython$ >>> >>> The fix for this one is to put quotes around the script name. Or to >>> escape the blanks. Or even better to rename the file so it doesn't have >>> spaces in it. >>> >>> >>> Please be specific. You're running some OS, you launch some particular >>> version of Python, you give it some commandline, and you get some >>> unexpected result. Use a lot of copy/paste and it's not too painful. >>> >> I have version 3 of python. >> >> it will let me type in the type of car and then enter >> then i type in the base price and when i hit enter, it says error >> > The problem is in your input statement: base_price = input("What is the > base price?") > > input (on Python version 3.x) always returns a string. Sometimes that's > what you want, sometimes it's not. In this case, just change to: > > base_price = int(input("What is the base price?")) > > >> This is the error message: >> tax = base_price / 25 >> TypeError: unsupported operand type(s) for /: 'str' and 'int' >> >> I tried adding int() in front of base_price but it still didn't work > Again, please be specific. If you really tried this: > > tax = int() base_price /25 > > then it naturally won't work. But if you tried > tax = int(base_price) / 25 > > it should have worked. What error did you get? Did it give the wrong > answer, or another exception traceback? > > Anyway, I showed you my preference. Convert data to their final type as > soon as possible after getting it from the user. Not later when you're > trying to use it. > > > From goknmuse at gmail.com Sat Sep 22 06:25:42 2012 From: goknmuse at gmail.com (Muse Gk) Date: Sat, 22 Sep 2012 12:25:42 +0800 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: eryksun (), thanks for your help. I had tried MinGW-w64 today, however, another more errors happen which just like this ( http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o ). Another no solution error. First, I tried to remove all instances of -mno-cygwin in distutils\cygwinccompiler.py and got another different error. Second, keep -mno-cygwin in distutils\cygwinccompiler.py, tried a little version of MinGW-w64 ( http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.5-release/ ). This time finally kill the error "gcc: error: unrecognized command line option '-mno-cygwin' ", however, got another one "collect2: ld returned 1 exit status" instead. It seems there is no way I can kill all errors. It took me hours and hours to kill those errors, however, there is still another one. I am feeling very depressed. I do not want to install pycrypto any more. :( I hope there will be an easy way to install it in the short future. gk On Sat, Sep 22, 2012 at 2:32 AM, eryksun wrote: > On Fri, Sep 21, 2012 at 12:26 PM, Muse Gk wrote: >> >> I have the very similar problem like this guy except I want to install >> pycrypto ( https://www.dlitz.net/software/pycrypto/ ). >> http://stackoverflow.com/questions/12005109/python-cannot-build-pycpuid > > Try MinGW-w64 running under Windows instead of Cygwin: > > website > http://mingw-w64.sourceforge.net/ > > rubenvb toolchain > http://sourceforge.net/projects/mingw-w64/files/ > Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.7-release/ > > Shortened URL for the above: > http://goo.gl/Igujs From dwightdhutto at gmail.com Sat Sep 22 11:13:41 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 22 Sep 2012 05:13:41 -0400 Subject: [Tutor] Help In-Reply-To: <505C88D7.4050906@pearwood.info> References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> <505C88D7.4050906@pearwood.info> Message-ID: >> It's tricky. >> >> Ideally, you need to take your large code base, and reduce it into a >> short piece of sample code that is runnable and reproduces your issue. > > > +10000 on this. > > There is no good answer. Speaking for myself, I would prefer that you > attach the file to your email. But others will be unhappy if you do > that, and will prefer that you use a pastebin. But if you use a pastebin,r There are other options like Facebook nowadays(just guessing, but I don't use it that much, but seems appropriate). I'd say youtube, but you couldn't copy and paste from the video, just look at the errors outputed, and a good long video of the code. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From eryksun at gmail.com Sat Sep 22 11:36:08 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Sep 2012 05:36:08 -0400 Subject: [Tutor] Help In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> <505C88D7.4050906@pearwood.info> Message-ID: On Sat, Sep 22, 2012 at 5:13 AM, Dwight Hutto wrote: > > I'd say youtube, but you couldn't copy and paste from the video, just > look at the errors outputed, and a good long video of the code. OK, but please don't make a video and basically grunt like Animal from the Muppet Show: see code! see code no work! see error! fix, fix, fix! http://www.youtube.com/watch?v=2cEPydnb0Ns From chigga101 at gmail.com Sat Sep 22 12:56:12 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 11:56:12 +0100 Subject: [Tutor] Relative import help Message-ID: i have an assignment from a book to practice implementing relative imports. it gave a very clear and easy to follow explanation, but my results are proving the instructions are wrong. here's what i have tried. my folder structure: Project / __init__.py main.py Domestic / __init__.py players.py premier_leauge.py silverware.py Europe / __init__.py champions_league.py europa.py winners.py Internationals / __init__.py nations.py its easy to use the normal import method to import something further down the directory, but when trying to go up, nothing works. heres something weird. winner.py in the Europe directory, i used this code to try and import a class named Silverware in silverware.py 1 directory up: from ..silverware import Silverware heres my error mesages: ... ValueError: Attempted relative import in non-package i can accept this and say i did something wrong, but.... i left the import statement even with the error. now my main.py in the 1st directory called Project. i imported winner.py. the file that got this error message. And by importing this file, i have access to silverware.py. i can access everything in this file through that old import statement: from ..silverware import Silverware so why is it this statement wont allow me to import silverware.py to winner.py directly, but still gives access to winner.py if winner.py is imported from a directory on the same level or further up from silverware.py? this is the exact code instructions my book gave me, why isn't it working for files futher down? From steve at pearwood.info Sat Sep 22 14:15:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Sep 2012 22:15:22 +1000 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: <505DABDA.7060903@pearwood.info> On 22/09/12 20:56, Matthew Ngaha wrote: > i have an assignment from a book to practice implementing relative > imports. it gave a very clear and easy to follow explanation, but my > results are proving the instructions are wrong. Not impossible, but I doubt that. Have you followed the instructions *exactly*? If not, you have probably missed something. What book is it? Otherwise, the book and you are probably using different versions of Python. What version of Python are you using, and what is the book using? -- Steven From __peter__ at web.de Sat Sep 22 14:25:16 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Sep 2012 14:25:16 +0200 Subject: [Tutor] Relative import help References: Message-ID: Matthew Ngaha wrote: > i have an assignment from a book to practice implementing relative > imports. it gave a very clear and easy to follow explanation, but my > results are proving the instructions are wrong. here's what i have > tried. my folder structure: > > Project / > > __init__.py > main.py > Domestic / > > __init__.py > players.py > premier_leauge.py > silverware.py > Europe / > > __init__.py > champions_league.py > europa.py > winners.py > Internationals / > > __init__.py > nations.py > > its easy to use the normal import method to import something further > down the directory, but when trying to go up, nothing works. heres > something weird. winner.py in the Europe directory, i used this code > to try and import a class named Silverware in silverware.py 1 > directory up: > > from ..silverware import Silverware > heres my error mesages: ... ValueError: Attempted relative import in > non-package > > i can accept this and say i did something wrong, but.... i left the > import statement even with the error. now my main.py in the 1st > directory called Project. i imported winner.py. the file that got this > error message. And by importing this file, i have access to > silverware.py. i can access everything in this file through that old > import statement: > > from ..silverware import Silverware > so why is it this statement wont allow me to import silverware.py to > winner.py directly, but still gives access to winner.py if winner.py > is imported from a directory on the same level or further up from > silverware.py? this is the exact code instructions my book gave me, > why isn't it working for files futher down? You probably have a path that reaches into Domestic or Europe sub-package. That can happen if e. g. Project/Domestic/Europe is your current working directory. Try to cd into the Project folder's parent directory and see if $ python -c 'import Project.Domestic.Europe.winners' works. From chigga101 at gmail.com Sat Sep 22 14:29:01 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 13:29:01 +0100 Subject: [Tutor] Relative import help In-Reply-To: <505DABDA.7060903@pearwood.info> References: <505DABDA.7060903@pearwood.info> Message-ID: > Not impossible, but I doubt that. > > Have you followed the instructions *exactly*? If not, you have > probably missed something. What book is it? > > Otherwise, the book and you are probably using different versions of > Python. What version of Python are you using, and what is the book > using? the book always indicates its using Python 3, but never actually states which version of Python 3. The name of the book itself is called Python 3 Object Oriented Programming. I'm i am using Python 3.1. i followed the instructions as the book instructed, creating the same folder structure etc. It came out in 2010, im not really sure which was the current Python version at that time. From chigga101 at gmail.com Sat Sep 22 14:33:30 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 13:33:30 +0100 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: > You probably have a path that reaches into Domestic or Europe sub-package. > That can happen if e. g. Project/Domestic/Europe is your current working > directory. > > Try to cd into the Project folder's parent directory and see if > > $ python -c 'import Project.Domestic.Europe.winners' > > works. hey i am very new to programming:) what do you mean by Try to cd? how and where should i do that to type the code you provided? From d at davea.name Sat Sep 22 14:44:15 2012 From: d at davea.name (Dave Angel) Date: Sat, 22 Sep 2012 08:44:15 -0400 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: <505DB29F.8090900@davea.name> On 09/22/2012 08:33 AM, Matthew Ngaha wrote: >> You probably have a path that reaches into Domestic or Europe sub-package. >> That can happen if e. g. Project/Domestic/Europe is your current working >> directory. >> >> Try to cd into the Project folder's parent directory and see if >> >> $ python -c 'import Project.Domestic.Europe.winners' >> >> works. > hey i am very new to programming:) what do you mean by Try to cd? how > and where should i do that to type the code you provided? > cd is a shell command; you do it before starting Python. You didn't mention what OS you're running, but cd should be about the same for Linux, Windows, or Mac. davea at think:~/pythonProject$ cd .. davea at think:~$ -- DaveA From eryksun at gmail.com Sat Sep 22 14:51:15 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Sep 2012 08:51:15 -0400 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: On Sat, Sep 22, 2012 at 12:25 AM, Muse Gk wrote: > > I had tried MinGW-w64 today, however, another more errors happen which > just like this ( > http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o > ). Another no solution error. > > First, I tried to remove all instances of -mno-cygwin in > distutils\cygwinccompiler.py and got another different error. > > Second, keep -mno-cygwin in distutils\cygwinccompiler.py, tried a > little version of MinGW-w64 ( > http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.5-release/ > ). This time finally kill the error "gcc: error: unrecognized command > line option '-mno-cygwin' ", however, got another one "collect2: ld > returned 1 exit status" instead. Which library caused the linker to fail? Before running setup.py, add the following environment variable with the "set" command: set LIBRARY_PATH=c:\pythonXX\libs where XX is your version of Python (e.g. XX is 27 for Python 2.7). Also, according to http://bugs.python.org/issue4709, you might need MS_WIN64 to be manually defined. Try installing like this: python setup.py build_ext -DMS_WIN64 install Alternatively, here's a Stack Overflow answer that links to step-by-step instructions for using the compiler from the Windows 7 SDK: http://stackoverflow.com/a/11408432/205580 > It seems there is no way I can kill all errors. It took me hours and > hours to kill those errors, however, there is still another one. I am > feeling very depressed. I do not want to install pycrypto any more. :( > > I hope there will be an easy way to install it in the short future. I doubt there will ever be an easy way considering export restrictions on cryptography software. Plus you might feel just a bit more secure building your own copy. From chigga101 at gmail.com Sat Sep 22 16:07:34 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 15:07:34 +0100 Subject: [Tutor] Relative import help In-Reply-To: <4213e58d68fb3d9f5306d33ce3ee5097.squirrel@webmail.sonic.net> References: <4213e58d68fb3d9f5306d33ce3ee5097.squirrel@webmail.sonic.net> Message-ID: > try > import ../my_module > instead of > import ..my_module > and see what happens. > Your problem may be just that you haven't included the separator. > > .. means one directory higher but you must separate it from the file name. > > Two directories higher would be > ../../my_module sadly this was invalid syntax:( From chigga101 at gmail.com Sat Sep 22 16:10:13 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 15:10:13 +0100 Subject: [Tutor] Relative import help In-Reply-To: <505DB29F.8090900@davea.name> References: <505DB29F.8090900@davea.name> Message-ID: > cd is a shell command; you do it before starting Python. You didn't > mention what OS you're running, but cd should be about the same for > Linux, Windows, or Mac. im on windows. i always start Python via IDLE. ive never started it for editing though the shell, run > cmd etc? ill type that into the cmd but im not sure ill know how to work with Python after as ive never used it through shell:( From fomcl at yahoo.com Sat Sep 22 17:11:54 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 22 Sep 2012 08:11:54 -0700 (PDT) Subject: [Tutor] application whitelisting In-Reply-To: <505C7C9B.2030507@pearwood.info> References: <1348224678.99583.YahooMailNeo@web110707.mail.gq1.yahoo.com> <505C7C9B.2030507@pearwood.info> Message-ID: <1348326714.12667.YahooMailNeo@web110715.mail.gq1.yahoo.com> ? >On 21/09/12 20:51, Albert-Jan Roskam wrote: >> Hi, >> >> My company just started application whitelisting. Now a new version of >>a (benign!!) dll does not work as it (or rather, its file hash, if I >>understood it correctly) is not whitelisted. > >Then get it whitelisted. If your company doesn't have the ability to >update the whitelist when your software updates, it's even more stupid >than it seems. You are right, I should treat it like any other update. What I hate is the amount of paperwork and time involved. >It's worse than that. If the application whitelist is using md5 (and wanna >bet that at least 50% of the commercial whitelist software out there is?), >then it is already broken. An attacker can easily take an arbitrary >application, and generate a new application with the same MD5 sum and the >same length, differing by 128 bytes. > >http://www.mscs.dal.ca/~selinger/md5collision/ > Very interesting indeed! I noticed that the link to the original article was broken. This one works: http://www.infosec.sdu.edu.cn/uploadfile/papers/How%20to%20Break%20MD5%20and%20Other%20Hash%20Functions.pdf "In this paper we described a powerful attack against hash functions, and in particular showed that finding a collision of MD5 is easily feasible. Our attack is also able to break efficiently other hash functions, such as HAVAL-128, MD4, RIPEMD, and SHA-0." From chigga101 at gmail.com Sat Sep 22 17:13:34 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 16:13:34 +0100 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: > You probably have a path that reaches into Domestic or Europe sub-package. > That can happen if e. g. Project/Domestic/Europe is your current working > directory. > > Try to cd into the Project folder's parent directory and see if > > $ python -c 'import Project.Domestic.Europe.winners' > > works. ive got into the parent directory and typed this code both in cmd, and my python file. niether seems to work. on idle i get invalid syntax error. im on windows From goknmuse at gmail.com Sat Sep 22 17:25:11 2012 From: goknmuse at gmail.com (Muse Gk) Date: Sat, 22 Sep 2012 23:25:11 +0800 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: eryksun (), I really appreciate what you had done for me. I still can not make through those errors. Or I can say there is no way install pycrypto with MinGW or Cygwin. >Also, according to http://bugs.python.org/issue4709, you might need >MS_WIN64 to be manually defined. Try installing like this: > python setup.py build_ext -DMS_WIN64 install >Alternatively, here's a Stack Overflow answer that links to >step-by-step instructions for using the compiler from the Windows 7 >SDK: > http://stackoverflow.com/a/11408432/205580 It seems I have to install Visual Studio 2010, http://mpir.org/ , http://gmplib.org/ and maybe more. I do not know the reason why I really do not want to install Visual Studio on my machine. Sorry. Maybe I should create a virtual machine with VirtualBox which OS is Ubuntu or Fedora. This will be easy for me. When I search possible solutions, I do find a much easy way ( http://www.voidspace.org.uk/python/modules.shtml#pycrypto ) Also do not know why I do not just pick it up. Maybe I thought there were supposed to have a way to solve all those errors or bugs, however, by trial and error, I realize I can not make it. This is the full logs when build: C:\Users\gk\Downloads\pycrypto-2.6>python setup.py build --compiler=mingw32 running build running build_py running build_ext running build_configure checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.exe checking for suffix of executables... .exe checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for __gmpz_init in -lgmp... no checking for __gmpz_init in -lmpir... no checking whether mpz_powm is declared... no checking whether mpz_powm_sec is declared... no checking how to run the C preprocessor... gcc -E checking for grep that handles long lines and -e... /usr/bin/grep checking for egrep... /usr/bin/grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking for inttypes.h... (cached) yes checking limits.h usability... yes checking limits.h presence... yes checking for limits.h... yes checking stddef.h usability... yes checking stddef.h presence... yes checking for stddef.h... yes checking for stdint.h... (cached) yes checking for stdlib.h... (cached) yes checking for string.h... (cached) yes checking wchar.h usability... yes checking wchar.h presence... yes checking for wchar.h... yes checking for inline... inline checking for int16_t... yes checking for int32_t... yes checking for int64_t... yes checking for int8_t... yes checking for size_t... yes checking for uint16_t... yes checking for uint32_t... yes checking for uint64_t... yes checking for uint8_t... yes checking for stdlib.h... (cached) yes checking for GNU libc compatible malloc... yes checking for memmove... yes checking for memset... yes configure: creating ./config.status config.status: creating src/config.h warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom' extension creating build\temp.win32-2.7 creating build\temp.win32-2.7\Release creating build\temp.win32-2.7\Release\src C:\Users\gk\Downloads\mingw64\bin\gcc.exe -mno-cygwin -mdll -Wall -std=c99 -O3 - fomit-frame-pointer -Isrc/ -IC:\Python27\include -IC:\Python27\PC -c src/winrand .c -o build\temp.win32-2.7\Release\src\winrand.o src/winrand.c:38:0: warning: "_WIN32_WINNT" redefined c:\users\gk\downloads\mingw64\bin\../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/include/_mingw.h:244:0: note: this is the location of the p revious definition writing build\temp.win32-2.7\Release\src\winrandom.def C:\Users\gk\Downloads\mingw64\bin\gcc.exe -mno-cygwin -shared -s build\temp.win3 2-2.7\Release\src\winrand.o build\temp.win32-2.7\Release\src\winrandom.def -LC:\ Python27\libs -LC:\Python27\PCbuild -lws2_32 -ladvapi32 -lpython27 -lmsvcr90 -o build\lib.win32-2.7\Crypto\Random\OSRNG\winrandom.pyd c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/libpytho n27.a when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/python27 .lib when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs\libpytho n27.a when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/libpytho n27.a when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/python27 .lib when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs\python27 .lib when searching for -lpython27 c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: cannot find -lpython27 collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 I hope you [eryksun()] do not think I am wasting your time. I really better to give up on installing pycrypto on windows 64bit. BTW, I am just an application chemistry major student who has much interests in computer things on spare time. I better know more about Python and Crypto things and then think about how to use pycrypto. Thanks again, eryksun(). NO more take time on my question. You have done enough for me. gk On Sat, Sep 22, 2012 at 8:51 PM, eryksun wrote: > On Sat, Sep 22, 2012 at 12:25 AM, Muse Gk wrote: >> >> I had tried MinGW-w64 today, however, another more errors happen which >> just like this ( >> http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o >> ). Another no solution error. >> >> First, I tried to remove all instances of -mno-cygwin in >> distutils\cygwinccompiler.py and got another different error. >> >> Second, keep -mno-cygwin in distutils\cygwinccompiler.py, tried a >> little version of MinGW-w64 ( >> http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.5-release/ >> ). This time finally kill the error "gcc: error: unrecognized command >> line option '-mno-cygwin' ", however, got another one "collect2: ld >> returned 1 exit status" instead. > > > Which library caused the linker to fail? > > Before running setup.py, add the following environment variable with > the "set" command: > > set LIBRARY_PATH=c:\pythonXX\libs > > where XX is your version of Python (e.g. XX is 27 for Python 2.7). > > Also, according to http://bugs.python.org/issue4709, you might need > MS_WIN64 to be manually defined. Try installing like this: > > python setup.py build_ext -DMS_WIN64 install > > Alternatively, here's a Stack Overflow answer that links to > step-by-step instructions for using the compiler from the Windows 7 > SDK: > > http://stackoverflow.com/a/11408432/205580 > > >> It seems there is no way I can kill all errors. It took me hours and >> hours to kill those errors, however, there is still another one. I am >> feeling very depressed. I do not want to install pycrypto any more. :( >> >> I hope there will be an easy way to install it in the short future. > > I doubt there will ever be an easy way considering export restrictions > on cryptography software. Plus you might feel just a bit more secure > building your own copy. From __peter__ at web.de Sat Sep 22 18:42:26 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Sep 2012 18:42:26 +0200 Subject: [Tutor] Relative import help References: Message-ID: Matthew Ngaha wrote: >> You probably have a path that reaches into Domestic or Europe >> sub-package. That can happen if e. g. Project/Domestic/Europe is your >> current working directory. >> >> Try to cd into the Project folder's parent directory and see if >> >> $ python -c 'import Project.Domestic.Europe.winners' >> >> works. > > ive got into the parent directory and typed this code both in cmd, and > my python file. niether seems to work. on idle i get invalid syntax > error. im on windows You had forward slashes in your description of the folder layout, so I assumed you were on a linux box or a mac. I think I have now learned the lesson and will make fewer assumptions in the future. First, in idle's "shell" window type >>> import sys >>> print(sys.executable) (dont' type the ">>>", that will appear automatically) This should print something like C:\python32\python3.exe Now use Windows Explorer to navigate to the parent folder of "Project" and follow the instructions on http://www.windows7hacker.com/index.php/2009/08/how-to-open-dos-prompt- command-here-in-windows-7-and-more/ (hold the shift key and right-click, then choose [Open Command Window Here]) You should now see an ugly little black box. Type in C:\python32\python3 -c 'import Project.Domestic.Europe.winners' but remember to replace C:\python32\python3 with the actual contents of sys.executable. Whew ;) From chigga101 at gmail.com Sat Sep 22 19:38:26 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 22 Sep 2012 18:38:26 +0100 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: > You had forward slashes in your description of the folder layout, so I > assumed you were on a linux box or a mac. I think I have now learned the > lesson and will make fewer assumptions in the future. > > First, in idle's "shell" window type > >>>> import sys >>>> print(sys.executable) > > (dont' type the ">>>", that will appear automatically) This should print > something like > > C:\python32\python3.exe > > Now use Windows Explorer to navigate to the parent folder of "Project" and > follow the instructions on > > http://www.windows7hacker.com/index.php/2009/08/how-to-open-dos-prompt- > command-here-in-windows-7-and-more/ > > (hold the shift key and right-click, then choose [Open Command Window Here]) > > You should now see an ugly little black box. Type in > > C:\python32\python3 -c 'import Project.Domestic.Europe.winners' > > but remember to replace C:\python32\python3 with the actual contents of > sys.executable. > > Whew ;) :p.. whew!! well i followed your instructions and everything went well with inputting the sys.executable into my Project's cmd shell. Sadly my winners.py still can't directly access silverware.py in the directory further up. Not to worry though, i spent all of yesterday and most of today trying to get it to work, im mentally tired with this import stuff, i just want to work through the rest of the book now:) Thats whats important. maybe i'll revisit relative importing when i actually need to use it. I'm still a far way away from those types of projects as im still reading beginner tutorials, and the normal absolute imports seem to be doing just fine. Thanks for all your help and efforts:) From eryksun at gmail.com Sun Sep 23 00:38:49 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Sep 2012 18:38:49 -0400 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: On Sat, Sep 22, 2012 at 11:25 AM, Muse Gk wrote: > > c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. > ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/libpytho > n27.a when searching for -lpython27 FYI, -lpython27 is for linking to the python27 library. gcc links each extension module against the import library "libpython27.a" so at runtime the module can access the exported functions and data of the shared library "python27.dll". I just checked the contents of the 64-bit installer, python-2.7.3.amd64.msi, and it doesn't include libpython27.a, the import lib needed by gcc. 64-bit ActivePython might have it, but otherwise I suspect you have a 32-bit Python installation. Are you sure you have 64-bit Python installed? The official 64-bit installer only comes with python27.lib, the import library used by MSVC. Apparently differences in the C++ runtime between MSVC and gcc make using gcc on Windows officially unsupportable. (Yet they continue to include libpython27.a in the 32-bit version, which I'd imagine is equally unsupportable.) PyCrypto is only C, so this probably isn't an issue. I'm not 100% certain, however. All I can say is that in the past when I used Windows I had no problems with C extensions built with MinGW for 32-bit Python. I mostly stick to Debian Linux these days, so I'm not up to date on the pitfalls of 64-bit Windows. Assuming you've installed the official 64-bit Python, you can try creating your own libpython27.a import lib using gendef and dlltool (these should be in your MinGW-w64 installation). Start by copying C:\Windows\System32\python27.dll to a temp directory. Then run the following: gendef python27.dll This creates "python27.def", which lists the DLL's exports. Open this file and search for "Py_InitModule4". Make sure the name has _64 appended to it, i.e. "Py_InitModule4_64". If not, add it. Then run the following: dlltool --dllname python27.dll --input-def python27.def --output-lib libpython27.a Copy "libpython27.a" to C:\Python27\libs. As before make sure the library path is set: set LIBRARY_PATH=C:\Python27\libs For good measure, manually define the macro MS_WIN64 in the build/install command: python setup.py build_ext -DMS_WIN64 install If this fails, don't hesitate to reply with the errors. I don't mind. But it might be time to throw in the towel. From wprins at gmail.com Sun Sep 23 00:49:11 2012 From: wprins at gmail.com (Walter Prins) Date: Sat, 22 Sep 2012 23:49:11 +0100 Subject: [Tutor] Relative import help In-Reply-To: References: Message-ID: Hi, On 22 September 2012 11:56, Matthew Ngaha wrote: > from ..silverware import Silverware > heres my error mesages: ... ValueError: Attempted relative import in > non-package Just an off the cuff remark since no one else picked up on this, but the above errir message to me implies there's possibly something wrong with your __init__.py files that mark your packages. Obviously if you packages aren't considered to be packages by Python (due to for example incorrect naming of __init__.py) then your relative import stuff will NOT work... Walter From goknmuse at gmail.com Sun Sep 23 09:31:27 2012 From: goknmuse at gmail.com (Muse Gk) Date: Sun, 23 Sep 2012 15:31:27 +0800 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: Sorry, it is my mistake. I had installed python-2.7.3 32-bit on my Windows 7 64-bit machine. > c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. > ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/libpytho > n27.a when searching for -lpython27 About this error, I also do lots of researches with Google. I did not find a solution or there maybe a solution which I just do not how to do. So today, I uninstalled python-2.7.3 32-bit and installed python-2.7.3.amd64.exe lol, kill one error and the other one occurs. The detail logs about the errors: --- C:\Users\gk>cd Downloads C:\Users\gk\Downloads>cd pycrypto-2.6 C:\Users\gk\Downloads\pycrypto-2.6>set LIBRART_PATH=C:\Python27\libs C:\Users\gk\Downloads\pycrypto-2.6>set PATH=C:\Users\gk\Downloads\mingw64\bin;%P ATH% C:\Users\gk\Downloads\pycrypto-2.6>python setup.py build --compiler=mingw32 buil d_ext -DMS-WIN64 running build running build_py running build_ext running build_configure warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom' extension C:\Users\gk\Downloads\mingw64\bin\gcc.exe -mno-cygwin -mdll -Wall -std=c99 -O3 - fomit-frame-pointer -DMS-WIN64=1 -Isrc/ -IC:\Python27\include -IC:\Python27\PC - c src/winrand.c -o build\temp.win-amd64-2.7\Release\src\winrand.o :0:3: warning: ISO C99 requires whitespace after the macro name src/winrand.c:38:0: warning: "_WIN32_WINNT" redefined c:\users\gk\downloads\mingw64\bin\../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/include/_mingw.h:244:0: note: this is the location of the p revious definition writing build\temp.win-amd64-2.7\Release\src\winrandom.def C:\Users\gk\Downloads\mingw64\bin\gcc.exe -mno-cygwin -shared -s build\temp.win- amd64-2.7\Release\src\winrand.o build\temp.win-amd64-2.7\Release\src\winrandom.d ef -LC:\Python27\libs -LC:\Python27\PCbuild\amd64 -lws2_32 -ladvapi32 -lpython27 -lmsvcr90 -o build\lib.win-amd64-2.7\Crypto\Random\OSRNG\winrandom.pyd build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0xbe): undefined reference to `__imp_PyExc_SystemError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x163): undefine d reference to `__imp_PyExc_TypeError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x1d0): undefine d reference to `__imp_PyExc_TypeError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x2b4): undefine d reference to `__imp_PyExc_SystemError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x2e8): undefine d reference to `__imp_PyExc_ValueError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x328): undefine d reference to `__imp_PyExc_TypeError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x37c): undefine d reference to `__imp_PyExc_SystemError' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x3bd): undefine d reference to `__imp_PyType_Type' build\temp.win-amd64-2.7\Release\src\winrand.o:winrand.c:(.text+0x3d2): undefine d reference to `__imp_Py_InitModule4' c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. ./x86_64-w64-mingw32/bin/ld.exe: build\temp.win-amd64-2.7\Release\src\winrand.o: bad reloc address 0x18 in section `.data' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 --- Thank you, eryksun(). Is it time to throw in the towel? I think it is the time. BTW, I tried to install PyCrypto on my Virtual_Machine which OS is Fedora_17 64-bit. It only took me no more than 2 minutes to success perfect installation. lol I must use Windows at least when I am still at school. Because my major is Application Chemistry and some chemical related software only perfect supported on Windows. What's more, people around me rarely use Linux as their default OS, so am I. Though I am a little familiar with Linux and fond of Linux, I can only use it with VirtualBox. :( gk On Sun, Sep 23, 2012 at 6:38 AM, eryksun wrote: > On Sat, Sep 22, 2012 at 11:25 AM, Muse Gk wrote: >> >> c:/users/gk/downloads/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.5.4/../../../. >> ./x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\Python27\libs/libpytho >> n27.a when searching for -lpython27 > > FYI, -lpython27 is for linking to the python27 library. gcc links each > extension module against the import library "libpython27.a" so at > runtime the module can access the exported functions and data of the > shared library "python27.dll". > > I just checked the contents of the 64-bit installer, > python-2.7.3.amd64.msi, and it doesn't include libpython27.a, the > import lib needed by gcc. 64-bit ActivePython might have it, but > otherwise I suspect you have a 32-bit Python installation. Are you > sure you have 64-bit Python installed? > > The official 64-bit installer only comes with python27.lib, the import > library used by MSVC. Apparently differences in the C++ runtime > between MSVC and gcc make using gcc on Windows officially > unsupportable. (Yet they continue to include libpython27.a in the > 32-bit version, which I'd imagine is equally unsupportable.) PyCrypto > is only C, so this probably isn't an issue. I'm not 100% certain, > however. All I can say is that in the past when I used Windows I had > no problems with C extensions built with MinGW for 32-bit Python. I > mostly stick to Debian Linux these days, so I'm not up to date on the > pitfalls of 64-bit Windows. > > Assuming you've installed the official 64-bit Python, you can try > creating your own libpython27.a import lib using gendef and dlltool > (these should be in your MinGW-w64 installation). Start by copying > C:\Windows\System32\python27.dll to a temp directory. Then run the > following: > > gendef python27.dll > > This creates "python27.def", which lists the DLL's exports. Open this > file and search for "Py_InitModule4". Make sure the name has _64 > appended to it, i.e. "Py_InitModule4_64". If not, add it. Then run the > following: > > dlltool --dllname python27.dll --input-def python27.def > --output-lib libpython27.a > > Copy "libpython27.a" to C:\Python27\libs. > > As before make sure the library path is set: > > set LIBRARY_PATH=C:\Python27\libs > > For good measure, manually define the macro MS_WIN64 in the > build/install command: > > python setup.py build_ext -DMS_WIN64 install > > If this fails, don't hesitate to reply with the errors. I don't mind. > But it might be time to throw in the towel. From mylesbroomes at hotmail.co.uk Sun Sep 23 12:08:06 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 23 Sep 2012 10:08:06 +0000 Subject: [Tutor] Sudoku Message-ID: I'm currently coding a Sudoku clone but I'm having trouble displaying the board: # Sudoku # Sudoku is a logic-based number-placement puzzle # The objective is to fill a 9?9 grid with digits so that each column, each row, and each of the nine 3?3 sub-grids that compose the grid contains all of the digits from 1 to 9import randomdef new_board(): """Creates the game board. """ board=[] for i in range(9): column=[] for j in range(9): column.append(i) board.append(column) return boarddef display_board(board): """Display game board on screen.""" for i in range(9): for j in range(9): rand_num=random.randint(0,9) if rand_num not in board[i]: board[i][j]=rand_num else: board[i][j]=' ' print(board[i][j],"|")# assign the new board to a variable and display it on the screen game_board=new_board() display_board(game_board) I cant think of a way to get each column in the for loop (board[i]) to print side by side. Any help would be much appreciated. Myles. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Sep 23 13:28:39 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 23 Sep 2012 13:28:39 +0200 Subject: [Tutor] Sudoku In-Reply-To: References: Message-ID: On Sun, Sep 23, 2012 at 12:08 PM, myles broomes wrote: > > I'm currently coding a Sudoku clone but I'm having trouble displaying the > board: > > # Sudoku > # Sudoku is a logic-based number-placement puzzle > # The objective is to fill a 9?9 grid with digits so that each column, > each row, and each of the nine 3?3 sub-grids that compose the grid contains > all of the digits from 1 to 9 > import random > def new_board(): > """Creates the game board. """ > board=[] > for i in range(9): > column=[] > for j in range(9): > column.append(i) > board.append(column) > return board > def display_board(board): > """Display game board on screen.""" > for i in range(9): > for j in range(9): > rand_num=random.randint(0,9) > if rand_num not in board[i]: > board[i][j]=rand_num > else: > board[i][j]=' ' > print(board[i][j],"|") > # assign the new board to a variable and display it on the screen > game_board=new_board() > display_board(game_board) > > I cant think of a way to get each column in the for loop (board[i]) to > print side by side. Any help would be much appreciated. > > Which version of python are you using? In python 2.x, you can prevent print from adding a newline at the end by appending a comma, like this: print board[i][j], "|", in python 3.x, the print function takes an "end" argument which does the same thing: # default for end is "\n", but here we force no end character print(board[i][j], "|", end="") this way you can print multiple things on a single line. Now the only other thing you need to do is add a single newline after you print a single row. You can do that with just an empty print() call (or print statement in python 2.x) HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sun Sep 23 14:14:20 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 23 Sep 2012 08:14:20 -0400 Subject: [Tutor] Can not install pycrypto on Windows 64bit with cygwin(python27) In-Reply-To: References: Message-ID: On Sun, Sep 23, 2012 at 3:31 AM, Muse Gk wrote: > > C:\Users\gk\Downloads\pycrypto-2.6>python setup.py build --compiler=mingw32 buil > d_ext -DMS-WIN64 It's "MS_WIN64", with an underscore, not "MS-WIN64" with a hyphen. This being defined enables another macro that replaces "Py_InitModule4" in the source with "Py_InitModule4_64". That's probably why you got the error "undefined reference to `__imp_Py_InitModule4'". In case you haven't, you'll also have to manually create libpython27.a, as I described previously. Also, so that you don't need to keep typing "build --compiler=mingw32", you can create C:\Python27\Lib\distutils\distutils.cfg, containing the following: [build] compiler = mingw32 Or just use MSVC via the SDK. PyWin32 (a wrapper for the Win32 API and COM) apparently has to use the MS compiler, which means Windows Python absolutely has to be built with MSVC. That's the path of least resistance. With persistent fiddling I'm reasonably certain you can make MinGW-w64 work with 64-bit Python (at least for plain C extensions), but even if you solve these immediate problems I can't say whether or not it will just reveal another error, or how many errors you'll have to hack around before getting it to work. I'm off to read http://bugs.python.org/issue3871 to educate myself about attempts to build Python itself with MinGW. From mylesbroomes at hotmail.co.uk Sun Sep 23 15:34:09 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 23 Sep 2012 13:34:09 +0000 Subject: [Tutor] Sudoku Message-ID: Me again, I've been sat here for about an hour now staring at this code: # Sudoku # Sudoku is a logic-based number-placement puzzle # The objective is to fill a 9?9 grid with digits so that each column, each row, and each of the nine 3?3 sub-grids that compose the grid contains all of the digits from 1 to 9import randomdef new_board(): """Creates the game board. """ board=[] for i in range(9): column=[] for j in range(9): column.append(i) board.append(column) return boarddef display_board(board): """Displays the game board on screen. """ for i in range(9): for j in range(9): rand_num=random.randint(1,9) if rand_num not in board[i]: board[i][j]=rand_num else: board[i][j]=' ' print(board[i][j],"|",end='') print()# assign the new board to a variable and display it on the screen game_board=new_board() display_board(game_board) I'm cant figure out how to make it so that each column only has (at most) 1 of each number. I've managed to do it fine for the rows but I'm not sure of how I can do it for the columns. I dont want it to seem like I'm being lazy and just getting you guys to do all the work for me so I'm not necceserily asking for a solution, just advice really. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Sep 23 15:56:59 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 14:56:59 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: Message-ID: On 23/09/2012 14:34, myles broomes wrote: > > Me again, I've been sat here for about an hour now staring at this code: # Sudoku > # Sudoku is a logic-based number-placement puzzle > # The objective is to fill a 9?9 grid with digits so that each column, each row, > and each of the nine 3?3 sub-grids that compose the grid contains all of the digits > from 1 to 9 [code snipped] > I'm cant figure out how to make it so that each column only has (at most) 1 > of each number. I've managed to do it fine for the rows but I'm not sure of how I can > do it for the columns. I dont want it to seem like I'm being lazy and just getting you guys > to do all the work for me so I'm not necceserily asking for a solution, just advice really. > My advice is don't just stare, do something. Try small pieces of code in the interactive interpreter or run the code through a debugger. FWIW I rarely use a debugger but I'd recommend win pdb, which I believe runs on all platforms despite the name. -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Sun Sep 23 16:33:16 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Sep 2012 15:33:16 +0100 Subject: [Tutor] Help In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474166BC8B0@SCACMX008.exchad.jpmchase.net> <505BCDC5.3080702@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474166BE702@SCACMX008.exchad.jpmchase.net> Message-ID: On 21/09/12 15:33, Prasad, Ramit wrote: > Steven D'Aprano wrote: >> On 21/09/12 08:54, Prasad, Ramit wrote: >>> People on this list are not all receiving this via email. >> >> They're not? How else can you receive this? Unlike the main python-list, >> this isn't (as far as I know) mirrored on Usenet. >> >> I wonder under what circumstances people could read this email without >> seeing any attachments. > > My mistake, I was under the impression it was mirrored on Usenet. It is mirrored in several places such as the main Python web site, the ActiveState archive and the GMane news server.So although it's not on Usenet per se it can be read via a newsreader. It's how I receive it :-) I'm not sure how well the Python/Activestate archives support attachments but GMane seems to work just fine... A bigger problem for mobile users is that attachments use bandwidth which is often paid for by the byte so lots of attachments become expensive... Although most mobile mail tools should defer fetching attachments until specifically asked to! -- Alan G Just back from vacation and catching up... From ginarf at comcast.net Sun Sep 23 16:44:08 2012 From: ginarf at comcast.net (Gina) Date: Sun, 23 Sep 2012 09:44:08 -0500 Subject: [Tutor] casting Message-ID: <505F2038.5030403@comcast.net> what is casting? From ginarf at comcast.net Sun Sep 23 16:47:24 2012 From: ginarf at comcast.net (Gina) Date: Sun, 23 Sep 2012 09:47:24 -0500 Subject: [Tutor] What does a \ do? Message-ID: <505F20FC.1070002@comcast.net> What does a \ do? From steve at pearwood.info Sun Sep 23 17:28:14 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 24 Sep 2012 01:28:14 +1000 Subject: [Tutor] casting In-Reply-To: <505F2038.5030403@comcast.net> References: <505F2038.5030403@comcast.net> Message-ID: <505F2A8E.4070008@pearwood.info> On 24/09/12 00:44, Gina wrote: > what is casting? Depends on the context. I presume you're talking about programming, not movie-making. Without knowing the context, it's hard to tell exactly what people mean when they say "cast", but as a rough translation, you won't be terribly far wrong if you take is to mean "convert from one kind of data to a different kind" (e.g. convert an integer to a string). In some contexts, "cast" means to tell the compiler to treat a variable as a different type. For example, suppose you have a 16-bit integer (a "short") with the value 19781. If you cast it to a string ("array of two chars"), it will be treated as the string "ME". The point about casting in this case is that the compiler doesn't have to convert the data, it just treats it as a different kind of value. The actual bits remain exactly the same. But in *other* programming languages, "cast" is just a synonym for "convert", and the bits may not be the same (and probably aren't). In *those* languages, casting the integer 19781 to a string gives five digits, not two, "19781". Python is one of those languages. -- Steven From steve at pearwood.info Sun Sep 23 17:37:49 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 24 Sep 2012 01:37:49 +1000 Subject: [Tutor] What does a \ do? In-Reply-To: <505F20FC.1070002@comcast.net> References: <505F20FC.1070002@comcast.net> Message-ID: <505F2CCD.4080204@pearwood.info> On 24/09/12 00:47, Gina wrote: > What does a \ do? Depends on the context. In Python code, if you end the line with a backslash, Python will continue the line of code into the next. So: print 23 + \ x is the same as: print 23 + x Inside a string, \ is used to start an "escape sequence" which has special meaning to Python. For example, the string "x\ny" is *not* X BACKSLASH N Y, instead it is X NEWLINE Y: the \n means "newline". Some of the escape sequences are: \n newline \t tab \r carriage return \f form feed \\ backslash and others. Inside a regular expression ("import re"), backslashes are used to specify what you want to search for. For example, \d means to search for any decimal digit 0...9. Finally, inside Windows file names, backslash is used to separate folders from subfolders. You can also use forward slashes for the same thing. So: My Documents\new folder\another folder\file.txt is a Windows file pathname. -- Steven From d at davea.name Sun Sep 23 20:46:32 2012 From: d at davea.name (Dave Angel) Date: Sun, 23 Sep 2012 14:46:32 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: Message-ID: <505F5908.1010304@davea.name> On 09/23/2012 09:34 AM, myles broomes wrote: Did you have a valid reason for making a brand new thread with the same title and practically the same code? Probably most readers just decided you were double-posting, and ignored the new message. Please use reply-all when continuing with a thread. > Me again, I've been sat here for about an hour now staring at this code: # Sudoku > # Sudoku is a logic-based number-placement puzzle > # The objective is to fill a 9?9 grid with digits so that each column, each row, and each of the nine 3?3 sub-grids that compose the grid contains all of the digits from 1 to 9import randomdef new_board(): > """Creates the game board. """ > board=[] > for i in range(9): > column=[] > for j in range(9): > column.append(i) > board.append(column) > return boarddef display_board(board): Your email program messed up there, throwing out the newline after the return statement. > """Displays the game board on screen. """ > for i in range(9): > for j in range(9): > rand_num=random.randint(1,9) > if rand_num not in board[i]: > board[i][j]=rand_num Why are you doing this stuff inside a function called display_board() ? Generally, you want each function to do one thing, and to do it completely. I think you have three functions here: 1) fill the matrix with random values 2) blank out any that happen to line up in the same row or column as another of the same number. 3) print the matrix > else: > board[i][j]=' ' > print(board[i][j],"|",end='') > print()# assign the new board to a variable and display it on the screen > game_board=new_board() > display_board(game_board) > I'm cant figure out how to make it so that each column only has (at most) 1 of each number. I've managed to do it fine for the rows but I'm not sure of how I can do it for the columns. I dont want it to seem like I'm being lazy and just getting you guys to do all the work for me so I'm not necceserily asking for a solution, just advice really. > Write a triply-nested loop (row, column, rowtest), that compares a particular cell with all the others in the same column. Any time you get a match, blank out one of the cells of the match. -- DaveA From dwightdhutto at gmail.com Sun Sep 23 21:20:00 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 23 Sep 2012 15:20:00 -0400 Subject: [Tutor] Sudoku In-Reply-To: <505F5908.1010304@davea.name> References: <505F5908.1010304@davea.name> Message-ID: You have a grid that needs to be filled with zxz numbers within. This grid needs to be iteraterd through number by number in order to fulfil some criteria. Define the criteria, and then flow through each puzzle with an all inclusive search for numerical combinations, then print out the resulting configuration of numerals as the number. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Sun Sep 23 23:11:47 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 22:11:47 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 23/09/2012 20:20, Dwight Hutto wrote: > You have a grid that needs to be filled with zxz numbers within. This > grid needs to be iteraterd through number by number in order to fulfil > some criteria. > > Define the criteria, and then flow through each puzzle with an all > inclusive search for numerical combinations, then print out the > resulting configuration of numerals as the number. > > The complete lack of context reminds me of the old song "Where Have All the Flowers Gone". I guess being called Dwight means you can ignore context in the same way that drivers of Audi, BMW, Volvo, Jaguar, Mercedes and any 4x4 cars to name but a few can ignore parking rules. -- Cheers. Mark Lawrence. From wprins at gmail.com Sun Sep 23 23:20:37 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 23 Sep 2012 22:20:37 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: Mark, On 23 September 2012 22:11, Mark Lawrence wrote: > The complete lack of context reminds me of the old song "Where Have All the > Flowers Gone". I guess being called Dwight means you can ignore context in > the same way that drivers of Audi, BMW, Volvo, Jaguar, Mercedes and any 4x4 > cars to name but a few can ignore parking rules. Is the personal sniping really necessary? (That's a rhetorical question, just to be clear.) Walter From dwightdhutto at gmail.com Sun Sep 23 23:25:54 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 23 Sep 2012 17:25:54 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: > Is the personal sniping really necessary? (That's a rhetorical > question, just to be clear.) Yeah it is, welcome to netiquette 10020 with programmers. His is just a lite spectral emission compared to a real flame war. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From oscar.j.benjamin at gmail.com Sun Sep 23 23:29:55 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 23 Sep 2012 22:29:55 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On Sep 21, 2012 8:10 PM, "Gregory Lund" wrote: > print zipContents > > z.close You need to have round brackets to actually call the close method, i.e.: z.close() > ---------------------------------------- > > It works, I get the following in the Python Shell: > > '>>> ================================ RESTART ================================' > > '>>>' > > ['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip', > 'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip', > 'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/', > 'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/', > 'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip', > 'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/'] Did you mean to have the paths of folders (e.g. 'Lab_2/aforker') in the same list as the paths of zip-files (e.g. 'Lab_2/aforker/aforker_Lab2.zip')? > > '>>> ' > > But, what I can't figure out is how to get 'into' each unique folder: > aforker, allisw99, etc. and then extract any and all zips within > 'aforker', 'allisw99', etc. > > I have no doubt that the suggestions posted here will work, but they > all seem to get away from a single .py file and.... > a) I can't get them to work, and > b) it doesn't really help me because I need ONE stand alone .py file > to make this all work in ArcGIS. I don't know what ArcGIS is but if it runs Python then I'm sure that it can be done with a stand alone .py file. > > I will be using this to create an ArcGIS 'tool' that requires one > script (at least for me to comprehend it) :-) > > Thank you in advance for any and all suggestions, tips etc. > > For the record, I did try the following (to at least try > something....) at the bottom of the code above: > ----------------------- > > for item in zipContents: > itemLoc = os.path.join(outDir,item) > y = zipfile.ZipFile(itemLoc,'a') > y.extractall(os.path.aplit(itemLoc)[0]) > y.close > ------------------------ > > but I get the following error: > > Traceback (most recent call last): File > "D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts\unzip_a_zip.py", > line 50, in y = zipfile.ZipFile(itemLoc,'a') File > "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 687, in init self.fp = > open(file, modeDict[mode]) IOError: [Errno 13] Permission denied: > 'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\Lab_2/aforker/' You're trying to open the directory as if it were a zipfile. You should pass in the path to a zipfile not to a folder. Also you're opening the files in append mode 'a'. I think you really want read-only mode 'r'. > > I guess my first issue is to resolve the 'Permission denied' problem. > And, I know I need an 'if' statement, somehow... Remove the folder paths from the list of paths. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Sep 23 23:53:03 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 22:53:03 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 23/09/2012 22:20, Walter Prins wrote: > Mark, > > On 23 September 2012 22:11, Mark Lawrence wrote: >> The complete lack of context reminds me of the old song "Where Have All the >> Flowers Gone". I guess being called Dwight means you can ignore context in >> the same way that drivers of Audi, BMW, Volvo, Jaguar, Mercedes and any 4x4 >> cars to name but a few can ignore parking rules. > > Is the personal sniping really necessary? (That's a rhetorical > question, just to be clear.) > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Well if Dwight insists on replying to something without quoting the context so the rest of us haven't the faintest idea what he's talking about what are we meant to do? Sadly my mind reading capabilities are quite low, I don't know about that for anyone else. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Sun Sep 23 23:54:13 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 22:54:13 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 23/09/2012 22:25, Dwight Hutto wrote: >> Is the personal sniping really necessary? (That's a rhetorical >> question, just to be clear.) > > Yeah it is, welcome to netiquette 10020 with programmers. His is just > a lite spectral emission compared to a real flame war. > > Hurrah he's got the message and quoted some context, glad to see he's learning!!! -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Mon Sep 24 00:03:14 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 23 Sep 2012 18:03:14 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On Sun, Sep 23, 2012 at 5:53 PM, Mark Lawrence wrote: > On 23/09/2012 22:20, Walter Prins wrote: >> >> Mark, >> >> On 23 September 2012 22:11, Mark Lawrence wrote: >>> >>> The complete lack of context reminds me of the old song "Where Have All >>> the >>> Flowers Gone". I guess being called Dwight means you can ignore context >>> in >>> the same way that drivers of Audi, BMW, Volvo, Jaguar, Mercedes and any >>> 4x4 >>> cars to name but a few can ignore parking rules. >> >> >> Is the personal sniping really necessary? (That's a rhetorical >> question, just to be clear.) >> >> Walter >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Well if Dwight insists on replying to something without quoting the context > so the rest of us haven't the faintest idea what he's talking about what are > we meant to do? Sadly my mind reading capabilities are quite low, Especially if you don't follow the conversation. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Mon Sep 24 00:05:33 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 23 Sep 2012 18:05:33 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On Sun, Sep 23, 2012 at 5:54 PM, Mark Lawrence wrote: > On 23/09/2012 22:25, Dwight Hutto wrote: >>> >>> Is the personal sniping really necessary? (That's a rhetorical >>> question, just to be clear.) >> >> >> Yeah it is, welcome to netiquette 10020 with programmers. His is just >> a lite spectral emission compared to a real flame war. >> >> > > Hurrah he's got the message and quoted some context, glad to see he's > learning!!! Context was usually always used in my replies, this stems from a singular incident. Get it right, or remove yourself from the conversation. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Mon Sep 24 00:16:56 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 23:16:56 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 23/09/2012 23:05, Dwight Hutto wrote: > On Sun, Sep 23, 2012 at 5:54 PM, Mark Lawrence wrote: >> On 23/09/2012 22:25, Dwight Hutto wrote: >>>> >>>> Is the personal sniping really necessary? (That's a rhetorical >>>> question, just to be clear.) >>> >>> >>> Yeah it is, welcome to netiquette 10020 with programmers. His is just >>> a lite spectral emission compared to a real flame war. >>> >>> >> >> Hurrah he's got the message and quoted some context, glad to see he's >> learning!!! > > Context was usually always used in my replies, this stems from a > singular incident. Get it right, or remove yourself from the > conversation. > > > Not without a please. And even then I reserve the right to stay in it in the vain hope that you might learn something. Actually looking out of the window I've just spotted a squadron of low flying pigs. -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Mon Sep 24 00:21:51 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 23 Sep 2012 18:21:51 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: > window I've just spotted a squadron of low flying pigs. A family reunion no doubt. Maybe if you could pay attention instead of picking sides you would understand the argument, and comment. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Mon Sep 24 00:34:48 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Sep 2012 23:34:48 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 23/09/2012 23:21, Dwight Hutto wrote: >> window I've just spotted a squadron of low flying pigs. > > A family reunion no doubt. Maybe if you could pay attention instead of > picking sides you would understand the argument, and comment. > Sticks and stones... -- Cheers. Mark Lawrence. From gnj091405 at gmail.com Mon Sep 24 03:22:51 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Sun, 23 Sep 2012 18:22:51 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: > > > > z.close > > You need to have round brackets to actually call the close method, i.e.: > > z.close() > Fixed > > ---------------------------------------- > > > > It works, I get the following in the Python Shell: > > > > '>>> ================================ RESTART > > ================================' > > > > '>>>' > > > > ['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip', > > 'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip', > > 'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/', > > 'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/', > > 'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip', > > 'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/'] > > Did you mean to have the paths of folders (e.g. 'Lab_2/aforker') in the > same list as the paths of zip-files (e.g. 'Lab_2/aforker/aforker_Lab2.zip')? > Actually, I just used the 'zipContents = z.namelist() to see if I could get some sort of positive result of my initial unzip. It was just so I could see what I was getting. but, I see that you're correct in noticing that i do use that namelist in the next block of code, which (as you point out) isn't going to work. > > > > '>>> ' > > > > But, what I can't figure out is how to get 'into' each unique folder: > > aforker, allisw99, etc. and then extract any and all zips within > > 'aforker', 'allisw99', etc. > > > > I have no doubt that the suggestions posted here will work, but they > > all seem to get away from a single .py file and.... > > a) I can't get them to work, and > > b) it doesn't really help me because I need ONE stand alone .py file > > to make this all work in ArcGIS. > > I don't know what ArcGIS is but if it runs Python then I'm sure that it > can be done with a stand alone .py file. > ArcGIS is Esri's ArcGIS Analysis/Mapping software, that uses python for it's scripts. And, I hope that you are correct, (that I can get one stand alone .py file to work. If I can, I KNOW I can make the minor modifications necessary to use in the graphic interface. > > > > I will be using this to create an ArcGIS 'tool' that requires one > > script (at least for me to comprehend it) :-) > > > > Thank you in advance for any and all suggestions, tips etc. > > > > For the record, I did try the following (to at least try > > something....) at the bottom of the code above: > > ----------------------- > > > > for item in zipContents: > > itemLoc = os.path.join(outDir,item) > > y = zipfile.ZipFile(itemLoc,'a') > > y.extractall(os.path.aplit(itemLoc)[0]) > > y.close > > ------------------------ > > > > but I get the following error: > > > > Traceback (most recent call last): File > > > > "D:\D_Drive_Documents\Scripts\Unzip_a_zip_of_zips\Scripts\unzip_a_zip.py", > > line 50, in y = zipfile.ZipFile(itemLoc,'a') File > > "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 687, in init self.fp = > > open(file, modeDict[mode]) IOError: [Errno 13] Permission denied: > > 'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\Lab_2/aforker/' > > You're trying to open the directory as if it were a zipfile. You should > pass in the path to a zipfile not to a folder. Agreed, but how do I do that "pass in the path to a zipfile'? Using an if statement I presume? > > Also you're opening the files in append mode 'a'. I think you really want > read-only mode 'r'. > fixed it to 'r' mode. (rookie mistake) > > > > I guess my first issue is to resolve the 'Permission denied' problem. > > And, I know I need an 'if' statement, somehow... > Yes, the permission denied problem seems to be the first real obstacle, but I can't figure it out. I tried searching online but everything I found to try, didn't work. > Remove the folder paths from the list of paths. How can I remove the folder paths from the list of paths? > > Oscar From oscar.j.benjamin at gmail.com Mon Sep 24 03:34:47 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 02:34:47 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On 24 September 2012 02:22, Gregory Lund wrote: > > You're trying to open the directory as if it were a zipfile. You should > > pass in the path to a zipfile not to a folder. > > Agreed, but how do I do that "pass in the path to a zipfile'? > Using an if statement I presume? > > > > > > > I guess my first issue is to resolve the 'Permission denied' problem. > > > And, I know I need an 'if' statement, somehow... > > > Yes, the permission denied problem seems to be the first real > obstacle, but I can't figure it out. > I tried searching online but everything I found to try, didn't work. > The permission error is because you are trying to open a folder as if it were a file. The operating system does not give you permission to do this because it is a nonsensical operation. > Remove the folder paths from the list of paths. > > How can I remove the folder paths from the list of paths? > You can do it with a list comprehension: import os.path paths = [p for p in paths if os.path.isdir(p)] Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Sep 24 03:37:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 02:37:06 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On 24 September 2012 02:34, Oscar Benjamin wrote: > On 24 September 2012 02:22, Gregory Lund wrote: > > >> > You're trying to open the directory as if it were a zipfile. You should >> > pass in the path to a zipfile not to a folder. >> >> Agreed, but how do I do that "pass in the path to a zipfile'? >> Using an if statement I presume? >> >> > > >> >> > > I guess my first issue is to resolve the 'Permission denied' problem. >> > > And, I know I need an 'if' statement, somehow... >> > >> Yes, the permission denied problem seems to be the first real >> obstacle, but I can't figure it out. >> I tried searching online but everything I found to try, didn't work. >> > > The permission error is because you are trying to open a folder as if it > were a file. The operating system does not give you permission to do this > because it is a nonsensical operation. > > > Remove the folder paths from the list of paths. >> >> How can I remove the folder paths from the list of paths? >> > > You can do it with a list comprehension: > > import os.path > paths = [p for p in paths if os.path.isdir(p)] > Sorry that should be (note the 'not'): paths = [p for p in paths if not os.path.isdir(p)] Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnj091405 at gmail.com Mon Sep 24 04:00:18 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Sun, 23 Sep 2012 19:00:18 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: >>> > You're trying to open the directory as if it were a zipfile. You should >>> > pass in the path to a zipfile not to a folder. >>> >>> Agreed, but how do I do that "pass in the path to a zipfile'? >>> Using an if statement I presume? >>> >>> > > >>> >>> > > I guess my first issue is to resolve the 'Permission denied' problem. >>> > > And, I know I need an 'if' statement, somehow... >>> > >>> Yes, the permission denied problem seems to be the first real >>> obstacle, but I can't figure it out. >>> I tried searching online but everything I found to try, didn't work. >> >> >> The permission error is because you are trying to open a folder as if it >> were a file. The operating system does not give you permission to do this >> because it is a nonsensical operation. >> >>> > Remove the folder paths from the list of paths. >>> >>> How can I remove the folder paths from the list of paths? >> >> >> You can do it with a list comprehension: >> >> import os.path >> paths = [p for p in paths if os.path.isdir(p)] > > > Sorry that should be (note the 'not'): > paths = [p for p in paths if not os.path.isdir(p)] > Ok, but where do I put that? Sorry Oscar, I don't know where to put it, nor do I know how to use 'paths' once I do that. I was trying this prior to getting your email about paths...(I put this after z.close() for item in zipContents: if item(-4) == ('.zip'): x = zipfile.Zipfile(item,'r') x.extractall() x.close() but, I kept getting a "TypeError: 'str' object is not callable" error. then I tried for item in zipContents: if item.lower() .endswith(".zip"): item.extractall() item.close() but got a " item.extractall() AttributeError: 'str' object has no attribute 'extractall'" error Can't say I'm not trying. :-) not working, but i'm trying whatever I can. I greatly appreciate the help Oscar! Greg From oscar.j.benjamin at gmail.com Mon Sep 24 04:17:43 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 03:17:43 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On 24 September 2012 03:00, Gregory Lund wrote: > >>> > You're trying to open the directory as if it were a zipfile. You > should > >>> > pass in the path to a zipfile not to a folder. > >>> > >>> Agreed, but how do I do that "pass in the path to a zipfile'? > >>> Using an if statement I presume? > >>> > >>> > > > >>> > >>> > > I guess my first issue is to resolve the 'Permission denied' > problem. > >>> > > And, I know I need an 'if' statement, somehow... > >>> > > >>> Yes, the permission denied problem seems to be the first real > >>> obstacle, but I can't figure it out. > >>> I tried searching online but everything I found to try, didn't work. > >> > >> > >> The permission error is because you are trying to open a folder as if it > >> were a file. The operating system does not give you permission to do > this > >> because it is a nonsensical operation. > >> > >>> > Remove the folder paths from the list of paths. > >>> > >>> How can I remove the folder paths from the list of paths? > >> > >> > >> You can do it with a list comprehension: > >> > >> import os.path > >> paths = [p for p in paths if os.path.isdir(p)] > > > > > > Sorry that should be (note the 'not'): > > paths = [p for p in paths if not os.path.isdir(p)] > > > Ok, but where do I put that? > Sorry Oscar, I don't know where to put it, nor do I know how to use > 'paths' once I do that. > > I was trying this prior to getting your email about paths...(I put > this after z.close() > > for item in zipContents: > if item(-4) == ('.zip'): > That should be: if item[-4:] == '.zip' but a better way to do that is: if item.endswith('.zip') x = zipfile.Zipfile(item,'r') > x.extractall() > x.close() > > but, I kept getting a "TypeError: 'str' object is not callable" error. > > then I tried > > for item in zipContents: > if item.lower() .endswith(".zip"): > Ok that's better. > item.extractall() > item.close() > > but got a " item.extractall() > AttributeError: 'str' object has no attribute 'extractall'" error > item is a string object. You need to use that string to create a ZipFile object and then call extractall() on the ZipFile object (the way you did in your original post in this thread). Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnj091405 at gmail.com Mon Sep 24 04:26:51 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Sun, 23 Sep 2012 19:26:51 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: > > but a better way to do that is: > if item.endswith('.zip') > >> x = zipfile.Zipfile(item,'r') >> x.extractall() >> x.close() >> ok, I used that (above) typed below: for item in zipContents: if item.endswith('.zip'): x = zipfile.Zipfile(item,'r') x.extractall() x.close() but now get a " x = zipfile.Zipfile(item,'r') AttributeError: 'module' object has no attribute 'Zipfile' " error grrrrr, this is going to send me to the funny farm! greg From oscar.j.benjamin at gmail.com Mon Sep 24 04:59:21 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 03:59:21 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: On 24 September 2012 03:26, Gregory Lund wrote: > > > > but a better way to do that is: > > if item.endswith('.zip') > > > >> x = zipfile.Zipfile(item,'r') > >> x.extractall() > >> x.close() > >> > ok, I used that (above) > typed below: > > for item in zipContents: > if item.endswith('.zip'): > x = zipfile.Zipfile(item,'r') > x.extractall() > x.close() > > but now get a " x = zipfile.Zipfile(item,'r') > AttributeError: 'module' object has no attribute 'Zipfile' " > Capital F. ZipFile not Zipfile. > > error > > grrrrr, this is going to send me to the funny farm! > > greg > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Sep 24 05:15:07 2012 From: d at davea.name (Dave Angel) Date: Sun, 23 Sep 2012 23:15:07 -0400 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: <505FD03B.3090706@davea.name> On 09/23/2012 10:26 PM, Gregory Lund wrote: > > > for item in zipContents: > if item.endswith('.zip'): > x = zipfile.Zipfile(item,'r') > x.extractall() > x.close() > > but now get a " x = zipfile.Zipfile(item,'r') > AttributeError: 'module' object has no attribute 'Zipfile' " > > error > > grrrrr, this is going to send me to the funny farm! > > greg > One way to avoid the "funny farm" is to learn to use the tools that Python provides, built-in. As soon as you get an error like that one, add a print statement immediately before the one in error, and find the type and attributes of the object that supposedly doesn't have the attribute. For example, you could have added a dir(zipfile), and then studied the one that seems to be the same as the one you tried to use. Presumably you would have quickly discovered what Oscar pointed out. We all make typos, the difference is in how quickly we find and fix them. Use the tools. -- DaveA From fomcl at yahoo.com Mon Sep 24 12:02:55 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 24 Sep 2012 03:02:55 -0700 (PDT) Subject: [Tutor] Borg di borg di borg (or: Swedish chef) Message-ID: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> Hi Pythonistas, I have three classes, Generic, Test and Test2. Generic contains a load method that loads a file. This may only be done once, as a file_read_open error is returned if the file is open already and an attempt is made to re-open it. The file may be opened from Test or Test2. After a lot of playing with a "counter" class variable, I realized this may be a legitimate use case for the Borg pattern (http://code.activestate.com/recipes/66531). Is the code below the right way to apply the Borg pattern? somefile = "/home/albertjan/Desktop/somefile.txt" class Borg(object): ??? counter = 0 ??? _state = {} ??? def __init__(self): ??????? self.__dict__ = self._state class Generic(Borg): ?? ? ??? def __init__(self): ??????? super(Generic, self).__init__() ??????? self.loaded = self.load() ??????? print "@state", Borg._state ??????? print self.loaded ?????? ? ??? def load(self): ??????? """ Only one file at a time may be opened, or else ??????? there will be an open-read error""" ??????? Borg.counter += 1 ??????? return open(somefile) class Test(Generic): ?? ? ??? def __init__(self): ??????? if Borg.counter == 0: ??????????? self.theFile = Generic().load() ??????? self.theFile = Borg._state["loaded"] ??????? print self.theFile class Test2(Generic): ??? def __init__(self): ??????? if Borg.counter == 0: ??????????? self.theFile = Generic().load()????? ? ??????? self.theFile = Borg._state["loaded"] ??????? print "---", self.theFile ??????? print Borg.counter ?????? ? b2 = Test2() b1 = Test() Thank you in advance! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From __peter__ at web.de Mon Sep 24 12:38:33 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2012 12:38:33 +0200 Subject: [Tutor] Borg di borg di borg (or: Swedish chef) References: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > Hi Pythonistas, > > I have three classes, Generic, Test and Test2. Generic contains a load > method that loads a file. This may only be done once, as a file_read_open > error is returned if the file is open already and an attempt is made to > re-open it. The file may be opened from Test or Test2. After a lot of > playing with a "counter" class variable, I realized this may be a > legitimate use case for the Borg pattern > (http://code.activestate.com/recipes/66531). Is the code below the right > way to apply the Borg pattern? What do you gain from that complexity? Even assert b1.load() is b2.load() will fail. So why not keep it simple? _file = None def load_file(): global _file if _file is None: _file = open(somefile) return _file (if you are using multiple threads you have to add a lock) Of course you can bypass this "safety" measure by doing open(somefile) anywhere in your code, so it is more like a gentleman's agreement between you and yourself not to tread over the red line. From bfishbein79 at gmail.com Mon Sep 24 18:41:40 2012 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 24 Sep 2012 11:41:40 -0500 Subject: [Tutor] running program in terminal Message-ID: Hello. I can run programs in IDLE but when I try to do it in a terminal or with textwrangler, it usually just logs out and says it's completed, but the program hasn't been run. This is particularly so when the program uses urllib. I'm using OS X. logout [Process completed] That's what it prints. Any idea what to do? Ben From wprins at gmail.com Mon Sep 24 18:52:30 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 24 Sep 2012 17:52:30 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: Mark, On 23 September 2012 22:53, Mark Lawrence wrote: >> Is the personal sniping really necessary? (That's a rhetorical >> question, just to be clear.) > > Well if Dwight insists on replying to something without quoting the context > so the rest of us haven't the faintest idea what he's talking about what are > we meant to do? Sadly my mind reading capabilities are quite low, I don't > know about that for anyone else. Well then tell him how to do it properly and/or provide a better answer without the personal invective. No one expects you to read minds obviously, but the personal attacks and sarcasm are really way out of line. I can only hang my head in shame at what Myles must be thinking of all this. So childish. Walter From eryksun at gmail.com Mon Sep 24 19:01:30 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 24 Sep 2012 13:01:30 -0400 Subject: [Tutor] Borg di borg di borg (or: Swedish chef) In-Reply-To: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> References: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: On Mon, Sep 24, 2012 at 6:02 AM, Albert-Jan Roskam wrote: > > I have three classes, Generic, Test and Test2. Generic contains a load > method that loads a file. This may only be done once, as a > file_read_open error is returned if the file is open already and an > attempt is made to re-open it. The file may be opened from Test or Test2. What's the context here? Is "file_read_open error" an error code returned by a library? If so, I'd pass it on by raising an exception instead of masking the error. As to the Borg pattern, it seems to me you don't actually need a 'Borg' base class. But if you do, then you probably also want to override _state with a new dict for each subclass. You can do this automatically with a custom descriptor, a metaclass, or even a simple property like the following: class Borg(object): _all_state = {} def __init__(self): self.__dict__ = self._state @property def _state(self): return self._all_state.setdefault(self.__class__, {}) class Generic(Borg): def __init__(self): super(Generic, self).__init__() self.loaded = None def load(self, filename): """ Only one file at a time may be opened, or else there will be an open-read error""" if self.loaded is None: self.loaded = open(filename) return self.loaded From oscar.j.benjamin at gmail.com Mon Sep 24 19:02:30 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 18:02:30 +0100 Subject: [Tutor] running program in terminal In-Reply-To: References: Message-ID: On 24 September 2012 17:41, Benjamin Fishbein wrote: > Hello. I can run programs in IDLE but when I try to do it in a terminal or > with textwrangler, it usually just logs out and says it's completed, but > the program hasn't been run. This is particularly so when the program uses > urllib. I'm using OS X. > > logout > > [Process completed] > Are you using the python launcher? Or are you opening a terminal and then typing 'python myscript.py'? Tell me if the following steps work for you: 1) Open the terminal - you can find it under Applications/Utiltiies (or if you just type 'terminal' in spotlight). You should see something like: Last login: Tue Mar 6 17:21:36 on console Welcome to Darwin! ibook:~ Alex$ 2) Type 'cd name/of/folder' and hit enter to move into the folder that contains your Python script. 3) Type 'python myscript.py' and hit enter to run the script called 'myscript.py'. Oscar About the terminal: http://macapper.com/2007/03/08/the-terminal-an-introduction/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Sep 24 21:16:39 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Sep 2012 20:16:39 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: On 24/09/2012 17:52, Walter Prins wrote: > Mark, > > On 23 September 2012 22:53, Mark Lawrence wrote: >>> Is the personal sniping really necessary? (That's a rhetorical >>> question, just to be clear.) >> >> Well if Dwight insists on replying to something without quoting the context >> so the rest of us haven't the faintest idea what he's talking about what are >> we meant to do? Sadly my mind reading capabilities are quite low, I don't >> know about that for anyone else. > > Well then tell him how to do it properly and/or provide a better > answer without the personal invective. No one expects you to read > minds obviously, but the personal attacks and sarcasm are really way > out of line. I can only hang my head in shame at what Myles must be > thinking of all this. So childish. > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Dwight Hutto refers to my family as pigs and you have a go at me, what a downright bloody check. We're here to teach Python. If he's too thick to understand context he can search the web for the word or resort to a dictionary. -- Cheers. Mark Lawrence. From aijathompson at hotmail.com Mon Sep 24 21:13:15 2012 From: aijathompson at hotmail.com (Aija Thompson) Date: Mon, 24 Sep 2012 15:13:15 -0400 Subject: [Tutor] BMI Question Message-ID: Hi! So I've been working on this question for hours! And Python keeps giving me an error saying that my syntax for BMI is wrong. I really can't understand why. So this is what I have so far: w = raw_input('Please give your weight in lbs: ')h = raw_input('Now your height in feet and inches: ')h. split("'")ft, inches = h. split("'")h_sum = float(12*int(ft)) + (int(inches.strip('"'))BMI = float(703*w)/float(h_sum*h_sum)print 'Your BMI is: ', BMI It's the first BMI that isn't agreeing with Python. Any help would do! Also, if there are any other serious problems, maybe you could let me know. I'm still having some trouble learning all of this. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From aijathompson at hotmail.com Mon Sep 24 21:15:42 2012 From: aijathompson at hotmail.com (Aija Thompson) Date: Mon, 24 Sep 2012 15:15:42 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: , <505F5908.1010304@davea.name>, , , , , , Message-ID: I'm sorry, I have no idea how this has any reference to my Python question... > To: tutor at python.org > From: breamoreboy at yahoo.co.uk > Date: Mon, 24 Sep 2012 20:16:39 +0100 > Subject: Re: [Tutor] Sudoku > > On 24/09/2012 17:52, Walter Prins wrote: > > Mark, > > > > On 23 September 2012 22:53, Mark Lawrence wrote: > >>> Is the personal sniping really necessary? (That's a rhetorical > >>> question, just to be clear.) > >> > >> Well if Dwight insists on replying to something without quoting the context > >> so the rest of us haven't the faintest idea what he's talking about what are > >> we meant to do? Sadly my mind reading capabilities are quite low, I don't > >> know about that for anyone else. > > > > Well then tell him how to do it properly and/or provide a better > > answer without the personal invective. No one expects you to read > > minds obviously, but the personal attacks and sarcasm are really way > > out of line. I can only hang my head in shame at what Myles must be > > thinking of all this. So childish. > > > > Walter > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > Dwight Hutto refers to my family as pigs and you have a go at me, what a > downright bloody check. We're here to teach Python. If he's too thick > to understand context he can search the web for the word or resort to a > dictionary. > > -- > Cheers. > > Mark Lawrence. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen at averagesecurityguy.info Mon Sep 24 21:21:01 2012 From: stephen at averagesecurityguy.info (Stephen Haywood) Date: Mon, 24 Sep 2012 15:21:01 -0400 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: <7340977862280466689@unknownmsgid> On Sep 24, 2012, at 3:16 PM, Aija Thompson wrote: Hi! So I've been working on this question for hours! And Python keeps giving me an error saying that my syntax for BMI is wrong. I really can't understand why. So this is what I have so far: w = raw_input('Please give your weight in lbs: ') h = raw_input('Now your height in feet and inches: ') h. split("'") ^^^^^ This doesn't seem necessary. ft, inches = h. split("'") h_sum = float(12*int(ft)) + (int(inches.strip('"')) ^^^^^ You have three opening parents on this line and only two closing parens. BMI = float(703*w)/float(h_sum*h_sum) print 'Your BMI is: ', BMI It's the first BMI that isn't agreeing with Python. Any help would do! Also, if there are any other serious problems, maybe you could let me know. I'm still having some trouble learning all of this. Thanks! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From aijathompson at hotmail.com Mon Sep 24 21:20:34 2012 From: aijathompson at hotmail.com (Aija Thompson) Date: Mon, 24 Sep 2012 15:20:34 -0400 Subject: [Tutor] Python Assignment Question Message-ID: Hi! I've been working on this question for a long time and for some reason it's just not clicking. I'm not sure if my loop for the question is the right one, or if I'm even on the right track. We're supposed to make a program that counts the number of days into the year it is if you input a date. Not including leap years. This is what I have so far: months = 'January, February, March, April, May, June, July, August, September, October, November, December'daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' #shorterMonths = 'February, April, June, September, Novmeber'#longerMonths = 'January, March, May, July, August, October, December' month = raw_input('Enter the month: ')day = raw_input('Enter the day: ') for x in month: whichMonth = months.index(x) monthNumber = daysPerMonth[whichMonth] dayYear.append(monthNumber) I was hoping to make a loop that would check which month it is and compare it to the second list I made with the number of days in that month. I don't know if I've made that clear to the program or not. Either way, I feel pretty lost at the moment. Any help would do! Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Sep 24 22:01:28 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Sep 2012 21:01:28 +0100 Subject: [Tutor] Sudoku In-Reply-To: References: , <505F5908.1010304@davea.name>, , , , , , Message-ID: On 24/09/2012 20:15, Aija Thompson wrote: > > I'm sorry, I have no idea how this has any reference to my Python question... > Please accept my apologies for getting completely off topic on your thread. -- Cheers. Mark Lawrence. From eryksun at gmail.com Mon Sep 24 22:10:56 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 24 Sep 2012 16:10:56 -0400 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 3:13 PM, Aija Thompson wrote: > > ft, inches = h. split("'") > h_sum = float(12*int(ft)) + (int(inches.strip('"')) Leave h_sum as an int: h_sum = 12 * int(ft) + int(inches.strip('"')) A better name here would be "h_inch". Also, make sure your parentheses are closed. You have an extra left parenthesis in your expression. A good editor will highlight matching parentheses. > BMI = float(703*w)/float(h_sum*h_sum) w is a string. Multiplying a string by N gives you a new string containing N copies. For example, 703 copies of "180" is a number string beyond the range of a float, so the result is inf (infinity). You need to convert w to an int before multiplying. Also, the expression is evaluated from left to right (based on standard order of operations) and will return a float if you start with the constant 703.0. For example 703.0 * 180 / (72 * 72) == 24.40972222222222. Here's the revised expression: BMI = 703.0 * int(w) / (h_sum * h_sum) Finally, you can round the BMI before printing, say to 2 decimal places: print 'Your BMI is:', round(BMI, 2) But using string formatting would be better: print 'Your BMI is: %.2f' % BMI From ramit.prasad at jpmorgan.com Mon Sep 24 22:05:45 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 24 Sep 2012 20:05:45 +0000 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166C540C@SCACMX008.exchad.jpmchase.net> Aija Thompson wrote: > Hi! > > So I've been working on this question for hours! And Python keeps giving me an > error saying that my syntax for BMI is wrong. I really can't understand why. > > So this is what I have so far: One suggestion: immediately convert to appropriate number type instead of storing the string values. It lets you know in the appropriate spot if there was a problem with the input instead of hiding it for later when you actually use the values. > > w = raw_input('Please give your weight in lbs: ') > h = raw_input('Now your height in feet and inches: ') > h. split("'") This line does nothing since the result of h.split("'") > ft, inches = h. split("'") ft = int(h.split("'")[0]) inches = int(h.split("'")[1].split('"')[0].strip()) weight = float(w) # or int? > h_sum = float(12*int(ft)) + (int(inches.strip('"')) Stephen already commented on your syntax error on the line above. h_sum = 12.0 * ft + inches # The .0 will force float multiplication > BMI = float(703*w)/float(h_sum*h_sum) The above line fails because you never converted `w` to a number. In addition, you do not need to convert everything to a float. One float in the equation should mean that Python returns the result of that equation as a float. BMI = 703.0 * weight / h_sum**2 > print 'Your BMI is: ', BMI > > It's the first BMI that isn't agreeing with Python. Any help would do! > > Also, if there are any other serious problems, maybe you could let me know. > I'm still having some trouble learning all of this. > > Thanks! This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From breamoreboy at yahoo.co.uk Mon Sep 24 22:16:23 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Sep 2012 21:16:23 +0100 Subject: [Tutor] Python Assignment Question In-Reply-To: References: Message-ID: On 24/09/2012 20:20, Aija Thompson wrote: > > Hi! > I've been working on this question for a long time and for some reason it's just not clicking. > I'm not sure if my loop for the question is the right one, or if I'm even on the right track. > We're supposed to make a program that counts the number of days into the year it is if you input a date. Not including leap years. > This is what I have so far: > months = 'January, February, March, April, May, June, July, August, September, October, November, December'daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' #shorterMonths = 'February, April, June, September, Novmeber'#longerMonths = 'January, March, May, July, August, October, December' > month = raw_input('Enter the month: ')day = raw_input('Enter the day: ') > for x in month: whichMonth = months.index(x) monthNumber = daysPerMonth[whichMonth] dayYear.append(monthNumber) > I was hoping to make a loop that would check which month it is and compare it to the second list I made with the number of days in that month. I don't know if I've made that clear to the program or not. Either way, I feel pretty lost at the moment. > Any help would do! > Thanks! Your code is basically unreadable in Thunderbird but as I pinched another of your threads I've had a go at untangling it. What you're doing is getting an index into a string. You want to get an index into a list. You can also simplfy the whole structure so search the web for "python two dimensional lists", without the quotes of course. HTH. -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Mon Sep 24 22:24:22 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 24 Sep 2012 16:24:22 -0400 Subject: [Tutor] Python Assignment Question In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 3:20 PM, Aija Thompson wrote: > Hi! > > I've been working on this question for a long time and for some reason it's > just not clicking. Algorithm is the appropriate approach. That's what makes it click. > > I'm not sure if my loop for the question is the right one, or if I'm even on > the right track. > > We're supposed to make a program that counts the number of days into the > year it is if you input a date. Not including leap years. We'll leave leap years alone for now then, but there are special years for that input which could be used as a count variable. > > This is what I have so far: > > months = 'January, February, March, April, May, June, July, August, > September, October, November, December' > daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' > > #shorterMonths = 'February, April, June, September, Novmeber' > #longerMonths = 'January, March, May, July, August, October, December' I'd suggest using a dictionary with the month as the identifier(month_dict = {'january' : 31, 'february': [28,29]}, and an integer as the value for each static count of months. > > month = raw_input('Enter the month: ') > day = raw_input('Enter the day: ') > > for x in month: > whichMonth = months.index(x) > monthNumber = daysPerMonth[whichMonth] > dayYear.append(monthNumber) > > I was hoping to make a loop that would check which month it is and compare > it to the second list I made with the number of days in that month. I don't > know if I've made that clear to the program or not. Either way, I feel > pretty lost at the moment. > > Any help would do! > > Thanks! > But in the end, you just want to count days. So you could iterate through the dictionary's values_of days in each month, up until the month and the date matches(loop stops), while using a day_count += 1 in the loop. Just check for the value of the month, and the number of the day to stop the loop count. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Mon Sep 24 22:30:28 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 24 Sep 2012 16:30:28 -0400 Subject: [Tutor] Python Assignment Question In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 4:24 PM, Dwight Hutto wrote: > On Mon, Sep 24, 2012 at 3:20 PM, Aija Thompson wrote: >> Hi! >> >> I've been working on this question for a long time and for some reason it's >> just not clicking. > > Algorithm is the appropriate approach. That's what makes it click. > >> >> I'm not sure if my loop for the question is the right one, or if I'm even on >> the right track. >> >> We're supposed to make a program that counts the number of days into the >> year it is if you input a date. Not including leap years. > > We'll leave leap years alone for now then, but there are special years > for that input which could be used as a count variable. > >> >> This is what I have so far: >> >> months = 'January, February, March, April, May, June, July, August, >> September, October, November, December' >> daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' >> >> #shorterMonths = 'February, April, June, September, Novmeber' >> #longerMonths = 'January, March, May, July, August, October, December' > > I'd suggest using a dictionary with the month as the > identifier(month_dict = {'january' : 31, 'february': [28,29]}, and an > integer as the value for each static count of months. > >> >> month = raw_input('Enter the month: ') >> day = raw_input('Enter the day: ') >> >> for x in month: >> whichMonth = months.index(x) >> monthNumber = daysPerMonth[whichMonth] >> dayYear.append(monthNumber) >> >> I was hoping to make a loop that would check which month it is and compare >> it to the second list I made with the number of days in that month. I don't >> know if I've made that clear to the program or not. Either way, I feel >> pretty lost at the moment. >> >> Any help would do! >> >> Thanks! >> > > But in the end, you just want to count days. > So you could iterate through the dictionary's values_of days in each > month, up until the month and the date matches(loop stops), while > using a day_count += 1 in the loop. > Or just count each month's days in the loop, and then when you hit the month, add the days to the adding of the previous months, which just would increment based on the dictionary's value, instead of a 1 count loop, you get an addition of the months prior to the date, plus how many days into the current month you want to find how many days into the year you are. For leap year just use a standard year, and if that year jn the input, or every 4 years past that, add in 1 day. > Just check for the value of the month, and the number of the day to > stop the loop count. > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com From ramit.prasad at jpmorgan.com Mon Sep 24 22:32:38 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 24 Sep 2012 20:32:38 +0000 Subject: [Tutor] Python Assignment Question In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166C5474@SCACMX008.exchad.jpmchase.net> Aija Thompson wrote: > Hi! > > I've been working on this question for a long time and for some reason it's > just not clicking. > > I'm not sure if my loop for the question is the right one, or if I'm even on > the right track. > > We're supposed to make a program that counts the number of days into the year > it is if you input a date. Not including leap years. > > This is what I have so far: > > months = 'January, February, March, April, May, June, July, August, September, > October, November, December' This is a string of months. That will not be very helpful to you. Looking at your later code this should be a list. months = [ 'January', 'February',.... ] > daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' Same problem here, but given your months I would use a dictionary so you can map the month to the days per month. months = { 1 : 31, 2 : 28 } Note the lack of quotes around 31 and 28. That means these are Python numbers and not strings. Numbers will be more useful while calculating. Instead of using the month names, I figured it would be more useful to know the month number. > > #shorterMonths = 'February, April, June, September, Novmeber' > #longerMonths = 'January, March, May, July, August, October, December' > > month = raw_input('Enter the month: ') > day = raw_input('Enter the day: ') > > for x in month: > ? ? ? ? whichMonth = months.index(x) > ? ? ? ? monthNumber = daysPerMonth[whichMonth] > ? ? ? ? dayYear.append(monthNumber) If you iterate through months (unlike the month as written) it would iterate through all months regardless if x is December while the date input is say August. # Untested days = 0 month = int( raw_input( 'month: ' ) ) day_of_month = int( raw_input( 'day: ' ) ) current_month = 1 while current_month < month: # For all months before desired month days += months[ current_month ] # Now add days for current month. days += day_of_month > > I was hoping to make a loop that would check which month it is and compare it > to the second list I made with the number of days in that month. I don't know > if I've made that clear to the program or not. Either way, I feel pretty lost > at the moment. Although the above should work, it is not very flexible. I would probably look at the date class in the datetime module. You can use the date class to compare dates and increment the days. This has the advantage of taking into account things like leap years and paves the way for calculating days between ranges (which I suspect will be an upcoming assignment if you are a student). Of course, this is computationally inefficient but it should be "fast enough" and work. The pseudo-code is written below. while current_date < desired_date days +=1 current_date += 1 # look at the datetime.timedelta class to do this > > Any help would do! > > Thanks! This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Mon Sep 24 22:48:56 2012 From: d at davea.name (Dave Angel) Date: Mon, 24 Sep 2012 16:48:56 -0400 Subject: [Tutor] Python Assignment Question In-Reply-To: References: Message-ID: <5060C738.7050906@davea.name> On 09/24/2012 03:20 PM, Aija Thompson wrote: > Hi! > I've been working on this question for a long time and for some reason it's just not clicking. > I'm not sure if my loop for the question is the right one, or if I'm even on the right track. > We're supposed to make a program that counts the number of days into the year it is if you input a date. Not including leap years. > This is what I have so far: > months = 'January, February, March, April, May, June, July, August, September, October, November, December'daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' #shorterMonths = 'February, April, June, September, Novmeber'#longerMonths = 'January, March, May, July, August, October, December' > month = raw_input('Enter the month: ')day = raw_input('Enter the day: ') > for x in month: whichMonth = months.index(x) monthNumber = daysPerMonth[whichMonth] dayYear.append(monthNumber) > I was hoping to make a loop that would check which month it is and compare it to the second list I made with the number of days in that month. I don't know if I've made that clear to the program or not. Either way, I feel pretty lost at the moment. > Any help would do! > Thanks! > Please don't send an html message; this is a text mailing list, and your text is hopelessly mangled. For the benefit of others, I reformatted the code and enclose it here, with tabs turned into 4 spaces. months = 'January, February, March, April, May, June, July, August, September, October, November, December' daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' #shorterMonths = 'February, April, June, September, Novmeber' #longerMonths = 'January, March, May, July, August, October, December' month = raw_input('Enter the month: ') day = raw_input('Enter the day: ') for x in month: print "x = ", x whichMonth = months.index(x) monthNumber = daysPerMonth[whichMonth] dayYear.append(monthNumber) is this your first assignment? Have you worked in any other programming language before learning Python? Are you working with CPython 2.7 ? Most of this code makes no sense to me at all. Why isn't months a list of strings? Why isn't daysPerMonth a list of ints? (I'm assuming that shorterMonths and longerMonths are vestigial code. If not, the two spellings for November would surely cause troubles. Why do you define day as a string, and not an int? And why is the loop looping through the characters in the specified month? Have you tried to describe in English how to solve the problem? -- DaveA From dwightdhutto at gmail.com Mon Sep 24 22:52:38 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 24 Sep 2012 16:52:38 -0400 Subject: [Tutor] Sudoku In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: Dwight, Please stop responding to Mark. His behaviour is typical schoolyard bully, meaning he's saying things precisely because he gets a reaction from you. He probably doesn't even realise that he's doing it consciously, but either way the best way to deal with such behaviour is to stop giving such a person what they want, e.g. the reaction. So, please just **stop responding** to any of his posts I respond, to let him know that he just thinks I don't add context, but lacks the ability to cheeck, that I do try to include context, but in these question answer sessions, you should be following, the conversation, which should put everything into context. . He'll soon grow bored and move on. If you had kept out of the conversation when I'd originally replied to him then I'd have been able to take him to task for his childish behaviour. As it stands now unfortunately, Myles' thread has become a wasteland of exchanges between yourself and him. Again: Please just stop responding to him. Well, It's an argument, and I won't let him win. I could stop responding, but then he would think he had won, and do it to someone else. He's wrong. He took one response out of context, and assumed that is what I do, when usually it's just I followed the conversation for real, and if he had, then he would know the context in which a certain comment was made. Thank you sincerely, Walter Prins On Mon, Sep 24, 2012 at 3:16 PM, Mark Lawrence wrote: > On 24/09/2012 17:52, Walter Prins wrote: >> >> Mark, >> >> On 23 September 2012 22:53, Mark Lawrence wrote: >>>> >>>> Is the personal sniping really necessary? (That's a rhetorical >>>> question, just to be clear.) >>> >>> Well if Dwight insists on replying to something without quoting the >>> context >>> so the rest of us haven't the faintest idea what he's talking about what >>> are >>> we meant to do? Sadly my mind reading capabilities are quite low, I >>> don't >>> know about that for anyone else. >> >> >> Well then tell him how to do it properly and/or provide a better >> answer without the personal invective. No one expects you to read >> minds obviously, but the personal attacks and sarcasm are really way >> out of line. I can only hang my head in shame at what Myles must be >> thinking of all this. So childish. >> >> Walter He only has one conversation to prove his point on, and I made the point of telling him I was following a short conversation(at the time), and therefore needed no context at the time, because the OP is following the thread for the answer, and knows the context. Walter's point of entry into the thread is of no concern to me, because the OP is following the conversation. If Walter wants to know the context, read the every post just like the OP would, because that's who I'm responding to, not Walter. > Dwight Hutto refers to my family as pigs and you have a go at And when did I do that, please point out where I said that about your family. > downright bloody check. We're here to teach Python. If he's too thick to > understand context he can search the web for the word or resort to a > dictionary. If you're too thick to understand that sometimes it's an offhand remark to JUST the OP, then you don't understand the context of a tutor session in which one person asks a question, and gets responses. You also seem to have missed lots of other conversations, where my replies are in line. You want an argument, and in this case you lose, because you couldn't understand the context of my remark, because you think that every time I respond it's without inline responses. You don't know enough about me to say I always quote out of context, and I can provide the evidence that I do. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From aijathompson at hotmail.com Mon Sep 24 22:56:14 2012 From: aijathompson at hotmail.com (Aija Thompson) Date: Mon, 24 Sep 2012 16:56:14 -0400 Subject: [Tutor] Python Assignment Question In-Reply-To: <5060C738.7050906@davea.name> References: , <5060C738.7050906@davea.name> Message-ID: Hi, Yeah this is my first assignment and I've never worked on anything programming before. I am working in Python 2.7 The shorter and longer months thing is just a not to myself, that is why it has the hash tag before he sentence. But my initial plan was to make a string of months and a string of the number of days in those months and have them compare to each other. So it would go through a loop and if you typed in February it would look through the list of numbers and see that January comes before and has 31 days and would add the number of days in February it has been. For instance 22. And it would add 22 to 31 to come up with how many days it has been this year so far. So I've been trying to make that work some way but I have so far been pretty unsuccesful. Does the way I'm even thinking about making the loop make sense? Thanks! > Date: Mon, 24 Sep 2012 16:48:56 -0400 > From: d at davea.name > To: aijathompson at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] Python Assignment Question > > On 09/24/2012 03:20 PM, Aija Thompson wrote: > > Hi! > > I've been working on this question for a long time and for some reason it's just not clicking. > > I'm not sure if my loop for the question is the right one, or if I'm even on the right track. > > We're supposed to make a program that counts the number of days into the year it is if you input a date. Not including leap years. > > This is what I have so far: > > months = 'January, February, March, April, May, June, July, August, September, October, November, December'daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' #shorterMonths = 'February, April, June, September, Novmeber'#longerMonths = 'January, March, May, July, August, October, December' > > month = raw_input('Enter the month: ')day = raw_input('Enter the day: ') > > for x in month: whichMonth = months.index(x) monthNumber = daysPerMonth[whichMonth] dayYear.append(monthNumber) > > I was hoping to make a loop that would check which month it is and compare it to the second list I made with the number of days in that month. I don't know if I've made that clear to the program or not. Either way, I feel pretty lost at the moment. > > Any help would do! > > Thanks! > > > > Please don't send an html message; this is a text mailing list, and > your text is hopelessly mangled. > > For the benefit of others, I reformatted the code and enclose it here, > with tabs turned into 4 spaces. > > months = 'January, February, March, April, May, June, July, August, > September, October, November, December' > daysPerMonth = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31' > #shorterMonths = 'February, April, June, September, Novmeber' > #longerMonths = 'January, March, May, July, August, October, December' > month = raw_input('Enter the month: ') > day = raw_input('Enter the day: ') > for x in month: > print "x = ", x > whichMonth = months.index(x) > monthNumber = daysPerMonth[whichMonth] > dayYear.append(monthNumber) > > is this your first assignment? Have you worked in any other programming > language before learning Python? Are you working with CPython 2.7 ? > > Most of this code makes no sense to me at all. Why isn't months a list > of strings? Why isn't daysPerMonth a list of ints? (I'm assuming that > shorterMonths and longerMonths are vestigial code. If not, the two > spellings for November would surely cause troubles. > > Why do you define day as a string, and not an int? > > And why is the loop looping through the characters in the specified month? > > Have you tried to describe in English how to solve the problem? > > > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Sep 24 23:13:44 2012 From: d at davea.name (Dave Angel) Date: Mon, 24 Sep 2012 17:13:44 -0400 Subject: [Tutor] Python Assignment Question In-Reply-To: References: , <5060C738.7050906@davea.name> Message-ID: <5060CD08.5050408@davea.name> On 09/24/2012 04:56 PM, Aija Thompson wrote: > > Hi, By top-posting, you lose all the context. The convention is to quote those parts of the previous messages necessary to understand the context, and then add your own remarks immediately after the appropriate parts. > Yeah this is my first assignment and I've never worked on anything programming before. > I am working in Python 2.7 > The shorter and longer months thing is just a not to myself, that is why it has the hash tag before he sentence. > But my initial plan was to make a string of months Fine. Have you played with it? Try something like this to get an idea what you have: months = 'January, February, March, April, May, June, July, August, September, October, November, December' for amonth in months: print amonth See what's wrong? Can you imagine what the difference might be if it were a list of strings? Once you get that, try the same kind of experimenting with the other anomalies I pointed out. I expect you haven't gotten a feeling for what all the various native types are good for, list, string, int, float. Are you also familiar with what int() does to a string? What def functions are? I'm sorry if i seem harsh, but this seems like a tough first assignment. You have to use a dozen concepts you apparently haven't wielded before. Weren't there exercises in the chapters you've been studying? Did you try every one of them? I'm actually somewhat envious of the way people get to try out computer programs today. That wasn't an option when I started. So take advantage of it. Write tiny programs and see whether they work, then figure out why not and fix them. and a string of the number of days in those months and have them compare to each other. So it would go through a loop and if you typed in February it would look through the list of numbers and see that January comes before and has 31 days and would add the number of days in February it has been. For instance 22. And it would add 22 to 31 to come up with how many days it has been this year so far. So I've been trying to make that work some way but I have so far been pretty unsuccesful. Does the way I'm even thinking about making the loop make sense? > Thanks! > -- DaveA From gnj091405 at gmail.com Mon Sep 24 23:15:29 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Mon, 24 Sep 2012 14:15:29 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: <505FD03B.3090706@davea.name> References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: >> but now get a " x = zipfile.Zipfile(item,'r') >> AttributeError: 'module' object has no attribute 'Zipfile' " >> >> error >> >> grrrrr, this is going to send me to the funny farm! >> >> greg >> > One way to avoid the "funny farm" is to learn to use the tools that > Python provides, built-in. As soon as you get an error like that one, > add a print statement immediately before the one in error, and find the > type and attributes of the object that supposedly doesn't have the > attribute. For example, you could have added a dir(zipfile), and then > studied the one that seems to be the same as the one you tried to use. > Presumably you would have quickly discovered what Oscar pointed out. > Thank you, I have printed and added to my Python quick hints. > We all make typos, the difference is in how quickly we find and fix > them. Use the tools. > must admit, I didn't notice the typo. > -- Greg From gnj091405 at gmail.com Mon Sep 24 23:16:25 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Mon, 24 Sep 2012 14:16:25 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> Message-ID: > > Capital F. ZipFile not Zipfile. > Keyboard - Forehead - SCHMACK. (and hand/forehead smack.) DOH! Thank you. Greg From lists at beatmixed.com Mon Sep 24 23:24:53 2012 From: lists at beatmixed.com (Matt Hite) Date: Mon, 24 Sep 2012 14:24:53 -0700 Subject: [Tutor] running program in terminal In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 9:41 AM, Benjamin Fishbein wrote: > Hello. I can run programs in IDLE but when I try to do it in a terminal or with textwrangler, it usually just logs out and says it's completed, but the program hasn't been run. This is particularly so when the program uses urllib. I'm using OS X. Try adding this to the end: x = raw_input("Waiting for you to hit enter...") From oscar.j.benjamin at gmail.com Mon Sep 24 23:28:00 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 24 Sep 2012 22:28:00 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: On 24 September 2012 22:15, Gregory Lund wrote: > >> but now get a " x = zipfile.Zipfile(item,'r') > >> AttributeError: 'module' object has no attribute 'Zipfile' " > >> > >> error > >> > >> grrrrr, this is going to send me to the funny farm! > >> > >> greg > >> > > One way to avoid the "funny farm" is to learn to use the tools that > > Python provides, built-in. As soon as you get an error like that one, > > add a print statement immediately before the one in error, and find the > > type and attributes of the object that supposedly doesn't have the > > attribute. For example, you could have added a dir(zipfile), and then > > studied the one that seems to be the same as the one you tried to use. > > Presumably you would have quickly discovered what Oscar pointed out. > > > Thank you, I have printed and added to my Python quick hints. > > > We all make typos, the difference is in how quickly we find and fix > > them. Use the tools. > > > must admit, I didn't notice the typo. > No but Python did when it ran your code and it tried to tell you. The trick is to read the error message, see what line of code it occurs at and then look very closely at that line of code and the surrounding lines of code. The first thing to check for is a typo. The error message that Python gives may seem cryptic but it's actually very informative if you know how to read it. For this reason it's also more helpful to show the *verbatim* error message when posting to this (or other) lists. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Sep 24 23:53:23 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 24 Sep 2012 21:53:23 +0000 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> Message-ID: <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Note: attributions might be a bit off due to the way this was sent. Dwight Hutto wrote: > > Dwight, > > Please stop responding to Mark. His behaviour is typical schoolyard > bully, meaning he's saying things precisely because he gets a reaction > from you. He probably doesn't even realise that he's doing it > consciously, but either way the best way to deal with such behaviour > is to stop giving such a person what they want, e.g. the reaction. > So, please just **stop responding** to any of his posts > > I respond, to let him know that he just thinks I don't add context, > but lacks the ability to cheeck, that I do try to include context, but > in these question answer sessions, you should be following, the > conversation, which should put everything into context. To be fair, I do not think Mark is chastising you for context anywhere that you actually provide context; only when it is missing. I do agree it was unnecessary to remark on your use of context in one thread. > . He'll soon > grow bored and move on. If you had kept out of the conversation when > I'd originally replied to him then I'd have been able to take him to > task for his childish behaviour. As it stands now unfortunately, > Myles' thread has become a wasteland of exchanges between yourself and > him. Again: Please just stop responding to him. > > Well, It's an argument, and I won't let him win. I could stop > responding, but then he would think he had won, and do it to someone > else. Hmm, arguing on the internet. Reminds me of: http://www.systemcomic.com/2011/08/03/so-youre-mad-about-something-on-the-internet/ and http://xkcd.com/386/ > > He's wrong. He took one response out of context, and assumed that is > what I do, when usually it's just I followed the conversation for > real, and if he had, then he would know the context in which a certain > comment was made. You have forgotten context more often than "one response". I am not sure what you mean by "I followed the conversation for real..." > > Thank you sincerely, > > Walter Prins > > On Mon, Sep 24, 2012 at 3:16 PM, Mark Lawrence > wrote: > > On 24/09/2012 17:52, Walter Prins wrote: > >> > >> Mark, > >> > >> On 23 September 2012 22:53, Mark Lawrence wrote: > >>>> > >>>> Is the personal sniping really necessary? (That's a rhetorical > >>>> question, just to be clear.) > > >>> > >>> Well if Dwight insists on replying to something without quoting the > >>> context > >>> so the rest of us haven't the faintest idea what he's talking about what > >>> are > >>> we meant to do? Sadly my mind reading capabilities are quite low, I > >>> don't > >>> know about that for anyone else. > >> > >> > >> Well then tell him how to do it properly and/or provide a better > >> answer without the personal invective. No one expects you to read > >> minds obviously, but the personal attacks and sarcasm are really way > >> out of line. I can only hang my head in shame at what Myles must be > >> thinking of all this. So childish. Agreed. Wait, who is Myles? The OP? > >> > >> Walter > > He only has one conversation to prove his point on, and I made the > point of telling him I was following a short conversation(at the > time), and therefore needed no context at the time, because the OP is > following the thread for the answer, and knows the context. > > Walter's point of entry into the thread is of no concern to me, > because the OP is following the conversation. If Walter wants to know > the context, read the every post just like the OP would, because > that's who I'm responding to, not Walter. > > > Dwight Hutto refers to my family as pigs and you have a go at > > And when did I do that, please point out where I said that about your family. """> window I've just spotted a squadron of low flying pigs. A family reunion no doubt. Maybe if you could pay attention instead of picking sides you would understand the argument, and comment. """" From: http://thread.gmane.org/gmane.comp.python.tutor/77951/focus=77955 > > > downright bloody check. We're here to teach Python. If he's too thick to > > understand context he can search the web for the word or resort to a > > dictionary. > > If you're too thick to understand that sometimes it's an offhand > remark to JUST the OP, then you don't understand the context of a > tutor session in which one person asks a question, and gets responses. True, but that is not really helpful to other people who may be reading and curious or able to offer a correction/comment. Not to mention anyone in need of future help. Though I have noted that you do attempt to place context sometimes and I appreciate that. > > You also seem to have missed lots of other conversations, where my > replies are in line. > > You want an argument, and in this case you lose, because you couldn't > understand the context of my remark, because you think that every time > I respond it's without inline responses. > > You don't know enough about me to say I always quote out of context, > and I can provide the evidence that I do. Activate your super powers! ????????BA This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue Sep 25 01:09:43 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Sep 2012 00:09:43 +0100 Subject: [Tutor] running program in terminal In-Reply-To: References: Message-ID: On 24/09/12 17:41, Benjamin Fishbein wrote: > Hello. I can run programs in IDLE but when I try to do it in a terminal or with textwrangler, it usually just logs out and says it's completed, but the program hasn't been run. This is particularly so when the program uses urllib. I'm using OS X. > > logout > > [Process completed] > > That's what it prints. > Any idea what to do? Can you start up a terminal window then try to run your program and finally paste the whole session into a mail and post it here? That should help. If your program is complex try a simple one like: print ('Hello world') input('Hit enter to quit...') -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 25 01:13:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Sep 2012 00:13:09 +0100 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: On 24/09/12 20:13, Aija Thompson wrote: > Hi! > > So I've been working on this question for hours! And Python keeps giving > me an error saying that my syntax for BMI is wrong. I really can't > understand why. So send us the full error text not a summary. If Python reports a syntax its usually recorded at the point immediately after the error so you may have to look at the line before. > So this is what I have so far: > > w = raw_input('Please give your weight in lbs: ') > h = raw_input('Now your height in feet and inches: ') > h. split("'") > ft, inches = h. split("'") > h_sum = float(12*int(ft)) + (int(inches.strip('"')) count the parens in the last expression... > BMI = float(703*w)/float(h_sum*h_sum) > print 'Your BMI is: ', BMI HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dwightdhutto at gmail.com Tue Sep 25 01:25:07 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 24 Sep 2012 19:25:07 -0400 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 7:13 PM, Alan Gauld wrote: > On 24/09/12 20:13, Aija Thompson wrote: >> >> Hi! >> >> So I've been working on this question for hours! And Python keeps giving >> me an error saying that my syntax for BMI is wrong. I really can't >> understand why. > > I'd suggest an editor, or editor option that highlights the end of certain code separators like brackets/parenthesis > > So send us the full error text not a summary. > > If Python reports a syntax its usually recorded at the point immediately > after the error so you may have to look at the line before. > >> So this is what I have so far: >> >> w = raw_input('Please give your weight in lbs: ') >> h = raw_input('Now your height in feet and inches: ') >> h. split("'") >> ft, inches = h. split("'") >> h_sum = float(12*int(ft)) + (int(inches.strip('"')) > > > count the parens in the last expression... > >> BMI = float(703*w)/float(h_sum*h_sum) >> print 'Your BMI is: ', BMI > > > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Tue Sep 25 01:28:33 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 24 Sep 2012 19:28:33 -0400 Subject: [Tutor] BMI Question In-Reply-To: References: Message-ID: On Mon, Sep 24, 2012 at 7:25 PM, Dwight Hutto wrote: > On Mon, Sep 24, 2012 at 7:13 PM, Alan Gauld wrote: >> On 24/09/12 20:13, Aija Thompson wrote: >>> >>> Hi! >>> >>> So I've been working on this question for hours! And Python keeps giving >>> me an error saying that my syntax for BMI is wrong. I really can't >>> understand why. >> >> > I'd suggest an editor, or editor option that highlights the end of > certain code separators like brackets/parenthesis > >> >> So send us the full error text not a summary. >> >> If Python reports a syntax its usually recorded at the point immediately >> after the error so you may have to look at the line before. >> >>> So this is what I have so far: >>> >>> w = raw_input('Please give your weight in lbs: ') >>> h = raw_input('Now your height in feet and inches: ') >>> h. split("'") >>> ft, inches = h. split("'") >>> h_sum = float(12*int(ft)) + (int(inches.strip('"')) >> >> >> count the parens in the last expression... >> Proper netiquette suggests I place this here: I'd suggest an editor, or editor option that highlights the end of certain code separators like brackets/parenthesis so you can see the in depth parameters placed into code. >>> BMI = float(703*w)/float(h_sum*h_sum) >>> print 'Your BMI is: ', BMI > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From bfishbein79 at gmail.com Tue Sep 25 01:31:49 2012 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 24 Sep 2012 18:31:49 -0500 Subject: [Tutor] running program in terminal In-Reply-To: References: Message-ID: <0BC523EB-926F-46B5-AF30-2A2DDA3CCBAC@gmail.com> > > Can you start up a terminal window then try to run your program and finally paste the whole session into a mail and post it here? > > That should help. > If your program is complex try a simple one like: > > print ('Hello world') > input('Hit enter to quit...') Last login: Mon Sep 24 18:27:48 on ttys000 Benjamins-MacBook-Air:~ bfishbein$ cd '/Users/bfishbein/Documents/Python in Use/' && '/usr/local/bin/pythonw' '/Users/bfishbein/Documents/Python in Use/BB.py' && echo Exit status: $? && exit 1 put in the text input Textbooks.com - Your Search Results for Buyback From gnj091405 at gmail.com Tue Sep 25 01:33:36 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Mon, 24 Sep 2012 16:33:36 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: > No but Python did when it ran your code and it tried to tell you. The trick > is to read the error message, see what line of code it occurs at and then > look very closely at that line of code and the surrounding lines of code. > The first thing to check for is a typo. To be honest, I did check for typos, a misplaced period, etc., but didn't notice it, I even compared it with the similar line above, but didn't notice the 'F'. (Truth Hurts) > > The error message that Python gives may seem cryptic but it's actually very > informative if you know how to read it. For this reason it's also more > helpful to show the *verbatim* error message when posting to this (or other) > lists. > I will show the verbatim error message from now on, thank you for suggesting it! , speaking of which: This is my code, as modified based on all the great help thus far. (again, I need a stand alone .py file for my purposes and need to use Python 2.6 because it's the version that works with my GIS application (Esri's ArcGIS). import os, os.path, zipfile, arcpy in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip' outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" z = zipfile.ZipFile(in_Zip,'r') z.extractall(outDir) zipContents = z.namelist() print zipContents z.close() for item in zipContents: if item.endswith('.zip'): x = zipfile.ZipFile(item,'r') x.extractall() x.close() for the record, I print 'zipContents' to help me figure out how to 'get into' the first folder of the extracted zip which is never a zip folder, but a non-zipped folder, that holds (usually) 1 or more .zip files (folders that are zipped) This is the way I receive the data from the Learning Management System LMS). The initial zip (2012-09-18 Lab_2.zip) is created by the LMS, and actually the internal folders (aforker, allisw99, etc.) are also created by the LMS (its' how the LMS sorts the individual student folders/upload using their user name. my results and error of the above code is listed below. IDLE 2.6.5 >>> ================================ RESTART ================================ >>> ['Lab_2/aforker/', 'Lab_2/aforker/aforker_Lab2.zip', 'Lab_2/allisw99/', 'Lab_2/allisw99/allisw99_Lab2.zip', 'Lab_2/allisw99/allisw99_Lab2_Bonus.pdf', 'Lab_2/allisw992/', 'Lab_2/allisw992/allisw99_Lab2_Bonus.pdf', 'Lab_2/btaylor7/', 'Lab_2/btaylor7/2nd_btaylor7_Lab2.zip', 'Lab_2/btaylor7/btaylor7_Lab2.zip', 'Lab_2/'] Traceback (most recent call last): File "D:/D_Drive_Documents/Scripts/Unzip_a_zip_of_zips/Scripts/unzip_a_zip_of_zips_rewrite_shortest_of_the_shorts2.py", line 18, in x = zipfile.ZipFile(item,'r') File "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 683, in __init__ self.fp = open(file, modeDict[mode]) IOError: [Errno 2] No such file or directory: 'Lab_2/aforker/aforker_Lab2.zip' >>> Near as I can tell, I got rid of the permissions error, the ZipFile error with the missing capital 'F' Now I need to 'get into' the non zipped folder of each student and unzip any and all zips that are inside of it. Thoughts? Thanks again Oscar and Dave for sticking with me and not throwing in the towel on my rookie errors! Greg From alan.gauld at btinternet.com Tue Sep 25 02:02:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Sep 2012 01:02:05 +0100 Subject: [Tutor] running program in terminal In-Reply-To: <0BC523EB-926F-46B5-AF30-2A2DDA3CCBAC@gmail.com> References: <0BC523EB-926F-46B5-AF30-2A2DDA3CCBAC@gmail.com> Message-ID: On 25/09/12 00:31, Benjamin Fishbein wrote: > Last login: Mon Sep 24 18:27:48 on ttys000 > Benjamins-MacBook-Air:~ bfishbein$ cd > '/Users/bfishbein/Documents/Python in Use/' && > '/usr/local/bin/pythonw' '/Users/bfishbein/Documents/Python in > Use/BB.py' && echo Exit status: $? && exit 1 When debugging simplify the code. In this case break it into individual commands so you can see the effect of each one and see where the errors are coming from. However.... > put in the text input > > href='http://www.textbooks.com/apple-touch-icon.png' /> rel='apple-touch-icon-precomposed' sizes='114x114' href='http:Exit > status: 0 > logout > > [Process completed] This looks to be doing exactly what you asked it to. So the error, if any such exists, seems to be in your Python code. Or maybe its just finished processing earlier than you expected (due to a data issue maybe?) But without sight of the code its hard to say... > launcher. But for the programs like this one that take large chunks of > raw input and then parse through them, it stops after a dozen lines or > so...it doesn't even finish pasting the text into the terminal. When you say it 'stops' what exactly do you mean? The above output suggests that far from stopping the program terminates successfully (exit status 0). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Tue Sep 25 02:20:50 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 25 Sep 2012 01:20:50 +0100 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: On 25 September 2012 00:33, Gregory Lund wrote: > > z.extractall(outDir) > > zipContents = z.namelist() > print zipContents > z.close() > > for item in zipContents: > if item.endswith('.zip'): > x = zipfile.ZipFile(item,'r') > x.extractall() > x.close() > > Traceback (most recent call last): > File > "D:/D_Drive_Documents/Scripts/Unzip_a_zip_of_zips/Scripts/unzip_a_zip_of_zips_rewrite_shortest_of_the_shorts2.py", > line 18, in > x = zipfile.ZipFile(item,'r') > File "C:\Python26\ArcGIS10.0\lib\zipfile.py", line 683, in __init__ > self.fp = open(file, modeDict[mode]) > IOError: [Errno 2] No such file or directory: > 'Lab_2/aforker/aforker_Lab2.zip' > >>> > > Near as I can tell, I got rid of the permissions error, the ZipFile > error with the missing capital 'F' > Now I need to 'get into' the non zipped folder of each student and > unzip any and all zips that are inside of it. > The error message says 'No such file or directory'. That means that when Python tries to open a file with the name you gave it can't find a file that has that name. In this case I suspect the problem is that you need to give the full path to each file i.e. instead of 'Lab_2/aforker/aforker_Lab2.zip' you need to give 'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\Lab_2\aforker\aforker_Lab2.zip' You can create the full path with: import os.path # Put this at the top of your file for item in zipContents: if item.endswith('.zip'): # Combine the base folder name with the subpath to the zip file fullpath = os.path.join(outDir, item) x = zipfile.ZipFile(fullpath,'r') I just googled to find you a page explaining absolute paths and, by chance, came up with this from the ArcGIS documentation: http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Pathnames%20explained%3A%20Absolute%2C%20relative%2C%20UNC%2C%20and%20URL Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnj091405 at gmail.com Tue Sep 25 04:24:30 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Mon, 24 Sep 2012 19:24:30 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: >> Near as I can tell, I got rid of the permissions error, the ZipFile >> error with the missing capital 'F' >> Now I need to 'get into' the non zipped folder of each student and >> unzip any and all zips that are inside of it. > > > The error message says 'No such file or directory'. That means that when > Python tries to open a file with the name you gave it can't find a file that > has that name. In this case I suspect the problem is that you need to give > the full path to each file i.e. instead of > 'Lab_2/aforker/aforker_Lab2.zip' full code is now: import os, os.path, zipfile, arcpy in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip' outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" z = zipfile.ZipFile(in_Zip,'r') z.extractall(outDir) zipContents = z.namelist() print zipContents z.close() for item in zipContents: if item.endswith('.zip'): # Combine the base folder name with the subpath to the zip file fullpath = os.path.join(outDir, item) x = zipfile.ZipFile(fullpath,'a') x.extractall() x.close() NO errors! yea! But, it's (I'm) still just extracting the first zip, not the zipfiles within the Lab_2\aforker, Lab_2\allisw99 folders. however, I used my brain (no comments!) and figured out that while it's not extracting the info to the folders I want (the Lab_2\aforker, Lab_2\allisw99 etc. folder, it's extracting them to the location in which my script is stored. I kept looking at it thinking 'OK, it didn't come up with an error, but it's 'not' extracting, but it should be.... then I realized that I didn't specify the folder to which I want it extracted. Ta-da, that's why it's going back to where the script is stored. So... I tried to use: x.extractall(fullpath) but that of course gave me errors because 'fullpath' is the path of the file. I need to figure out how to just list the respective Lab_2\aforker, Lab_2\allisw99 folders. Thus far, I have not had any luck. Does python have a way to go back to the relative folder where the zip is located? > I just googled to find you a page explaining absolute paths and, by chance, > came up with this from the ArcGIS documentation: > http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Pathnames%20explained%3A%20Absolute%2C%20relative%2C%20UNC%2C%20and%20URL Good find, It's like pulling teeth to explain paths/directories to my students. The relative vs. absolute paths is one of their first obstacles to learning, yet really it's a simple check box in ArcGIS that is NOT a default, and resets each night in the computer lab. I am going to use that link you provided, tomorrow, the first day of GIS311! Greg From __peter__ at web.de Tue Sep 25 11:26:03 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Sep 2012 11:26:03 +0200 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: Gregory Lund wrote: > if item.endswith('.zip'): > # Combine the base folder name with the subpath to the zip file > fullpath = os.path.join(outDir, item) > x = zipfile.ZipFile(fullpath,'a') Why did you change file mode to "a"? > x.extractall() > x.close() > I tried to use: > x.extractall(fullpath) but that of course gave me errors because > 'fullpath' is the path of the file. > I need to figure out how to just list the respective Lab_2\aforker, > Lab_2\allisw99 folders. > > Thus far, I have not had any luck. > Does python have a way to go back to the relative folder where the zip > is located? dest_path = os.path.dirname(fullpath) x.extractall(dest_path) From rdmoores at gmail.com Tue Sep 25 13:55:47 2012 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 25 Sep 2012 04:55:47 -0700 Subject: [Tutor] Usefulness of BIFs all() and any()? Message-ID: I was just perusing the Built-in Functions of Python 3.2 (< http://docs.python.org/py3k/library/functions.html>) and was wondering where would one ever use any() or all(). all(iterable) Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to: def all(iterable): for element in iterable: if not element: return False return True any(iterable) Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: def any(iterable): for element in iterable: if element: return True return False Given a = [0, 1, 2, 3], >>> all(a) False >>> any(a) True But so what? Could I get some better examples? And why >>> all([]) True >>> any([]) False Thanks, Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Sep 25 14:24:20 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 25 Sep 2012 14:24:20 +0200 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: References: Message-ID: On Tue, Sep 25, 2012 at 1:55 PM, Richard D. Moores wrote: > I was just perusing the Built-in Functions of Python 3.2 (< > http://docs.python.org/py3k/library/functions.html>) and was wondering > where would one ever use any() or all(). > > But so what? Could I get some better examples? > I frequently use any() or all() in combination with a generator expression to check for a certain condition over a list of elements. Let's say, for example, I want to make sure all files I used are closed at the end of a function (or perhaps a unit test?) assert all(f.closed for f in open_files) probably not the *most* useful example of that, but I'm sure you understand the principle. It's useful when you need to check if all() or any() of an iterator pass a certain condition. > > And why > >>> all([]) > True > >>> any([]) > False > People often wonder over this one. any([]) should logically be False, because it is like asking the question "is there any member in this iterable that is True?" Obviously, there is not, since the iterator is empty. all([]) is True by the principle of vacuous truth: http://en.wikipedia.org/wiki/Vacuous_truth The principle, though somewhat intuitive, has a strong mathematical basis. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Sep 25 14:33:22 2012 From: d at davea.name (Dave Angel) Date: Tue, 25 Sep 2012 08:33:22 -0400 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: References: Message-ID: <5061A492.2080100@davea.name> On 09/25/2012 07:55 AM, Richard D. Moores wrote: > > > And why >>>> all([]) > True >>>> any([]) > False > > Same problem as calling sum() with an empty list. What value should it have? Clearly, it should return its 'start' parameter, which defaults to zero. Well the all() has a start value of True, and ands that with each element of the iterable till one of them ends up with false. Similarly, the any() has a start value of False. -- DaveA From steve at pearwood.info Tue Sep 25 15:41:53 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Sep 2012 23:41:53 +1000 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: References: Message-ID: <5061B4A1.4040304@pearwood.info> On 25/09/12 21:55, Richard D. Moores wrote: > I was just perusing the Built-in Functions of Python 3.2 (< > http://docs.python.org/py3k/library/functions.html>) and was wondering > where would one ever use any() or all(). Both are very useful. They are especially useful for validating data, or for interactive use. For instance, to check that a list of numbers are all positive: if all(x > 0 for x in numbers): ... and then go on to process the numbers. There are over a dozen examples of any or all in the Python standard library. (There would be more, but a lot of the std lib pre-dates the two functions.) They tend to be used to check the state of some collection of values, and return a flag. For example: return any(key in m for m in self.maps) checks whether a key appears in a collection of maps. Otherwise that one line would be written as: for m in self.maps: if key in m: return True return False Notice the pattern there is that if the collection of maps is empty, then you return False. And sure enough, any([]) returns False. In an example from my own code, I have a pool of threads doing work, and loop until all of the threads have finished: while any(t.isAlive() for t in threads): ... Another example, I check that a list of objects are all integers: if not all(isinstance(i, int) for i in key): ... Basically, the functions all and any should be used whenever you need to check that a condition holds for ALL the values, or for ANY value, in a collection of values. If they sound like trivial functions, well, yes, they are trivial like a hammer is trivial. It's just a lump of metal used for bashing in nails. > And why >>>> all([]) > True >>>> any([]) > False Because they match the most useful and common patterns for testing that some condition holds. Normally we want to test: * there is at least one value where this condition holds (use any) rather than: * there are no values at all, or there is at least one value... Imagine the set of living people with no heads. If any of them are called "Steve", you pay me a dollar. Do you owe me anything? The case for all([]) returning True is a bit less obvious. One of the first things I did in my own code was write an alternative version of all: def all2(iterable): magic = object() element = magic for element in iterable: if not element: return False return element is not magic but I've never used it. See also: http://en.wikipedia.org/wiki/Vacuous_truth -- Steven From gnj091405 at gmail.com Tue Sep 25 16:52:04 2012 From: gnj091405 at gmail.com (Gregory Lund) Date: Tue, 25 Sep 2012 07:52:04 -0700 Subject: [Tutor] Unzipping a Zip of folders that have zips within them that I'd like to unzip all at once. In-Reply-To: References: <5059EC54.6040804@pearwood.info> <505FD03B.3090706@davea.name> Message-ID: > Why did you change file mode to "a"? I was trying different things and forgot to change it back before I cut/pasted. > > > dest_path = os.path.dirname(fullpath) > x.extractall(dest_path) > Ding ding ding, winner winner chicken dinner! It's working! Final .py stand alone code is: import os, os.path, zipfile, arcpy in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip' outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" z = zipfile.ZipFile(in_Zip,'r') z.extractall(outDir) zipContents = z.namelist() z.close() for item in zipContents: if item.endswith('.zip'): # Combine the base folder name with the subpath to the zip file fullpath = os.path.join(outDir, item) x = zipfile.ZipFile(fullpath,'r') dest_path = os.path.dirname(fullpath) x.extractall(dest_path) x.close() and... the final code that I'll use in my ArcGIS script/tool is: (I kept the old code with absolute paths to help anyone who wanted to use this on their zip of zips (with it commented out and my ArcGIS requirements immediately below.) import os, os.path, zipfile, arcpy #in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 Lab_2.zip' in_Zip = arcpy.GetParameterAsText(0) #outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" outDir = os.getcwd() z = zipfile.ZipFile(in_Zip,'r') z.extractall(outDir) zipContents = z.namelist() z.close() for item in zipContents: if item.endswith('.zip'): # Combine the base folder name with the subpath to the zip file fullpath = os.path.join(outDir, item) x = zipfile.ZipFile(fullpath,'r') dest_path = os.path.dirname(fullpath) x.extractall(dest_path) x.close() -------------------------------- Words/pixels can not express how grateful I am to everyone that pitched in and helped guide me through this seemingly simple task. The code works & the Esri ArcGIS tool works! It's not really 'my' code or tool: the credit goes to Peter, Oscar, Dave, Stephen and others for their/your comments, debugging, code suggestions, and patience. I also appreciate the fact that someone didn't just give me the full code, struggling through googling etc. helped me learn. I'm still a rookie/neophyte, but a very happy one this morning! Aug. 7 to now, thanks for all the help! Thanks again! Regards, Greg Lund PS, but aren't you all going to miss my daily stupid questions? (ok, maybe not!). From steve at pearwood.info Tue Sep 25 17:17:39 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Sep 2012 01:17:39 +1000 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: <5061B4A1.4040304@pearwood.info> References: <5061B4A1.4040304@pearwood.info> Message-ID: <5061CB13.2030007@pearwood.info> On 25/09/12 23:41, Steven D'Aprano wrote: > See also: > > http://en.wikipedia.org/wiki/Vacuous_truth And another useful link about vacuous truth: http://www.dailykos.com/story/2012/06/16/1087320/-Vacuous-truth -- Steven From rdmoores at gmail.com Tue Sep 25 18:03:01 2012 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 25 Sep 2012 09:03:01 -0700 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: <5061CB13.2030007@pearwood.info> References: <5061B4A1.4040304@pearwood.info> <5061CB13.2030007@pearwood.info> Message-ID: Thanks for the great instruction, Tutors. I'd been working over a script of mine that factors integers. I noticed that if all the prime factors of n are the same, then if f is one of the factors and p is the number of factors, n = f ^ p. I thought of using all() or any(), but couldn't see how to do so. The only code I could think of for this was: n = 64 factors = [2, 2, 2, 2, 2, 2] first_factor = factors[0] power = len(factors) all_equal = True for factor in factors: if factor != first_factor: all_equal = False break if all_equal == True: power = len(factors) print(n, "=", first_factor, "^", power) But after asking my question I've changed it to: n = 64 factors = [2, 2, 2, 2, 2, 2] first_factor = factors[0] power = len(factors) if all(factor == first_factor for factor in factors): print(n, "=", first_factor, "^", power) which prints, 64 = 2 ^ 6 Dick -------------- next part -------------- An HTML attachment was scrubbed... URL: From afzal.pcc at gmail.com Tue Sep 25 18:06:42 2012 From: afzal.pcc at gmail.com (Afzal Hossain) Date: Tue, 25 Sep 2012 22:06:42 +0600 Subject: [Tutor] Tutor Digest, Vol 103, Issue 124 In-Reply-To: References: Message-ID: hi i am trying to install python3.1.5 tgz in windows 7 but not getting exe file for installing.can u help me for this On 9/25/12, 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 > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Usefulness of BIFs all() and any()? (Richard D. Moores) > 2. Re: Usefulness of BIFs all() and any()? (Hugo Arts) > 3. Re: Usefulness of BIFs all() and any()? (Dave Angel) > 4. Re: Usefulness of BIFs all() and any()? (Steven D'Aprano) > 5. Re: Unzipping a Zip of folders that have zips within them > that I'd like to unzip all at once. (Gregory Lund) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 25 Sep 2012 04:55:47 -0700 > From: "Richard D. Moores" > To: Tutor List > Subject: [Tutor] Usefulness of BIFs all() and any()? > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > I was just perusing the Built-in Functions of Python 3.2 (< > http://docs.python.org/py3k/library/functions.html>) and was wondering > where would one ever use any() or all(). > > all(iterable) > Return True if all elements of the iterable are true (or if the iterable is > empty). Equivalent to: > > def all(iterable): > for element in iterable: > if not element: > return False > return True > > any(iterable) > Return True if any element of the iterable is true. If the iterable is > empty, return False. Equivalent to: > > def any(iterable): > for element in iterable: > if element: > return True > return False > > Given a = [0, 1, 2, 3], > >>>> all(a) > False >>>> any(a) > True > > But so what? Could I get some better examples? > > And why >>>> all([]) > True >>>> any([]) > False > > Thanks, > > Dick Moores > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 2 > Date: Tue, 25 Sep 2012 14:24:20 +0200 > From: Hugo Arts > To: "Richard D. Moores" > Cc: Tutor List > Subject: Re: [Tutor] Usefulness of BIFs all() and any()? > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > On Tue, Sep 25, 2012 at 1:55 PM, Richard D. Moores > wrote: > >> I was just perusing the Built-in Functions of Python 3.2 (< >> http://docs.python.org/py3k/library/functions.html>) and was wondering >> where would one ever use any() or all(). >> >> But so what? Could I get some better examples? >> > > I frequently use any() or all() in combination with a generator expression > to check for a certain condition over a list of elements. Let's say, for > example, I want to make sure all files I used are closed at the end of a > function (or perhaps a unit test?) > > assert all(f.closed for f in open_files) > > probably not the *most* useful example of that, but I'm sure you understand > the principle. It's useful when you need to check if all() or any() of an > iterator pass a certain condition. > > >> >> And why >> >>> all([]) >> True >> >>> any([]) >> False >> > > People often wonder over this one. any([]) should logically be False, > because it is like asking the question "is there any member in this > iterable that is True?" Obviously, there is not, since the iterator is > empty. all([]) is True by the principle of vacuous truth: > > http://en.wikipedia.org/wiki/Vacuous_truth > > The principle, though somewhat intuitive, has a strong mathematical basis. > > HTH, > Hugo > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 3 > Date: Tue, 25 Sep 2012 08:33:22 -0400 > From: Dave Angel > To: "Richard D. Moores" > Cc: Tutor List > Subject: Re: [Tutor] Usefulness of BIFs all() and any()? > Message-ID: <5061A492.2080100 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1 > > On 09/25/2012 07:55 AM, Richard D. Moores wrote: >> >> >> And why >>>>> all([]) >> True >>>>> any([]) >> False >> >> > > Same problem as calling sum() with an empty list. What value should it > have? Clearly, it should return its 'start' parameter, which defaults > to zero. > > Well the all() has a start value of True, and ands that with each > element of the iterable till one of them ends up with false. Similarly, > the any() has a start value of False. > > > > -- > > DaveA > > > > ------------------------------ > > Message: 4 > Date: Tue, 25 Sep 2012 23:41:53 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Usefulness of BIFs all() and any()? > Message-ID: <5061B4A1.4040304 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 25/09/12 21:55, Richard D. Moores wrote: >> I was just perusing the Built-in Functions of Python 3.2 (< >> http://docs.python.org/py3k/library/functions.html>) and was wondering >> where would one ever use any() or all(). > > Both are very useful. They are especially useful for validating data, or > for interactive use. For instance, to check that a list of numbers are > all positive: > > if all(x > 0 for x in numbers): ... > > and then go on to process the numbers. > > There are over a dozen examples of any or all in the Python standard > library. (There would be more, but a lot of the std lib pre-dates the two > functions.) They tend to be used to check the state of some collection of > values, and return a flag. For example: > > return any(key in m for m in self.maps) > > checks whether a key appears in a collection of maps. Otherwise that one > line would be written as: > > for m in self.maps: > if key in m: > return True > return False > > > Notice the pattern there is that if the collection of maps is empty, then > you return False. And sure enough, any([]) returns False. > > In an example from my own code, I have a pool of threads doing work, and > loop until all of the threads have finished: > > while any(t.isAlive() for t in threads): ... > > > Another example, I check that a list of objects are all integers: > > if not all(isinstance(i, int) for i in key): ... > > > Basically, the functions all and any should be used whenever you need to > check that a condition holds for ALL the values, or for ANY value, in a > collection of values. If they sound like trivial functions, well, yes, > they are trivial like a hammer is trivial. It's just a lump of metal used > for bashing in nails. > > >> And why >>>>> all([]) >> True >>>>> any([]) >> False > > Because they match the most useful and common patterns for testing that > some condition holds. Normally we want to test: > > * there is at least one value where this condition holds (use any) > > rather than: > > * there are no values at all, or there is at least one value... > > Imagine the set of living people with no heads. If any of them are called > "Steve", you pay me a dollar. Do you owe me anything? > > The case for all([]) returning True is a bit less obvious. One of the first > things I did in my own code was write an alternative version of all: > > def all2(iterable): > magic = object() > element = magic > for element in iterable: > if not element: > return False > return element is not magic > > > but I've never used it. > > See also: > > http://en.wikipedia.org/wiki/Vacuous_truth > > > > > -- > Steven > > > ------------------------------ > > Message: 5 > Date: Tue, 25 Sep 2012 07:52:04 -0700 > From: Gregory Lund > To: Peter Otten <__peter__ at web.de>, Oscar Benjamin > > Cc: tutor at python.org > Subject: Re: [Tutor] Unzipping a Zip of folders that have zips within > them that I'd like to unzip all at once. > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > >> Why did you change file mode to "a"? > I was trying different things and forgot to change it back before I > cut/pasted. >> > > >> >> dest_path = os.path.dirname(fullpath) >> x.extractall(dest_path) >> > Ding ding ding, winner winner chicken dinner! > It's working! > Final .py stand alone code is: > > import os, os.path, zipfile, arcpy > > in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 > Lab_2.zip' > > outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" > > z = zipfile.ZipFile(in_Zip,'r') > > z.extractall(outDir) > > zipContents = z.namelist() > z.close() > > for item in zipContents: > if item.endswith('.zip'): > # Combine the base folder name with the subpath to the zip file > fullpath = os.path.join(outDir, item) > x = zipfile.ZipFile(fullpath,'r') > dest_path = os.path.dirname(fullpath) > x.extractall(dest_path) > x.close() > > and... the final code that I'll use in my ArcGIS script/tool is: > (I kept the old code with absolute paths to help anyone who wanted to > use this on their zip of zips (with it commented out and my ArcGIS > requirements immediately below.) > > > import os, os.path, zipfile, arcpy > > #in_Zip = r'D:\D_Drive_Documents\Student_Work_Sample_usecopy1\2012-09-18 > Lab_2.zip' > in_Zip = arcpy.GetParameterAsText(0) > > #outDir = r"D:\D_Drive_Documents\Student_Work_Sample_usecopy1" > outDir = os.getcwd() > > z = zipfile.ZipFile(in_Zip,'r') > > z.extractall(outDir) > > zipContents = z.namelist() > z.close() > > for item in zipContents: > if item.endswith('.zip'): > # Combine the base folder name with the subpath to the zip file > fullpath = os.path.join(outDir, item) > x = zipfile.ZipFile(fullpath,'r') > dest_path = os.path.dirname(fullpath) > x.extractall(dest_path) > x.close() > > -------------------------------- > Words/pixels can not express how grateful I am to everyone that > pitched in and helped guide me through this seemingly simple task. > The code works & the Esri ArcGIS tool works! > > It's not really 'my' code or tool: > the credit goes to Peter, Oscar, Dave, Stephen and others for > their/your comments, debugging, code suggestions, and patience. > > I also appreciate the fact that someone didn't just give me the full > code, struggling through googling etc. helped me learn. > I'm still a rookie/neophyte, but a very happy one this morning! > Aug. 7 to now, thanks for all the help! > > Thanks again! > > Regards, > Greg Lund > > PS, but aren't you all going to miss my daily stupid questions? (ok, > maybe not!). > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 103, Issue 124 > *************************************** > -- afzal From rdmoores at gmail.com Tue Sep 25 18:11:24 2012 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 25 Sep 2012 09:11:24 -0700 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: <5061B4A1.4040304@pearwood.info> References: <5061B4A1.4040304@pearwood.info> Message-ID: On Tue, Sep 25, 2012 at 6:41 AM, Steven D'Aprano wrote: > There are over a dozen examples of any or all in the Python standard > library. How could I have gone about finding these examples? I tried searching the docs on any and all, but found them only in the BIF section, . Dick From steve at pearwood.info Tue Sep 25 18:52:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Sep 2012 02:52:06 +1000 Subject: [Tutor] Usefulness of BIFs all() and any()? In-Reply-To: References: <5061B4A1.4040304@pearwood.info> Message-ID: <5061E136.7020105@pearwood.info> On 26/09/12 02:11, Richard D. Moores wrote: > On Tue, Sep 25, 2012 at 6:41 AM, Steven D'Aprano wrote: > >> There are over a dozen examples of any or all in the Python standard >> library. > > How could I have gone about finding these examples? I tried searching > the docs on any and all, but found them only in the BIF section, > . I used the Linux tools on my PC to search the library. (Oooh, I'm in trouble now... I called them *Linux* tools instead of GNU tools) *half a smiley* At a bash prompt, I did: cd /usr/local/lib/python3.2 grep " all[(]" *.py grep " any[(]" *.py Whatever your operating system is, find your Python installation, and search the .py files. You can also try these: http://code.google.com/codesearch http://www.koders.com/ -- Steven From emile at fenx.com Tue Sep 25 19:22:32 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Sep 2012 10:22:32 -0700 Subject: [Tutor] Tutor Digest, Vol 103, Issue 124 In-Reply-To: References: Message-ID: On 9/25/2012 9:06 AM Afzal Hossain said... > hi i am trying to install python3.1.5 tgz in windows 7 but not getting > exe file for installing.can u help me for this > > On 9/25/12, tutor-request at python.org wrote: If you're just starting out, save yourself some headache and use the ActiveState distribution. See http://www.activestate.com/activepython/downloads Emile From steve at pearwood.info Tue Sep 25 19:30:20 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Sep 2012 03:30:20 +1000 Subject: [Tutor] Tutor Digest, Vol 103, Issue 124 In-Reply-To: References: Message-ID: <5061EA2C.7050100@pearwood.info> On 26/09/12 02:06, Afzal Hossain wrote: > hi i am trying to install python3.1.5 tgz in windows 7 but not getting > exe file for installing.can u help me for this Hello and welcome! Four comments: Firstly, DO NOT reply to posts to start a new question. Always create a fresh new email, not a reply, to start a new discussion. Secondly, when sending an email, ALWAYS make sure the subject line is relevant and useful. "Re: [Tutor] Tutor Digest, Vol 103, Issue 124" is not relevant and not useful. Thirdly, if you reply to an email, ALWAYS trim out the text that is not relevant to your question. In this case, your post included copies of five emails we have already seen, nearly 400 lines of pointless text. We are volunteers here, we are not paid, and if you take the time to write good, careful emails, we are much more likely to take the time to give good, useful answers. If you don't, we are more likely to reply in kind with lazy, thoughtless answers -- or no answer at all. Finally, is there a reason you are using Python 3.1.5? That is an old version. The current version is Python 3.2, and the Windows installers are here: http://www.python.org/getit/releases/3.2.3/ Make sure you pick the right Windows installer for your system. Only use the x86-64 version if you have 64-bit Windows. If you don't need a production-stable version, I recommend you use the latest beta version: http://www.python.org/getit/releases/3.3.0 If you really need version 3.1.5, you will find the source code here: http://www.python.org/getit/releases/3.1.5 There is no exe file because it is source-only. You will need a C compiler to build it. Good luck! -- Steven From asabatgirl at hotmail.com Wed Sep 26 03:20:55 2012 From: asabatgirl at hotmail.com (Asmaa) Date: Wed, 26 Sep 2012 01:20:55 +0000 (UTC) Subject: [Tutor] Converting a real map to a dictionary Message-ID: Hello, I wonder if there is possibility to convert a map to a dictionary in python. My concern is getting the number of houses for specific area to return the coordination of the houses in this area. I can see that there are some useful codes to convert an address to its latitude and longitude (py-googlemaps.sourceforge.net) But I want to make a small network design on a real area, so I am looking for a way to extract the available houses for this area using a google map or something! Is this possible? It is a small design, but need to include some real data here, what are my options? Thanks. From fomcl at yahoo.com Wed Sep 26 09:56:33 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 26 Sep 2012 00:56:33 -0700 (PDT) Subject: [Tutor] Borg di borg di borg (or: Swedish chef) In-Reply-To: References: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: <1348646193.41386.YahooMailNeo@web110707.mail.gq1.yahoo.com> ---- Original Message ----- > From: eryksun > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Monday, September 24, 2012 7:01 PM > Subject: Re: [Tutor] Borg di borg di borg (or: Swedish chef) > > On Mon, Sep 24, 2012 at 6:02 AM, Albert-Jan Roskam > wrote: >> >> I have three classes, Generic, Test and Test2. Generic contains a load >> method that loads a file. This may only be done once, as a >> file_read_open error is returned if the file is open already and an >> attempt is made to re-open it. The file may be opened from Test or Test2. > > What's the context here? Is "file_read_open error" an error code > returned by a library? If so, I'd pass it on by raising an exception > instead of masking the error. Hi, sorry for the late reply. Yes, this is an error by a library. Good point. I made an error class and now check all error codes and raise an error if these are unequal to 0. > As to the Borg pattern, it seems to me you don't actually need a > 'Borg' base class. But if you do, then you probably also want to > override _state with a new dict for each subclass. You can do this > automatically with a custom descriptor, a metaclass, or even a simple > property like the following: > > ? ? class Borg(object): > ? ? ? ? _all_state = {} > > ? ? ? ? def __init__(self): > ? ? ? ? ? ? self.__dict__ = self._state > > ? ? ? ? @property > ? ? ? ? def _state(self): > ? ? ? ? ? ? return self._all_state.setdefault(self.__class__, {}) > > > ? ? class Generic(Borg): > > ? ? ? ? def __init__(self): > ? ? ? ? ? ? super(Generic, self).__init__() > ? ? ? ? ? ? self.loaded = None > > ? ? ? ? def load(self, filename): > ? ? ? ? ? ? """ Only one file at a time may be opened, or else > ? ? ? ? ? ? there will be an open-read error""" > ? ? ? ? ? ? if self.loaded is None: > ? ? ? ? ? ? ? ? self.loaded = open(filename) > ? ? ? ? ? ? return self.loaded Woaaah, nice! Took me a while to digest this. I've never really gotten the hang of decorators, but property() seems useful. Decorators always seem so Python-specific; I think I intuitively prefer a solution that is more language-agnostic. Regarding the Borg: doesn't this version (a dictionary with another dictionary as its key) defeat its purpose? Isn't it "we are one" instead of "we are several" (one of each subclass). Btw, I subclassed from Borg to make it more explicit I was using the Borg pattern. Thanks!! From breamoreboy at yahoo.co.uk Wed Sep 26 10:21:10 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 Sep 2012 09:21:10 +0100 Subject: [Tutor] OT: Netiquette In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: On 24/09/2012 22:53, Prasad, Ramit wrote: > To see the real Dwight Hutto I suggest everybody take a look at his revolting conduct on several threads on the main Python mailing list over the last 48 hours, particularly the night before last. It's the most disgraceful behaviour I've seen from anybody in the 10 years that I've been using Python. The only face I personally want to see of him because of this is his back. -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Wed Sep 26 10:26:51 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 26 Sep 2012 04:26:51 -0400 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: > > To see the real Dwight Hutto I suggest everybody take a look at his > revolting conduct on several threads on the main Python mailing list > over the last 48 hours, Sparked by real trolls particularly the night before last. It's the > most disgraceful behaviour I've seen from anybody in the 10 years that > I've been using Python. Maybe you wanna have a look at threads in other languages then you one trick pony The only face I personally want to see of him > because of this is his back. > You wanna see my ass, because that's what you want homo. Butt just look, you can't touch. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Wed Sep 26 10:29:21 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 26 Sep 2012 04:29:21 -0400 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: http://www.youtube.com/watch?v=_W-fIn2QZgg -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From wprins at gmail.com Wed Sep 26 12:59:19 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 26 Sep 2012 11:59:19 +0100 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: Dwight, On 26 September 2012 09:26, Dwight Hutto wrote: > The only face I personally want to see of him >> because of this is his back. >> > > You wanna see my ass, because that's what you want homo. Butt just > look, you can't touch. The personal attacks and innuendo are really not acceptable and you're apparently deliberately twisting/misinterpreting Mark's words there. Waaaay out of line and quite disingenuous. Would you respond so aggressively to people in person? No? Well why do you think it's OK to be abusive on the internet? (If you do think it's OK to be this abusive to people in person, then you're sadly mistaken.) Grow up. Walk away. Learn to be polite to people you don't know. This is not the school playground and you're not 5 years old. Do some careful introspection. Walter From eryksun at gmail.com Wed Sep 26 15:46:37 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 26 Sep 2012 09:46:37 -0400 Subject: [Tutor] Borg di borg di borg (or: Swedish chef) In-Reply-To: <1348646193.41386.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <1348480975.40287.YahooMailNeo@web110713.mail.gq1.yahoo.com> <1348646193.41386.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: On Wed, Sep 26, 2012 at 3:56 AM, Albert-Jan Roskam wrote: > > I've never really gotten the hang of decorators, but property() seems > useful. property is a built-in type that can work as a decorator. property(fget=None, fset=None, fdel=None, doc=None) When used as a decorator, it assigns the decorated function and its docstring to fget and doc. The property itself has two decorators, setter and deleter, for assigning fset and fdel: @property def prop(self): "the prop" @prop.setter def prop(self, value): pass @prop.deleter def prop(self): pass All three functions have the same name to keep the class namespace uncluttered. > Decorators always seem so Python-specific; I think I intuitively > prefer a solution that is more language-agnostic. A decorator is Python-specific 'syntactic sugar' for wrapping a function around another function: def f(): pass f = decorator(f) Other decorators: staticmethod, classmethod abc.abstractmethod, abc.abstractproperty functools.wraps, functools.total_ordering (classes) The really Python-specific paradigm is the descriptor protocol at the heart of methods and properties in Python's object system. Here's Raymond Hettinger's intro to descriptors: http://users.rcn.com/python/download/Descriptor.htm > Regarding the Borg: doesn't this version (a dictionary with another > dictionary as its key) defeat its purpose? Isn't it "we are one" instead > of "we are several" (one of each subclass). Btw, I subclassed from Borg > to make it more explicit I was using the Borg pattern. It's the instances that "are one" in the Borg collective, in contrast to the singleton/Highlander for which "there can be only one" instance. It would be a mess to have multiple Borg subclasses with all instances of all classes sharing the same dict. With the property example I gave, you can get the dict for Generic instances via Generic._all_state[Generic] or Borg._all_state[Generic]. This is awkward. Using a property was just an example, and not a good one at that. I could have just set _state as a class attribute in __init__ without using a property at all: class Borg(object): def __init__(self): if "_state" not in self.__class__.__dict__: self.__class__._state = {} self.__dict__ = self._state This has to directly check the class __dict__ instead of using "hasattr" because the latter would also search the base classes. Another method is to use a metaclass to set _state when the class object itself gets created: class MetaBorg(type): def __new__(mcls, name, bases, dikt): dikt["_state"] = {} return type.__new__(mcls, name, bases, dikt) class Borg(object): __metaclass__ = MetaBorg def __init__(self): self.__dict__ = self._state New-style class objects are instances of a metaclass. The base metaclass is 'type'. Ponder this. 'object' is an instance of 'object'; 'type' is an instance of 'type'; 'object' is an instance of 'type'; 'type' is an instance of 'object'; and 'type' is a subclass of 'object'. New-style classes are subclasses of 'object' and instances of both 'type' and 'object'. Metaclasses are subclasses of 'type'. When a class is defined, first the body of the class is executed to define the namespace in the dict I've called "dikt". Then Python calls the metaclass (it's either 'type' or __metaclass__ if defined). The arguments are the name of the class (a string), its bases as a tuple (e.g. (object,)), and the dict. If you override type.__new__ in a custom metaclass you can hack the returned class object almost anyway you want. You can also override type.__call__ to intercept arguments when the class object is called: class Meta(type): def __call__(cls, *args, **kwds): print "__call__" return type.__call__(cls, *args, **kwds) class Test(object): __metaclass__ = Meta >>> Test() __call__ <__main__.Test object at 0xb732ef8c> On the downside, there's the problem that now you have two class definitions to maintain. Also, it complicates cooperative inheritance (e.g. mixin classes). The metaclass of the derived class has to be a non-strict subclass of the metaclass of all base classes. Plus it's quite possibly confusing... From walksloud at gmail.com Wed Sep 26 17:20:12 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 26 Sep 2012 08:20:12 -0700 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: <866E5A0B-C561-44BC-B88E-E4A4D7F65FE0@gmail.com> To the python tutor list, One comment I would like to make in light of the current email exchanges is that generally speaking, one of the things I have greatly appreciated about the python user community is how friendly and helpful they have been. This particularly strikes me when I see time and again, new users ask the same old questions in their own way, and time and again, the same very helpful experienced users reply with helpful comments - they are clearly committed to trying to help people understand python (and programming), generally, with great patience. I hope that new subscribers to the list do not go away with the thought that bickering is common - quite the contrary, as I stated above, I have found the python tutor list (and other python lists I subscribe to) mostly free of this problem. Of course, in any community, problems like the current one are unavoidable. People bring with them their own communication styles, and when communication is solely restricted to electronic forms, we are bound to misinterpret others meaning and intentions, and sometimes that gets the better of us. Also, as most of us know from experience, sometimes a good fight is what is needed, to clear the air - especially true with "family". Regards, Andre On Sep 26, 2012, at 3:59 AM, Walter Prins wrote: > Dwight, > > On 26 September 2012 09:26, Dwight Hutto wrote: >> The only face I personally want to see of him >>> because of this is his back. >>> >> >> You wanna see my ass, because that's what you want homo. Butt just >> look, you can't touch. > > The personal attacks and innuendo are really not acceptable and you're > apparently deliberately twisting/misinterpreting Mark's words there. > Waaaay out of line and quite disingenuous. Would you respond so > aggressively to people in person? No? Well why do you think it's OK > to be abusive on the internet? (If you do think it's OK to be this > abusive to people in person, then you're sadly mistaken.) Grow up. > Walk away. Learn to be polite to people you don't know. This is not > the school playground and you're not 5 years old. Do some careful > introspection. > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Thu Sep 27 02:52:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Sep 2012 10:52:19 +1000 Subject: [Tutor] OT: Netiquette In-Reply-To: <866E5A0B-C561-44BC-B88E-E4A4D7F65FE0@gmail.com> References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> <866E5A0B-C561-44BC-B88E-E4A4D7F65FE0@gmail.com> Message-ID: <5063A343.7090800@pearwood.info> On 27/09/12 01:20, Andre' Walker-Loud wrote: > To the python tutor list, > > One comment I would like to make in light of the current email exchanges >is that generally speaking, one of the things I have greatly appreciated >about the python user community is how friendly and helpful they have been. Thank you Andre, I know sometimes I can be a bit sarcastic to people who expect us to read their mind, but I do try hard to remember that they are beginners and not experienced in debugging programming errors. I think it is a shame that one particular person is aggressively trying to spoil this list out of his own fragile ego. -- Steven From steve at pearwood.info Thu Sep 27 02:55:38 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Sep 2012 10:55:38 +1000 Subject: [Tutor] Converting a real map to a dictionary In-Reply-To: References: Message-ID: <5063A40A.3000306@pearwood.info> On 26/09/12 11:20, Asmaa wrote: > Hello, > > I wonder if there is possibility to convert a map to a dictionary in python. > My concern is getting the number of houses for specific area to return > the coordination of the houses in this area. What sort of data do you expect to store in the dictionary? The only thing I can think of is "address" and "coordinates". As you say below, there is code to convert an address to its latitude and longitude, so you can map address to coordinates: d = {} for address in list_of_addresses: coord = get_coordinates_from_address(address) # whatever that function is d[address] = coord But I don't think this is useful. What do you intend to do with the addresses, and why do you think a dictionary is where you want to store them? > I can see that there are some useful codes to convert an address to its > latitude and longitude (py-googlemaps.sourceforge.net) But I want to > make a small network design on a real area, so I am looking for > a way to extract the available houses for this area using a google map > or something! Is this possible? This isn't really a Python question. The answer depends on the features that Google provides via their Maps API. See here to get started: https://developers.google.com/maps/ -- Steven From breamoreboy at yahoo.co.uk Thu Sep 27 03:12:20 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Sep 2012 02:12:20 +0100 Subject: [Tutor] OT: Netiquette In-Reply-To: <5063A343.7090800@pearwood.info> References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> <866E5A0B-C561-44BC-B88E-E4A4D7F65FE0@gmail.com> <5063A343.7090800@pearwood.info> Message-ID: On 27/09/2012 01:52, Steven D'Aprano wrote: > On 27/09/12 01:20, Andre' Walker-Loud wrote: >> To the python tutor list, >> >> One comment I would like to make in light of the current email exchanges >> is that generally speaking, one of the things I have greatly appreciated >> about the python user community is how friendly and helpful they have >> been. > > > Thank you Andre, I know sometimes I can be a bit sarcastic to people who > expect us to read their mind, but I do try hard to remember that they are > beginners and not experienced in debugging programming errors. > > I think it is a shame that one particular person is aggressively trying to > spoil this list out of his own fragile ego. > > Steven and Andre + lots :) -- Cheers. Mark Lawrence. From dwightdhutto at gmail.com Fri Sep 28 05:43:13 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Thu, 27 Sep 2012 23:43:13 -0400 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: On Wed, Sep 26, 2012 at 6:59 AM, Walter Prins wrote: > Dwight, > > On 26 September 2012 09:26, Dwight Hutto wrote: >> The only face I personally want to see of him >>> because of this is his back. >>> >> >> You wanna see my ass, because that's what you want homo. Butt just >> look, you can't touch. > > The personal attacks and innuendo are really not acceptable and you're > apparently deliberately twisting/misinterpreting Mark's words there. Oooh, a PR attack in another post. > Waaaay out of line and quite disingenuous. Would you respond so > aggressively to people in person? No? Well why do you think it's OK > to be abusive on the internet? (If you do think it's OK to be this > abusive to people in person, then you're sadly mistaken.) Grow up. > Walk away. Learn to be polite to people you don't know. This is not > the school playground and you're not 5 years old. But he started it. Do some careful > introspection. Yeah, all up in my fucking cranium with nothing but me and God to hold on to one another. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From xperimental22 at gmail.com Fri Sep 28 07:18:04 2012 From: xperimental22 at gmail.com (jh) Date: Fri, 28 Sep 2012 01:18:04 -0400 Subject: [Tutor] quick question Message-ID: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Howdy Folks, I'm using Python 3.2.3, IDLE 3.2.3 (on Windows 7 64-bit if it matters) Here is my code: # Write a program that asks for the prices of 5 items then displays the subtotal # of the 5 items, then calculates sales tax (6 percent), and the displays the total. # Get input for the prices of 5 items from the user item1 = float(input('Enter the price of item 1: ')) item2 = float(input('Enter the price of item 2: ')) item3 = float(input('Enter the price of item 3: ')) item4 = float(input('Enter the price of item 4: ')) item5 = float(input('Enter the price of item 5: ')) # Calculate and print the subtotal of the items subtotal = item1 + item2 + item3 + item4 + item5 print('The subtotal of your items is:', subtotal) # Calculate sales tax and add it to the subtotal tax = subtotal * .06 total = subtotal + tax # Display the total to the user print('The total amount of your items plus tax is:' , \ format(total, ',.2f')) And here's my output: Enter the price of item 1: 12.36 Enter the price of item 2: 55.63 Enter the price of item 3: 32.36 Enter the price of item 4: 358.28 Enter the price of item 5: 25552.22 The subtotal of your items is: 26010.850000000002 The total amount of your items plus tax is: 27,571.50 My question here is, why does my subtotal have so many decimals when I never went above 2 in my input? Thanks in advance, J From swiftone at swiftone.org Fri Sep 28 07:26:13 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 27 Sep 2012 22:26:13 -0700 Subject: [Tutor] quick question In-Reply-To: <00f001cd9d38$a3a06660$eae13320$@gmail.com> References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: On Thu, Sep 27, 2012 at 10:18 PM, jh wrote: > The subtotal of your items is: 26010.850000000002 > > My question here is, why does my subtotal have so many decimals when I never > went above 2 in my input? This is not actually a Python thing, it's a computer thing. Computers represent numbers (everything) in binary, as you doubtless have heard. The issue is that while 1 or 12 or 4562 are easily represented in binary, a number like "0.1" is less obvious. Floating point numbers are stored as binary approximations that dont' work out to exactly the same thing. (For _most_ purposes they are close enough, but if you are every dealing with highly precise math, there are libraries to help be more accurate) This is similar to how 1/3 can't be represented easily in decimal form. (3 is hard number to use as a divisor in base 10. It turns out that most digits are painful to use as divisors in base 2 (binary) except for 1,2,4, 8, or other powers of 2.) -- Brett Ritter / SwiftOne swiftone at swiftone.org From dwightdhutto at gmail.com Fri Sep 28 07:27:19 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Fri, 28 Sep 2012 01:27:19 -0400 Subject: [Tutor] quick question In-Reply-To: <00f001cd9d38$a3a06660$eae13320$@gmail.com> References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: On Fri, Sep 28, 2012 at 1:18 AM, jh wrote: > Howdy Folks, > > I'm using Python 3.2.3, IDLE 3.2.3 (on Windows 7 64-bit if it matters) > > Here is my code: > > > # Write a program that asks for the prices of 5 items then displays the > subtotal > # of the 5 items, then calculates sales tax (6 percent), and the displays > the total. > > # Get input for the prices of 5 items from the user > > item1 = float(input('Enter the price of item 1: ')) > item2 = float(input('Enter the price of item 2: ')) > item3 = float(input('Enter the price of item 3: ')) > item4 = float(input('Enter the price of item 4: ')) > item5 = float(input('Enter the price of item 5: ')) > > # Calculate and print the subtotal of the items > > subtotal = item1 + item2 + item3 + item4 + item5 > > print('The subtotal of your items is:', subtotal) > > # Calculate sales tax and add it to the subtotal > > tax = subtotal * .06 > total = subtotal + tax > > # Display the total to the user > > print('The total amount of your items plus tax is:' , \ > format(total, ',.2f')) > > > And here's my output: > > Enter the price of item 1: 12.36 > Enter the price of item 2: 55.63 > Enter the price of item 3: 32.36 > Enter the price of item 4: 358.28 > Enter the price of item 5: 25552.22 > The subtotal of your items is: 26010.850000000002 > The total amount of your items plus tax is: 27,571.50 > > My question here is, why does my subtotal have so many decimals when I never > went above 2 in my input? > > Thanks in advance, > J > >>> x = round(float(10),2) >>> x 10.0 >>> x + round(float(1000.755555),2) 1010.76 >>> You have to round(float_number_variable,2) the float off. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Fri Sep 28 07:31:33 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Fri, 28 Sep 2012 01:31:33 -0400 Subject: [Tutor] quick question In-Reply-To: References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: On Fri, Sep 28, 2012 at 1:26 AM, Brett Ritter wrote: > On Thu, Sep 27, 2012 at 10:18 PM, jh wrote: >> The subtotal of your items is: 26010.850000000002 >> >> My question here is, why does my subtotal have so many decimals when I never >> went above 2 in my input? > > This is not actually a Python thing, it's a computer thing. Computers > represent numbers (everything) in binary, as you doubtless have heard. > The issue is that while 1 or 12 or 4562 are easily represented in > binary, a number like "0.1" is less obvious. Floating point numbers > are stored as binary approximations that dont' work out to exactly the > same thing. (For _most_ purposes they are close enough, but if you > are every dealing with highly precise math, there are libraries to > help be more accurate) > > This is similar to how 1/3 can't be represented easily in decimal > form. (3 is hard number to use as a divisor in base 10. It turns out > that most digits are painful to use as divisors in base 2 (binary) > except for 1,2,4, 8, or other powers of 2.) > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org That's a floating point error, not a round it off from the 3rd digit in this case. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From dwightdhutto at gmail.com Fri Sep 28 07:34:53 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Fri, 28 Sep 2012 01:34:53 -0400 Subject: [Tutor] quick question In-Reply-To: References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: > > That's a floating point error, not a round it off from the 3rd digit > in this case. More an error you have to calculate for from the macros of the languages python evolves from, down to the processor. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com From breamoreboy at yahoo.co.uk Fri Sep 28 11:03:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 10:03:37 +0100 Subject: [Tutor] quick question In-Reply-To: <00f001cd9d38$a3a06660$eae13320$@gmail.com> References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: On 28/09/2012 06:18, jh wrote: [snip] > The subtotal of your items is: 26010.850000000002 > The total amount of your items plus tax is: 27,571.50 > > My question here is, why does my subtotal have so many decimals when I never > went above 2 in my input? > > Thanks in advance, > J Brett Ritter has already answered your question, but a web search would have found the answer a lot faster, as this has been asked umpteen times on Python lists alone. Also note that if you'd have formatted the output in the same way that you did for the total you'd never have noticed. -- Cheers. Mark Lawrence. From bodsda at googlemail.com Fri Sep 28 12:38:48 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Fri, 28 Sep 2012 11:38:48 +0100 Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: On Sep 28, 2012 4:47 AM, "Dwight Hutto" wrote: > > On Wed, Sep 26, 2012 at 6:59 AM, Walter Prins wrote: > > Dwight, > > > > On 26 September 2012 09:26, Dwight Hutto wrote: > >> The only face I personally want to see of him > >>> because of this is his back. > >>> > >> > >> You wanna see my ass, because that's what you want homo. Butt just > >> look, you can't touch. > > > > The personal attacks and innuendo are really not acceptable and you're > > apparently deliberately twisting/misinterpreting Mark's words there. > > Oooh, a PR attack in another post. > > > > Waaaay out of line and quite disingenuous. Would you respond so > > aggressively to people in person? No? Well why do you think it's OK > > to be abusive on the internet? (If you do think it's OK to be this > > abusive to people in person, then you're sadly mistaken.) Grow up. > > Walk away. Learn to be polite to people you don't know. This is not > > the school playground and you're not 5 years old. > > But he started it. > > Do some careful > > introspection. > > Yeah, all up in my fucking cranium with nothing but me and God to hold > on to one another. > > > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Probably not a good idea to advertise that your the CEO of hitwebdevelopment.com if your gonna post like that. Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicki at thepenguin.org Thu Sep 6 15:56:38 2012 From: vicki at thepenguin.org (vicki at thepenguin.org) Date: Thu, 06 Sep 2012 13:56:38 -0000 Subject: [Tutor] =?utf-8?q?how_to_print_array_without_adding_newline?= In-Reply-To: <50486944.8030100@davea.name> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> Message-ID: <20120906134954.22610.qmail@server308.com> Thank you for your reply. I understand that it is odd, but my program is being called from a hubot and returning data to it as well. I have figured out how to make the changes to get it to output the correct data in the correct format, but now I am getting a "Premature end of script headers" error. I have the correct #! line and the output from the command line shows no errors that would be interfering. Is there a way to make sure it is showing me all the errors? To increase error logging? ------ !/usr/bin/env python import cloudfiles import random import sys import array conn = cloudfiles.get_connection('username', 'key') containers = conn.get_all_containers() i=0 print "Content-type: text/html"; wholelist=containers[0].list_objects() random.shuffle(wholelist) newlist=[] #newlist=wholelist[:] try: # print sys.argv[1] if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") # print sys.argv[1] del wholelist[int(sys.argv[1]):] while i < int(sys.argv[1]): newlist.append("http://example.com/"+wholelist[i].rstrip()) i = i+1 except IndexError, e: del newlist[5] except Exception, err: print 'Caught an exception' print newlist, ------- Vicki > -------Original Message------- > From: Dave Angel > To: vickistan > Cc: tutor at python.org > Subject: Re: [Tutor] how to print array without adding newline > Sent: Sep 06 '12 05:13 > > On 08/18/2012 09:17 PM, vickistan wrote: > > Hello: I am trying to output an array to another program that takes an array > > as input, but the print statement adds a newline. If it were adding to each > > individual element, I could solve it easily, but it is adding one at the end > > of the array. Is there another way to print an array besides > > > > print arrayname > > > > If it were a string, I have a whole host of options, but I need it to be > > output as an array. Each element is a url. I call it from a browser, and it > > works except for the added newline. > > > > Here are the relevant lines: > > > > ================= > > /* code that connects to cloudfiles omitted */ > > > > containers = conn.get_all_containers() > > i=0 > > print "Content-type: text/html\n\n"; > > wholelist=containers[0].list_objects() > > random.shuffle(wholelist) > > newlist=[] > > try: > >???? del wholelist[int(sys.argv[1]):] > >???? while i < int(sys.argv[1]): > >???????? newlist.append("http://example.com/"+wholelist[i].rstrip()) > >???????? i = i+1 > > except IndexError, e: > >???? del newlist[5] > > print newlist > > ============== > > > > The output I am seeing is as follows: > > > > ['http://example.com/wet-longhaireddachshund.jpg', > > 'http://example.com/dachshund2.jpg', > > 'http://example.com/dachshundingrass.jpg'] > > > > Any tips on better coding practices are welcome, but please don't beat me up > > > > Thanks, > > vickistan > > > > > > > > I don't see any arrays in that code, just lists.??i also don't see how > that program could produce exactly that ouput, as it also prints > > "Content-type: text/html\n\n"; > > But if you literally mean that only the final newline is a problem, then > just end the print statement with a comma: > ????print newlist, > > If you want more flexibility, instead of printing the list as a single > entity, you can just loop through it.??that way, you can choose which > newlines you want, if any. > ????for item in newlist: > ????????print repr(item),????#or many other variants.??But you probably > want some delimeter at least. > > > it's not clear what your other program is expecting for stdin, since > there is no single standard for "takes an array for input."??it's also > unclear why a trailing linefeed should hurt you.??But I hope this will > help some. > > > -- > > DaveA > > From smichr at gmail.com Tue Sep 11 13:44:04 2012 From: smichr at gmail.com (Chris Smith) Date: Tue, 11 Sep 2012 11:44:04 -0000 Subject: [Tutor] lazily decorated sort Message-ID: Hi all, I'm wondering if anyone has seen or knows of a good way to do a lazily decorated sort. I was reading about how good the DSU (decorate, sort, undecorate) approach is but the problem that we are running into in SymPy is that we want to get by with a fast hash sort if possible, and only decorate to break ties *if necessary*. It's a pity to decorate with an expensive function if you don't need it but I don't know how to only decorate when there are ties. Do you have any ideas how to do the following better: def f(): """delay for 2 seconds""" from time import time from random import random t=time() while time()-t<1: pass return random class foo(object): """an object that calls the delay function when comparing""" def __eq__(self, other): return f() == f() def __lt__(self, other): return f() < f() def lazyDSU(seq, keys=[]): """Return sorted seq, breaking ties by lazily applying keys successively as needed from the list of provided keys.""" if not keys: seq = sorted(seq) else: d = defaultdict(list) f = keys.pop(0) for a in seq: d[f(a)].append(a) seq = [] for k in sorted(d.keys()): if len(d[k]) > 1 and keys: seq.extend(lazyDSU(d[k], keys=keys[1:])) else: seq.extend(d[k]) return tuple(seq) >>> lazyDSU(range(5)) # fast (0, 1, 2, 3, 4) >>> [i[0] for i in lazyDSU(zip(range(5), [foo()]*5))] # fast, no ties [0, 1, 2, 3, 4] >>> [i[0] for i in lazyDSU([(0, foo())] + list(zip(range(5), [foo()]*5)))] # slower [0, 0, 1, 2, 3, 4] The last run takes 4 seconds (but not 12 seconds) because only two had to have ties broken. In the examples, no keys were passed but the discretionary decoration was demonstrated. /Chris From zach_dunphey at sbcglobal.net Tue Sep 11 23:18:39 2012 From: zach_dunphey at sbcglobal.net (zack dunphey) Date: Tue, 11 Sep 2012 21:18:39 -0000 Subject: [Tutor] python new window Message-ID: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> I have used python a lot at school and am relatively good with it. I just tried to get it on my mac and i try to open a "new window" and every time I do it freezes and i have to either do a forced quit or unplug the whole computer. I have been able to get into a "new window" through programs i saved on a jump drive at school and brought home but every time i try to do anything from that window it freezes. i tried re downloading it but that didn't help. can some one please help me zack dunphey From laddosingh at gmail.com Thu Sep 13 15:27:29 2012 From: laddosingh at gmail.com (Sukhvinder Singh) Date: Thu, 13 Sep 2012 15:27:29 +0200 Subject: [Tutor] Writing a function to examine a directory and testing with unittest Message-ID: Hi. I have an assigment where I'm need to write a module containing a function to examine the contents of the current working directory and print out a count of how many files have each extension (".txt", ".doc", etc.) I am a beginner in Python. This is the code of the function module: --- import os from collections import Counter path = ":c//mypath/dir" dirs = os.listdir( path ) filenames = {"this.txt", "that.txt", "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"} extensions = [] for filename in filenames: f = open(filename, "w") f.write("Some text\n") f.close() name , ext = os.path.splitext(f.name) extensions.append(ext) # This would print all the files and directories for file in dirs: print(file) for ext, count in Counter(extensions).items(): print("Count for %s: " % ext, count) --- path is just an example - not real path. I need to make this module into a function and write a separate unittest module to verify by testing that the function gives correct results. Help and pointers are much appreciated. -- Sukhvinder Singh +4740633099 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sntshkmr60 at gmail.com Sun Sep 16 09:20:09 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Sun, 16 Sep 2012 12:50:09 +0530 Subject: [Tutor] list all links with certain extension in an html file python Message-ID: I want to extract (no I don't want to download) all links that end in a certain extension. Suppose there is a webpage, and in the head of that webpage there are 4 different CSS files linked to external server. Let the head look like this: Please note that I don't want to download those CSS, instead I want something like this (to stdout): http://foo.bar/part1.css http://foo.bar/part1.css http://foo.bar/part1.css http://foo.bar/part1.css Also I don't want to use external libraries. I am asking for: which libraries and functions should I use? From mjldehoon at yahoo.com Mon Sep 17 07:20:48 2012 From: mjldehoon at yahoo.com (Michiel de Hoon) Date: Sun, 16 Sep 2012 22:20:48 -0700 (PDT) Subject: [Tutor] Storing information as attributes or as a dictionary Message-ID: <1347859248.4037.YahooMailClassic@web164006.mail.gq1.yahoo.com> Dear all, Suppose I have a parser that parses information stored in e.g. an XML file. I would like to store the information contained in this XML file as a Python object. One option is to create a class like this: class Record(object): pass and store the information in the XML file as attributes of objects of this class, as in >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record.name "John Doe" >>> record.birthday "February 30, 1920" Alternatively I could subclass the dictionary class: class Record(dict): pass and have something like >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record['name'] "John Doe" >>> record['birthday'] "February 30, 1920" I can see some advantage to using a dictionary, because it allows me to use the same strings as keys in the dictionary as in used in the XML file itself. But are there some general guidelines for when to use a dictionary-like class, and when to use attributes to store information? In particular, are there any situations where there is some advantage in using attributes? Thanks, -Michiel. From ajtritt at lbl.gov Wed Sep 19 20:27:32 2012 From: ajtritt at lbl.gov (Andrew Tritt) Date: Wed, 19 Sep 2012 11:27:32 -0700 Subject: [Tutor] floating point rounding inconsistency Message-ID: Hello, I am new to python, and I was experimenting with the round function, and came across what appears to be a bug in floating point rounding. I am guessing there is a valid explanation for it. When I round the floating points 10.6[0-9]5 to two decimal places, it rounds as expected for 6 of the 10, but not for the other 4. When I try the same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 possibilties, and not for the analogous floats. Also, python storing the numbers as they are represented at the prompt. i.e. 10.665 is stored as 10.665, not something like 10.665000001 or 10.66499999999. Can anyone explain to me what's happening? $ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> round(10.605,2) 10.61 >>> round(10.615,2) 10.62 >>> round(10.625,2) 10.63 >>> round(10.635,2) 10.63 >>> round(10.645,2) 10.64 >>> round(10.655,2) 10.65 >>> round(10.665,2) 10.66 >>> round(10.675,2) 10.68 >>> round(10.685,2) 10.69 >>> round(10.695,2) 10.7 >>> round(10.705,2) 10.71 >>> round(10.715,2) 10.71 >>> round(10.725,2) 10.72 >>> round(10.735,2) 10.73 >>> round(10.745,2) 10.74 >>> round(10.755,2) 10.76 >>> round(10.765,2) 10.77 >>> round(10.775,2) 10.78 >>> round(10.785,2) 10.79 >>> round(10.795,2) 10.79 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gaikwadpreeti at gmail.com Thu Sep 20 18:14:37 2012 From: gaikwadpreeti at gmail.com (Preeti Gaikwad) Date: Thu, 20 Sep 2012 18:14:37 +0200 Subject: [Tutor] how to save text or dat file using python Message-ID: Hello I am new user of python pls let me know how to save dat or txt file using python? what is the basic cmd for this? thanks a lot in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From gaikwadpreeti at gmail.com Fri Sep 21 15:20:09 2012 From: gaikwadpreeti at gmail.com (Preeti Gaikwad) Date: Fri, 21 Sep 2012 15:20:09 +0200 Subject: [Tutor] Fwd: regarding saving data in ASCII format In-Reply-To: References: Message-ID: Hello i am new user of python pls let me know how to save the data in ascii formate Suppose I hv two column data in x and y like x(:,-1) and y(:,0) then how to save this in [x(:,-1), y(:,0)]; and then save this in ascii or dat file? thanks a lot in advance -- preeti gaikwad -------------- next part -------------- An HTML attachment was scrubbed... URL: From wii_fit at ymail.com Sun Sep 23 06:46:08 2012 From: wii_fit at ymail.com (Fit Wii) Date: Sat, 22 Sep 2012 21:46:08 -0700 (PDT) Subject: [Tutor] assembly language and boot loader Message-ID: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> Hi there, ? Is there any IDE or Python interpreter that can show the assembly language generated by each line of python code?? Is there any popular boot loader written in Python (plus some assembly code)? ? Thanks, Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From dsnowdon at carolina.rr.com Thu Sep 27 18:42:47 2012 From: dsnowdon at carolina.rr.com (Debbie Snowdon) Date: Thu, 27 Sep 2012 12:42:47 -0400 Subject: [Tutor] Python for Absolute Beginners Message-ID: <1133DD8F960C48D1A6632C0A0A05F76C@DebbiePC> Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access the Companion Guide. Do I need it? Do I have to purchase it? How do I get it? The site he sends me to is very confusing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From beqirllarifation at gmail.com Mon Sep 17 21:21:30 2012 From: beqirllarifation at gmail.com (Fation Beqirllari) Date: Mon, 17 Sep 2012 21:21:30 +0200 Subject: [Tutor] hello Message-ID: I have a php code and I want to translate it to python..Can you help me > please,or show me how to do it ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmslgillis at gmail.com Sat Sep 8 18:08:13 2012 From: jmslgillis at gmail.com (james gillis) Date: Sat, 08 Sep 2012 16:08:13 -0000 Subject: [Tutor] new student Message-ID: I am looking for some recommendations ,,,,books to read.....websites,links,,,,,any information would be appreciated. Thanks, jmslgillis at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From phou_72 at sbcglobal.net Fri Sep 28 06:14:00 2012 From: phou_72 at sbcglobal.net (CHERRY PHOUTHAVONG) Date: Thu, 27 Sep 2012 21:14:00 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <1348805640.80600.YahooMailClassic@web181002.mail.ne1.yahoo.com> I would like tutorial ? Thank You? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Fri Sep 28 13:25:54 2012 From: dextrous85 at gmail.com (vishwajeet singh) Date: Fri, 28 Sep 2012 16:55:54 +0530 Subject: [Tutor] (no subject) In-Reply-To: <1348805640.80600.YahooMailClassic@web181002.mail.ne1.yahoo.com> References: <1348805640.80600.YahooMailClassic@web181002.mail.ne1.yahoo.com> Message-ID: On Fri, Sep 28, 2012 at 9:44 AM, CHERRY PHOUTHAVONG wrote: > I would like tutorial ? Thank You > What tutorial ? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Sep 28 13:29:29 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:29:29 +0100 Subject: [Tutor] lazily decorated sort In-Reply-To: References: Message-ID: On 11/09/2012 12:44, Chris Smith wrote: > Hi all, > > I'm wondering if anyone has seen or knows of a good way to do a lazily > decorated sort. I was reading about how good the DSU (decorate, sort, > undecorate) approach is but the problem that we are running into in > SymPy is that we want to get by with a fast hash sort if possible, and > only decorate to break ties *if necessary*. It's a pity to decorate > with an expensive function if you don't need it but I don't know how > to only decorate when there are ties. Do you have any ideas how to do > the following better: > > > def f(): > """delay for 2 seconds""" > from time import time > from random import random > t=time() > while time()-t<1: > pass > return random > > class foo(object): > """an object that calls the delay function when comparing""" > def __eq__(self, other): > return f() == f() > def __lt__(self, other): > return f() < f() > > def lazyDSU(seq, keys=[]): > """Return sorted seq, breaking ties by lazily applying keys successively > as needed from the list of provided keys.""" > if not keys: > seq = sorted(seq) > else: > d = defaultdict(list) > f = keys.pop(0) > for a in seq: > d[f(a)].append(a) > seq = [] > for k in sorted(d.keys()): > if len(d[k]) > 1 and keys: > seq.extend(lazyDSU(d[k], keys=keys[1:])) > else: > seq.extend(d[k]) > return tuple(seq) > >>>> lazyDSU(range(5)) # fast > (0, 1, 2, 3, 4) >>>> [i[0] for i in lazyDSU(zip(range(5), [foo()]*5))] # fast, no ties > [0, 1, 2, 3, 4] >>>> [i[0] for i in lazyDSU([(0, foo())] + list(zip(range(5), [foo()]*5)))] # slower > [0, 0, 1, 2, 3, 4] > > The last run takes 4 seconds (but not 12 seconds) because only two had > to have ties broken. > > In the examples, no keys were passed but the discretionary decoration > was demonstrated. > > /Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > It's my understanding that DSU is unneccessary in modern versions of Python so I suggest you read http://docs.python.org/howto/sorting.html http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Sorting these before you go any further, if you haven't already done so already that is. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Fri Sep 28 13:33:35 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:33:35 +0100 Subject: [Tutor] hello In-Reply-To: References: Message-ID: On 17/09/2012 20:21, Fation Beqirllari wrote: > I have a php code and I want to translate it to python..Can you help me >> please,or show me how to do it ? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > A better subject would help and no, we don't show you how to do it. You show us that you'd made some sort of attempt at translating the code and run into a problem, then we'll help. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Fri Sep 28 13:37:50 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:37:50 +0100 Subject: [Tutor] how to save text or dat file using python In-Reply-To: References: Message-ID: On 20/09/2012 17:14, Preeti Gaikwad wrote: > Hello I am new user of python pls let me know how to save dat or txt file > using python? what is the basic cmd for this? thanks a lot in advance > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yod need to write some code. When you run into problems show us your code and if appropriate the entire traceback and we'll help. As a starter search the web for something like "Python with file write". -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Fri Sep 28 13:42:51 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:42:51 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1348805640.80600.YahooMailClassic@web181002.mail.ne1.yahoo.com> References: <1348805640.80600.YahooMailClassic@web181002.mail.ne1.yahoo.com> Message-ID: On 28/09/2012 05:14, CHERRY PHOUTHAVONG wrote: > I would like tutorial ? Thank You > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Given that your subject is specifically no subject that's a tricky one. If you're talking about a Python tutorial, a good starting point is the Python tutorial http://docs.python.org/tutorial/ :) -- Cheers. Mark Lawrence. From oscar.j.benjamin at gmail.com Fri Sep 28 13:49:35 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Sep 2012 12:49:35 +0100 Subject: [Tutor] python new window In-Reply-To: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> References: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> Message-ID: Hi Zack, On 11 September 2012 22:18, zack dunphey wrote: > I have used python a lot at school and am relatively good with it. I just > tried to get it on my mac and i try to open a "new window" and every time I > do it freezes and i have to either do a forced quit or unplug the whole > computer. I have been able to get into a "new window" through programs i > saved on a jump drive at school and brought home but every time i try to do > anything from that window it freezes. i tried re downloading it but that > didn't help. > can some one please help me I'd like to help but I have no idea what you're talking about. What is a "new window"? Is that something that your script tries to do? Or do you mean a window to view and run your code? Could you be more specific about what exactly you're doing? Python does many things and can be used in many different ways so you cannot assume that anyone else really has any idea what you are doing. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Sep 28 13:39:25 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:39:25 +0100 Subject: [Tutor] Fwd: regarding saving data in ASCII format In-Reply-To: References: Message-ID: On 21/09/2012 14:20, Preeti Gaikwad wrote: > Hello i am new user of python pls let me know how to save the data in ascii > formate Suppose I hv two column data in x and y like > > x(:,-1) and y(:,0) then how to save this in [x(:,-1), y(:,0)]; and then > save this in ascii or dat file? > > > thanks a lot in advance > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please see my response to your other question :) -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Fri Sep 28 13:48:05 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 12:48:05 +0100 Subject: [Tutor] assembly language and boot loader In-Reply-To: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> References: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> Message-ID: On 23/09/2012 05:46, Fit Wii wrote: > Hi there, > > Is there any IDE or Python interpreter that can show the > assembly language generated by each line of python code? Is there any popular boot loader written in Python > (plus some assembly code)? > > Thanks, > Jerry > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I don't know about getting down to assembly but the dis module http://docs.python.org/library/dis.html can show you the byte code. -- Cheers. Mark Lawrence. From oscar.j.benjamin at gmail.com Fri Sep 28 13:56:32 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Sep 2012 12:56:32 +0100 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: On 19 September 2012 19:27, Andrew Tritt wrote: > Hello, > > I am new to python, and I was experimenting with the round function, and > came across what appears to be a bug in floating point rounding. I am > guessing there is a valid explanation for it. > > When I round the floating points 10.6[0-9]5 to two decimal places, it > rounds as expected for 6 of the 10, but not for the other 4. When I try the > same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 > possibilties, and not for the analogous floats. > > Also, python storing the numbers as they are represented at the prompt. > i.e. 10.665 is stored as 10.665, not something like 10.665000001 or > 10.66499999999. > > Can anyone explain to me what's happening? > It is because Python (like all programming languages I know) represents floating point numbers in base 2. This is discussed in the python.orgtutorial: http://docs.python.org/tutorial/floatingpoint.html Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Fri Sep 28 13:59:47 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Sep 2012 12:59:47 +0100 Subject: [Tutor] assembly language and boot loader In-Reply-To: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> References: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> Message-ID: On 23 September 2012 05:46, Fit Wii wrote: > Is there any IDE or Python interpreter that can show the assembly language > generated by each line of python code? Is there any popular boot loader > written in Python (plus some assembly code)? > Python doesn't generate assembly language code. It does, however, compile python code to bytecode which is like assembly for the Python interpreter rather than for the CPU. Have a look at the dis module: http://docs.python.org/library/dis.html Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Sep 28 14:04:06 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 28 Sep 2012 08:04:06 -0400 Subject: [Tutor] new student In-Reply-To: References: Message-ID: On Sat, Sep 8, 2012 at 12:08 PM, james gillis wrote: > I am looking for some recommendations ,,,,books to > read.....websites,links,,,,,any information would be appreciated. Thanks, > jmslgillis at gmail.com > http://python.org/doc/ is a nice place to start. -- Joel Goldstick From oscar.j.benjamin at gmail.com Fri Sep 28 14:09:19 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Sep 2012 13:09:19 +0100 Subject: [Tutor] list all links with certain extension in an html file python In-Reply-To: References: Message-ID: On 16 September 2012 08:20, Santosh Kumar wrote: > I want to extract (no I don't want to download) all links that end in > a certain extension. > > Suppose there is a webpage, and in the head of that webpage there are > 4 different CSS files linked to external server. Let the head look > like this: > > > > > > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > > Also I don't want to use external libraries. I am asking for: which > libraries and functions should I use? > If you don't want to use any third-party libraries then the standard library has a module urllib2 for downloading a html file and htmlparser for parsing it: http://docs.python.org/library/urllib2.html#examples http://docs.python.org/library/htmlparser.html#example-html-parser-application Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Sep 28 14:15:56 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 13:15:56 +0100 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: On 28/09/2012 12:56, Oscar Benjamin wrote: > On 19 September 2012 19:27, Andrew Tritt wrote: > >> Hello, >> >> I am new to python, and I was experimenting with the round function, and >> came across what appears to be a bug in floating point rounding. I am >> guessing there is a valid explanation for it. >> >> When I round the floating points 10.6[0-9]5 to two decimal places, it >> rounds as expected for 6 of the 10, but not for the other 4. When I try the >> same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 >> possibilties, and not for the analogous floats. >> >> Also, python storing the numbers as they are represented at the prompt. >> i.e. 10.665 is stored as 10.665, not something like 10.665000001 or >> 10.66499999999. >> >> Can anyone explain to me what's happening? >> > > It is because Python (like all programming languages I know) represents > floating point numbers in base 2. This is discussed in the python.orgtutorial: > http://docs.python.org/tutorial/floatingpoint.html > > Oscar > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The Python round function is itself problematic. The idea of deprecating it is currently being discussed on Python ideas. This quote from Calvin Spealman is typical "Also, I'd be completely in support of dropping round() and agree it gets misused and leads to too much confusion. We should promote the right ways, and sometimes to show the right path you need to lock another door and throw away the key.". -- Cheers. Mark Lawrence. From steve at pearwood.info Fri Sep 28 14:14:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Sep 2012 22:14:06 +1000 Subject: [Tutor] lazily decorated sort In-Reply-To: References: Message-ID: <5065948E.6030606@pearwood.info> On 11/09/12 21:44, Chris Smith wrote: > Hi all, > > I'm wondering if anyone has seen or knows of a good way to do a lazily > decorated sort. I was reading about how good the DSU (decorate, sort, > undecorate) approach is but the problem that we are running into in > SymPy is that we want to get by with a fast hash sort if possible, and > only decorate to break ties *if necessary*. It's a pity to decorate > with an expensive function if you don't need it but I don't know how > to only decorate when there are ties. Firstly, unless you intend supporting Python 2.3 or older, there is (probably) no need for an explicit DSU approach. Instead, use the key argument to sorted and list.sort. I'm not sure I completely understand your question. If you know ahead of time that you can avoid DSU, you can do this: if condition: x = sorted(something) else: x = sorted(something, key=func) But I imagine that's not what you mean. My guess is that you want the sort to be sufficiently clever that instead of doing this: decorate every item compare decorated items, and sort as needed undecorate every item you want it to do this: compare items, sorting as needed if they are equal, compare decorated items (which will never tie???) Am I close? I think you could arrange that two ways: 1) A two-pass sort; first, sort undecorated, then scan looking for ties, if you find any, sort again with a key function; (This is safe, since sorting in Python is now guaranteed to be stable.) 2) or use a key function that does something like this: class SmartComparator(object): def __init__(self, item): self.item = item def __cmp__(self, other): x = cmp(self.item, other.item) if x == 0: return cmp(self.decorate(self.item), self.decorate(other.item)) return x def decorate(self, value): # expensive magic goes in here... sorted(items, key=SmartComparator) I think the second version is more promising, since it avoids a linear search for ties. You will need to check the documentation to see whether sorting relies on __cmp__ or rich comparisons (__gt__, __lt__, __eq__, etc.). If you need any help, don't hesitate to ask. P.S. I just discovered sympy recently, it is awesome. -- Steven From d at davea.name Fri Sep 28 14:14:27 2012 From: d at davea.name (Dave Angel) Date: Fri, 28 Sep 2012 08:14:27 -0400 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: <506594A3.5010309@davea.name> On 09/19/2012 02:27 PM, Andrew Tritt wrote: > Hello, > > I am new to python, and I was experimenting with the round function, and > came across what appears to be a bug in floating point rounding. I am > guessing there is a valid explanation for it. Welcome to the Python tutor; hope you enjoy learning and using python. Not a bug, and not specific to Python. And not new - many threads already discuss this. > > When I round the floating points 10.6[0-9]5 to two decimal places, it > rounds as expected for 6 of the 10, but not for the other 4. When I try the > same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 > possibilties, and not for the analogous floats. > > Also, python storing the numbers as they are represented at the prompt. > i.e. 10.665 is stored as 10.665, not something like 10.665000001 or > 10.66499999999. > > Can anyone explain to me what's happening? Yep, Python does not store the number 10.065 in any of the forms you appear to expect. it instead converts it to binary floating point, and stores the nearest value that can represent. Sometimes such a value will convert back to the decimal value you started with, sometimes not. This is not a new problem - it was highlighted in the textbook i used for Fortran in 1967. But it was more or less made permanent by the Intel 8087 chip, which did binary floating point, and did not do decimal floating point. The IEEE committee then standardized pretty much on what was already done, and that's what's on all the Intel and AMD chips we see now. Generally, the way to avoid the problem is to mask it while displaying. Use some form of formatting to represent the precision you expect. See the article Oscar pointed you to: http://docs.python.org/tutorial/floatingpoint.html -- DaveA From __peter__ at web.de Fri Sep 28 14:17:31 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Sep 2012 14:17:31 +0200 Subject: [Tutor] lazily decorated sort References: Message-ID: Chris Smith wrote: > I'm wondering if anyone has seen or knows of a good way to do a lazily > decorated sort. I was reading about how good the DSU (decorate, sort, > undecorate) approach is but the problem that we are running into in > SymPy is that we want to get by with a fast hash sort if possible, and > only decorate to break ties *if necessary*. It's a pity to decorate > with an expensive function if you don't need it but I don't know how > to only decorate when there are ties. Do you have any ideas how to do > the following better: Here's an implementation that uses the key argument that is supported by list.sort() and the built-in sorted(). A generator function (keys(value)) is used to calculate the partial keys as necessary. import time import random from contextlib import contextmanager from functools import total_ordering try: from itertools import izip except ImportError: # python 3 izip = zip def make_key(keys): @total_ordering class Key(object): def __init__(self, value): self._keys = keys(value) self._cached = [] def keys(self): for k in self._cached: yield k for k in self._keys: self._cached.append(k) yield k def __eq__(self, other): return all(a == b for a, b in izip(self.keys(), other.keys())) def __lt__(self, other): for a, b in izip(self.keys(), other.keys()): if a == b: pass else: return a < b return False return Key @contextmanager def bench(description): print("starting...") start = time.time() yield stop = time.time() print(description.format(stop - start)) if __name__ == "__main__": N = 10 def keys(value): """user defined lazy key""" yield value time.sleep(.1) yield random.random() data = list(range(N)) + [N, N] wanted = list(data) random.shuffle(data) with bench("lazy key: {:.1f}s"): got = sorted(data, key=make_key(keys)) assert got == wanted with bench("eager key: {:.1f}s"): got = sorted(data, key=lambda value: tuple(keys(value))) assert got == wanted From d at davea.name Fri Sep 28 14:19:57 2012 From: d at davea.name (Dave Angel) Date: Fri, 28 Sep 2012 08:19:57 -0400 Subject: [Tutor] how to save text or dat file using python In-Reply-To: References: Message-ID: <506595ED.5040103@davea.name> On 09/20/2012 12:14 PM, Preeti Gaikwad wrote: > Hello I am new user of python pls let me know how to save dat or txt file > using python? what is the basic cmd for this? thanks a lot in advance > > Have you written any code that READs files? Check out the open() function, in particular the "w" or "wb" mode. Then use the method write(), on the file object returned by open(). -- DaveA From steve at pearwood.info Fri Sep 28 14:24:55 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Sep 2012 22:24:55 +1000 Subject: [Tutor] assembly language and boot loader In-Reply-To: References: <1348375568.6377.YahooMailNeo@web114316.mail.gq1.yahoo.com> Message-ID: <50659717.40701@pearwood.info> On 28/09/12 21:59, Oscar Benjamin wrote: > On 23 September 2012 05:46, Fit Wii wrote: > >> Is there any IDE or Python interpreter that can show the assembly language >> generated by each line of python code? Is there any popular boot loader >> written in Python (plus some assembly code)? That's two unjustified assumptions in two questions. Boot loaders need to be small and fast, which is why they are written in Forth or C. There aren't ANY boot loaders written in Python, let alone popular ones. It's quite silly to be even thinking about writing a boot loader in Python -- common hardware may require the boot loader to fit in just 64K of memory. Regular Python requires megabytes of memory just to start itself. I suppose it is just barely possible that TinyPy or Pycorn could be used, but I doubt it anyone has. > Python doesn't generate assembly language code. Pardon me, but I'm pretty sure that PyPy's JIT compiler will. Well, reasonably sure. Slightly confident. I'm guessing. :) However, I expect it only exists at runtime and you won't be able to get to it. Besides, it will be heavily optimized and ugly as sin. -- Steven From steve at pearwood.info Fri Sep 28 14:37:10 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Sep 2012 22:37:10 +1000 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: <506599F6.8050103@pearwood.info> On 28/09/12 22:15, Mark Lawrence wrote: > The Python round function is itself problematic. The idea of deprecating >it is currently being discussed on Python ideas. This quote from Calvin >Spealman is typical "Also, I'd be completely in support of dropping round() > and agree it gets misused and leads to too much confusion. We should > promote the right ways, and sometimes to show the right path you need to > lock another door and throw away the key.". Isn't that the same Calvin Spealman who wrote the blog post spreading FUD that Python was at risk of dying because, well, frankly because he was utterly ignorant of just how much Python code is written in the places where he thought no Python was written? I'm not impressed. He sprouts off about how you can't use Python on mobile devices, when you can. What makes you think his opinions on breaking working code just because he thinks he knows the "right ways" are any less ignorant? Deprecating and dropping features causes pain to developers who are already using them correctly. There is strong opposition on deprecating round. -- Steven From steve at pearwood.info Fri Sep 28 14:41:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Sep 2012 22:41:44 +1000 Subject: [Tutor] quick question In-Reply-To: References: <00f001cd9d38$a3a06660$eae13320$@gmail.com> Message-ID: <50659B08.6050005@pearwood.info> On 28/09/12 19:03, Mark Lawrence wrote: > On 28/09/2012 06:18, jh wrote: > > [snip] > >> The subtotal of your items is: 26010.850000000002 >> The total amount of your items plus tax is: 27,571.50 >> >> My question here is, why does my subtotal have so many decimals when I never >> went above 2 in my input? >> >> Thanks in advance, >> J > > Brett Ritter has already answered your question, but a web search would have >found the answer a lot faster, as this has been asked umpteen times on Python > lists alone. And I'm sure it will be asked a bazillion more times :/ > Also note that if you'd have formatted the output in the same way that you >did for the total you'd never have noticed. That's not strictly true, and by that I mean it's completely wrong :) String formatting can only hide so much. There are many ways to stumble over binary floating point issues. For example, this is using Python 3.2 which tries really hard to print a sensible float approximation for you: py> d = 1/10 py> numbers = [d]*10 py> print(numbers) [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] Here we have 0.1 repeated ten times. So if we add them, we ought to get one, right? py> total = sum(numbers) py> total == 1 False What's going on? If we look at the total, we see that it adds up to slightly *less* than the expected one: py> print(total) 0.9999999999999999 But if we print 0.1 in full precision, we see that it is slightly *greater* that 0.1 in decimal: py> print("%.17f" % d) 0.10000000000000001 So that's TWO nasty surprises (so far) with binary floating point numbers: * not all "nice" decimal numbers, like 0.1, can be stored exactly in a binary float; * and when you add ten numbers slightly greater than 0.1, the result can actually be less than 1.0 !!! Welcome to binary floating point hell. And this has nothing to do with Python, the same thing happens in *any* language with binary floats. -- Steven From wayne at waynewerner.com Fri Sep 28 15:07:21 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 28 Sep 2012 08:07:21 -0500 (CDT) Subject: [Tutor] OT: Netiquette In-Reply-To: References: <505F5908.1010304@davea.name> <5B80DD153D7D744689F57F4FB69AF474166C5626@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, 28 Sep 2012, Bod Soutar wrote: > On Sep 28, 2012 4:47 AM, "Dwight Hutto" wrote: > > Yeah, all up in my fucking cranium with nothing but me and God to hold > > on ?to one another. > > > > -- > > Best Regards, > > David Hutto > > CEO: http://www.hitwebdevelopment.com > > Probably not a good idea to advertise that your the CEO of hitwebdevelopment.com if your gonna post like that. > > Bodsda That's OK, if you don't like that sort of attitude you're obviously not in his target market (the one that enjoys was it 60MB GIF files, and background music). -W From breamoreboy at yahoo.co.uk Fri Sep 28 15:17:57 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Sep 2012 14:17:57 +0100 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: <506599F6.8050103@pearwood.info> References: <506599F6.8050103@pearwood.info> Message-ID: On 28/09/2012 13:37, Steven D'Aprano wrote: > On 28/09/12 22:15, Mark Lawrence wrote: > > > Deprecating and dropping features causes pain to developers who are already > using them correctly. There is strong opposition on deprecating round. > And there is strong support for deprecating round. Personally I'm staying out of the blood bath as I've never used it :) -- Cheers. Mark Lawrence. From md.husen at gmail.com Fri Sep 28 15:17:52 2012 From: md.husen at gmail.com (M Hussain) Date: Fri, 28 Sep 2012 15:17:52 +0200 Subject: [Tutor] list all links with certain extension in an html file Message-ID: On Fri, Sep 28, 2012 at 1:10 PM, wrote: > Date: Sun, 16 Sep 2012 12:50:09 +0530 > From: Santosh Kumar > To: tutor at python.org > Subject: [Tutor] list all links with certain extension in an html file > python > Message-ID: > < > CAE7MaQa53X8Pav96q2ka0VajHnJtRZ_rgZcmH_cbsaQDiz5GGg at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > I want to extract (no I don't want to download) all links that end in > a certain extension. > > > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > > Also I don't want to use external libraries. I am asking for: which > libraries and functions should I use? > > > do you mean, you want to parse the file and the URL of those css files, then parse the file, there are many parsing options http://lxml.de/parsing.html you don't have to use external libraries either, you may use http://docs.python.org/library/htmlparser.html or regular expressions or may be I did't understood what you really want to do. Br - Hussain -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Fri Sep 28 15:35:58 2012 From: wrw at mac.com (wrw at mac.com) Date: Fri, 28 Sep 2012 09:35:58 -0400 Subject: [Tutor] how to print array without adding newline In-Reply-To: <20120906134954.22610.qmail@server308.com> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> <20120906134954.22610.qmail@server308.com> Message-ID: <3B318FC9-6BF6-4726-95D1-CD6B327E8682@mac.com> On Sep 6, 2012, at 9:49 AM, vicki at thepenguin.org wrote: > Thank you for your reply. I understand that it is odd, but my program is being called from a hubot and returning data to it as well. I have figured out how to make the changes to get it to output the correct data in the correct format, but now I am getting a "Premature end of script headers" error. I have the correct #! line and the output from the command line shows no errors that would be interfering. Is there a way to make sure it is showing me all the errors? To increase error logging? > ------ > !/usr/bin/env python > import cloudfiles > import random > import sys > import array > > conn = cloudfiles.get_connection('username', 'key') > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html"; > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > #newlist=wholelist[:] > try: > # print sys.argv[1] > if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") > # print sys.argv[1] > del wholelist[int(sys.argv[1]):] > while i < int(sys.argv[1]): > newlist.append("http://example.com/"+wholelist[i].rstrip()) > i = i+1 > except IndexError, e: > del newlist[5] > except Exception, err: > print 'Caught an exception' > print newlist, > ------- > Vicki > Python doesn't know what to do with: !/usr/bin/env python try #!usr/bin/env python so python doesn't see it, only the the shell. -Bill From stefan_ml at behnel.de Fri Sep 28 15:59:12 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Sep 2012 15:59:12 +0200 Subject: [Tutor] list all links with certain extension in an html file python In-Reply-To: References: Message-ID: Santosh Kumar, 16.09.2012 09:20: > I want to extract (no I don't want to download) all links that end in > a certain extension. > > Suppose there is a webpage, and in the head of that webpage there are > 4 different CSS files linked to external server. Let the head look > like this: > > > > > > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > > Also I don't want to use external libraries. That's too bad because lxml.html would make this really easy. See the iterlinks() method here: http://lxml.de/lxmlhtml.html#working-with-links Note this this also handles links in embedded CSS code etc., although you might not be interested in that, if the example above is representative for your task. Stefan From eryksun at gmail.com Fri Sep 28 16:38:02 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 28 Sep 2012 10:38:02 -0400 Subject: [Tutor] lazily decorated sort In-Reply-To: References: Message-ID: On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten <__peter__ at web.de> wrote: > > def make_key(keys): > @total_ordering > class Key(object): > def __init__(self, value): > self._keys = keys(value) > self._cached = [] Using a generator/iterator to pump the key values into a cache is a great idea. But I think it would generally be nicer to let "keys" be a sequence of functions. Then define the generator in make_key() before you define the class: def make_key(keys): def _keys(value): for key in keys: yield key(value) @total_ordering class Key(object): def __init__(self, value): self._keys = _keys(value) self._cached = [] Also, as far as I can see in the code, implementing "total_ordering" is unnecessary for sorting. One only needs to implement __lt__. It's used by binarysort() to test the pivot via the IFLT/ISLT macros: http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 > def __lt__(self, other): > for a, b in izip(self.keys(), other.keys()): > if a == b: > pass > else: > return a < b > return False Or test for "!=": def __lt__(self, other): for a, b in izip(self.keys(), other.keys()): if a != b: return a < b return False From ramit.prasad at jpmorgan.com Fri Sep 28 16:43:35 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 28 Sep 2012 14:43:35 +0000 Subject: [Tutor] how to save text or dat file using python In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166CC7A3@SCACMX008.exchad.jpmchase.net> Preeti Gaikwad wrote: > ? Hello I am new user of python pls let me know how to save dat or txt file > using python? what is the basic cmd for this? thanks a lot in advance Try reading: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emile at fenx.com Fri Sep 28 18:29:52 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 28 Sep 2012 09:29:52 -0700 Subject: [Tutor] Python for Absolute Beginners In-Reply-To: <1133DD8F960C48D1A6632C0A0A05F76C@DebbiePC> References: <1133DD8F960C48D1A6632C0A0A05F76C@DebbiePC> Message-ID: On 9/27/2012 9:42 AM Debbie Snowdon said... > Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access > the Companion Guide. Do I need it? Do I have to purchase it? How do I > get it? The site he sends me to is very confusing. I'd ask your instructor or look in the book to see if the author has provided contact info. HTH. Emile From bgailer at gmail.com Fri Sep 28 18:34:32 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 28 Sep 2012 12:34:32 -0400 Subject: [Tutor] Translate PHP to Python In-Reply-To: References: Message-ID: <5065D198.4090602@gmail.com> As Mark pointed out - a better subject would help. I have changed it this time. On 9/17/2012 3:21 PM, Fation Beqirllari wrote: > I have a php code and I want to translate it to python..Can you help me > > please,or show me how to do it ? In what context do you run the PHP? A web server responding to a request, or standalone? If it is web server responding to a request then you might consider using a Python based web framework. Why do you want to translate it to Python? Which version of Python? How much expertise do you have in Python coding? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Sep 28 20:17:07 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Sep 2012 19:17:07 +0100 Subject: [Tutor] python new window In-Reply-To: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> References: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> Message-ID: On 11/09/12 22:18, zack dunphey wrote: > I have used python a lot at school and am relatively good with it. > I just tried to get it on my mac and i try to open a "new window" OK, Python doesn't have any windows so you must be talking about some kind of add-on tool - like IDLE maybe? If so please be specific about which tool, which python version, which OS (MacOSX here I assume) and exactly what you did - which menu, command key etc you used. > I have been able to get into a "new window" through programs > i saved on a jump drive at school and brought home Again using which OS, which python version, which tool? > but every time i try to do anything from that window it freezes. Which Window? > i tried re downloading it but that didn't help. What exactly are you downloading? How are you installing it? And how are you running it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Sep 28 20:23:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Sep 2012 19:23:39 +0100 Subject: [Tutor] Just flushed the moderation queue Message-ID: I'm just back from 2 weeks vacation and catching up on mail etc. I flushed the python tutor mail queue earlier hence the proliferation of messages some of which may be duplicates of stuff already seen... enjoy, -- Alan G List moderator. From tahir.hafiz at gmail.com Fri Sep 28 20:35:28 2012 From: tahir.hafiz at gmail.com (Tahir Hafiz) Date: Fri, 28 Sep 2012 19:35:28 +0100 Subject: [Tutor] python new window In-Reply-To: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> References: <28EBE210-A4EE-4189-B270-7932431AFFFA@sbcglobal.net> Message-ID: On Tue, Sep 11, 2012 at 10:18 PM, zack dunphey wrote: > I have used python a lot at school and am relatively good with it. I just > tried to get it on my mac and i try to open a "new window" and every time I > do it freezes and i have to either do a forced quit or unplug the whole > computer. I have been able to get into a "new window" through programs i > saved on a jump drive at school and brought home but every time i try to do > anything from that window it freezes. i tried re downloading it but that > didn't help. > can some one please help me > zack dunphey > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi Zac, Mac OS X comes with python already installed - just open a 'Terminal' and type python. In a Windows environment you have to install Python (or perhaps run it from a flash drive) but in Mac OS X Python comes as part of the system so you don't need to mess around downloading it and trying to install it. Hope that helps, Tahir -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Fri Sep 28 20:48:51 2012 From: sdragon1984 at gmail.com (Nathan) Date: Fri, 28 Sep 2012 14:48:51 -0400 Subject: [Tutor] Python for Absolute Beginners In-Reply-To: <1133DD8F960C48D1A6632C0A0A05F76C@DebbiePC> References: <1133DD8F960C48D1A6632C0A0A05F76C@DebbiePC> Message-ID: Which edition do you have? My copy mentions nothing about a companion guide, so my guess is that you don't need it. That said, my copy also doesn't send me to any sites for the exercises. Everything I need is right in the book. On Sep 28, 2012 7:30 AM, "Debbie Snowdon" wrote: > ** > Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access > the Companion Guide. Do I need it? Do I have to purchase it? How do I get > it? The site he sends me to is very confusing. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Sep 28 21:34:55 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Sep 2012 21:34:55 +0200 Subject: [Tutor] lazily decorated sort References: Message-ID: eryksun wrote: > On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten <__peter__ at web.de> wrote: >> >> def make_key(keys): >> @total_ordering >> class Key(object): >> def __init__(self, value): >> self._keys = keys(value) >> self._cached = [] > > > Using a generator/iterator to pump the key values into a cache is a > great idea. But I think it would generally be nicer to let "keys" be a > sequence of functions. Then define the generator in make_key() before > you define the class: I should have mentioned that make_key() may be used as a decorator. So it is @make_key def key(value): yield value yield f(value) yield value.attrib items.sorted(key=key) against (assuming the signature make_key(*keyfuncs)) items.sort(key=make_key( lambda value: value, f, operator.itemgetter("attrib")) ) I think the first version looks a bit cleaner, but that's a matter of taste. > Also, as far as I can see in the code, implementing "total_ordering" > is unnecessary for sorting. One only needs to implement __lt__. It's > used by binarysort() to test the pivot via the IFLT/ISLT macros: > > http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 I smell danger. I really don't like having a class lying around that partially implements ordering and may fail where you least expect it. >> if a == b: >> pass >> else: >> return a < b > Or test for "!=": Yes, that was odd indeed. From jimmyapt0 at gmail.com Fri Sep 28 22:32:23 2012 From: jimmyapt0 at gmail.com (Jim Apto) Date: Fri, 28 Sep 2012 16:32:23 -0400 Subject: [Tutor] Lotka-Volterra Model Simulation Questions Message-ID: Hello folks, I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey relation) simulator. The program basically will basically have a menu that takes user input, collect data, and then create a graph. Currently i've been working on the simulator section; I can't seem to get the lists right. I've assigned the following variables and parameters to the model for the program: x represents prey population y represents predator population dy/dt and dx/dt represents growth rate of the two populations over time t represents time a is the growth rate of prey b is the rate at which predators kill prey g is the death rate of predators d is the rate at which the predators population increases by consuming prey The equation: dx/dt = x(a-by) dy/dt = -y(g-dx) The code I have for this section is: def deltaX(a,b,x,y): dx = x*(a-b*y) def deltaY(g,d,x,y): dy = -y*(g-d*x) The simulation function is where I am having trouble. For the simulation function, I need to ask the user for the number of runs and then save it in a variable, create a list for prey and predator. For each run, i need to calculate the increment of change in prey and predator populations by calling the deltaX and deltaY functions, then save these in a variable, and then update the population information. The newly calculated populations then need to be added to the existing lists. After this is completed, a function for the graph is called. The following is my current simulation function: def simulation(): a=eval(input("Growth rate of prey:")) b=eval(input("Rate at which predators eat prey:")) g=eval(input("Death rate of predators:")) d=eval(input("Rate at which predators increase by consuming prey:")) x=eval(input("Current prey population:")) y=eval(input("Current predator population:")) deltaX(a,b,x,y) deltaY(g,d,x,y) n=eval(input("Number of runs:") r = 0 count=0 yList = [0] while r <= n: r = r + 1 count = count + 1 yList.append(dx + dx) zList= [0] while r <= n: r = r + 1 count = count +1 zList.append(dy + dy) It seems terribly wrong. The following is my graph function: def drawCurve(yList,zList,n): x = pylab.arange(n) pylab.title("Foxes and Rabbits") pylab.ylabel("Number of predator (Foxes)") pylab.xlabel("\nNumber of prey (Rabbits)") pylab.plot(x, yList, 'b') pylab.plot(x, zList, 'r') pylab.legend(('Rabbits','Foxes'),loc='upper left') pylab.show() The issue i'm having is the logic in the lists. How can I create the simulation function using lists and make it perform the expected task of creating a graph? I can't seem to get the logic right. Thanks, Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Sep 28 22:50:43 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 28 Sep 2012 16:50:43 -0400 Subject: [Tutor] lazily decorated sort In-Reply-To: References: Message-ID: On Fri, Sep 28, 2012 at 3:34 PM, Peter Otten <__peter__ at web.de> wrote: > >> Also, as far as I can see in the code, implementing "total_ordering" >> is unnecessary for sorting. One only needs to implement __lt__. It's >> used by binarysort() to test the pivot via the IFLT/ISLT macros: >> >> http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 > > I smell danger. I really don't like having a class lying around that > partially implements ordering and may fail where you least expect it. I don't know; they're just utility objects used for sorting, which only cares about __lt__. On the other hand, Python 3 enforces a sanity check if you implement __eq__ without __hash__. So now you have objects that can't be used in sets or as dict keys. Not that this matters. ;) Anyway, it's not hurting. I just thought I'd make the suggestion to spare you the [small] effort of implementing __eq__ on something like this. From ramit.prasad at jpmorgan.com Fri Sep 28 23:06:20 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 28 Sep 2012 21:06:20 +0000 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474166CCF19@SCACMX008.exchad.jpmchase.net> Jim Apto wrote > Hello folks, > > I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey relation) > simulator. ?The program basically will basically have a menu that takes user input, collect data, and then > create a graph. ?Currently i've been working on the simulator section; I can't seem to get the lists right. > ?I've assigned the following variables and parameters to the model for the program: > > x represents prey population > y represents predator population > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey > b is the rate at which predators kill prey > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > ? ? dx = x*(a-b*y) > > def deltaY(g,d,x,y): > ? ? dy = -y*(g-d*x) > > The simulation function is where I am having trouble. > > For the simulation function, I need to ask the user for the number of runs and then save it in a variable, > create a list for prey and predator. ?For each run, i need to calculate the increment of change in prey and > predator populations by calling the deltaX and deltaY functions, then save these in a variable, and then update > the population information. ?The newly calculated populations then need to be added to the existing lists. > ?After this is completed, a function for the graph is called. > > The following is my current simulation function: > You posted as HTML/rich text while I recommend posting as plain text. HTML/rich text can cause the text spacing to be wrong. My comments may not apply because of incorrect indention levels. > def simulation(): > ? ? a=eval(input("Growth rate of prey:")) Usage of eval is dangerous and not recommended except for advanced users. For your purposes, you can replace eval() with either int() or float() as appropriate. > ? ? b=eval(input("Rate at which predators eat prey:")) > ? ? g=eval(input("Death rate of predators:")) > ? ? d=eval(input("Rate at which predators increase by consuming prey:")) > ? ? x=eval(input("Current prey population:")) > ? ? y=eval(input("Current predator population:")) return a,b,g,d,x,y # need to return the data from simulation() Where do you ever call simulation? > > deltaX(a,b,x,y) > deltaY(g,d,x,y) Simulation does not return anything so this should either cause a NameError or use the incorrect values. > > n=eval(input("Number of runs:") > ? ? r = 0 Why did this change indentation levels? > ? ? count=0 > ? ? yList = [0] > ? ? while r <= n: > ? ? ? ? r = r + 1 > ? ? ? ? count = count + 1 > ? ? ? ? yList.append(dx + dx) What is the point of appending dx*2? What is the point of the loop appending the same things over and over? I suspect simulation should be called in between Not to mention that, this loop can be simplified by changing it to a for loop. for _ in xrange(n): yList.append(dx + dx) Or even converted into a list comprehension. yList.extend( [ dx + dx for _ in xrange(n) ] ) count += len(yList - 1) # -1 for the original [0] Shouldn't simulation be called or at least change the values of dx? > > ? ? zList= [0] > ? ? ? ?while r <= n: > ? ? ? ?r = r + 1 > ? ? ? ?count = count +1 > ? ? ? ?zList.append(dy + dy) > > It seems terribly wrong. ?The following is my graph function: > > def drawCurve(yList,zList,n): > ? ? x = pylab.arange(n) > ? ? pylab.title("Foxes and Rabbits") > ? ? pylab.ylabel("Number of predator (Foxes)") > ? ? pylab.xlabel("\nNumber of prey ?(Rabbits)") > ? ? pylab.plot(x, yList, 'b') > ? ? pylab.plot(x, zList, 'r') > ? ? pylab.legend(('Rabbits','Foxes'),loc='upper left') > ? ? pylab.show() > > The issue i'm having is the logic in the lists. ?How can I create the simulation function using lists and make > it perform the expected task of creating a graph? ?I can't seem to get the logic right. The lack of complete code (or issues with indentation) make it difficult to give you advice on how to solve it. If you can post your code in plain text (or attach it) you will get better help. It would also help if you can create a small sample that has the minimum amount of (functioning even if logically incorrect) code that displays the problem you are facing. This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wayne at waynewerner.com Fri Sep 28 23:06:42 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 28 Sep 2012 16:06:42 -0500 (CDT) Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Fri, 28 Sep 2012, Jim Apto wrote: > Hello folks, > I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey > relation) simulator. ?The program basically will basically have a menu that takes user input, collect > data, and then create a graph. ?Currently i've been working on the simulator section; I can't seem to > get the lists right. ?I've assigned the following variables and parameters to the model for the program: I don't know anything about the Lotka-Volterra model, but I've definitely got some recommendation > x represents prey population > y represents predator population > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey > b is the rate at which predators kill prey > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > ? ? dx = x*(a-b*y) > > def deltaY(g,d,x,y): > ? ? dy = -y*(g-d*x) > > The simulation function is where I am having trouble. > > For the simulation function, I need to ask the user for the number of runs and then save it in a > variable, create a list for prey and predator. ?For each run, i need to calculate the increment of > change in prey and predator populations by calling the deltaX and deltaY functions, then save these in a > variable, and then update the population information. ?The newly calculated populations then need to be > added to the existing lists. ?After this is completed, a function for the graph is called. > > The following is my current simulation function: > > def simulation(): > ? ? a=eval(input("Growth rate of prey:")) > ? ? b=eval(input("Rate at which predators eat prey:")) > ? ? g=eval(input("Death rate of predators:")) > ? ? d=eval(input("Rate at which predators increase by consuming prey:")) > ? ? x=eval(input("Current prey population:")) > ? ? y=eval(input("Current predator population:")) > Woah! Stop that right now - eval is an *incredibly* dangerous function. If you want to convert these numbers to integer or float, there's the int() and float() function. Additionally, single letter variables are really horrible. You could do: prey_growth_rate = float(input("Growth rate of prey: ")) predator_consumption_rate = #your code here predator_death_rate = ... predator_growth_rate = ... initial_prey_population = ... initial_predator_population = ... > deltaX(a,b,x,y) > deltaY(g,d,x,y) I don't see where you defined deltaX or deltaY... > > n=eval(input("Number of runs:") > ? ? r = 0 > ? ? count=0 > ? ? yList = [0] > ? ? while r <= n: > ? ? ? ? r = r + 1 > ? ? ? ? count = count + 1 > ? ? ? ? yList.append(dx + dx) > > ? ? zList= [0] > ? ? ? ?while r <= n: > ? ? ? ?r = r + 1 > ? ? ? ?count = count +1 > ? ? ? ?zList.append(dy + dy) > > It seems terribly wrong. ?The following is my graph function: > > def drawCurve(yList,zList,n): > ? ? x = pylab.arange(n) > ? ? pylab.title("Foxes and Rabbits") > ? ? pylab.ylabel("Number of predator (Foxes)") > ? ? pylab.xlabel("\nNumber of prey ?(Rabbits)") > ? ? pylab.plot(x, yList, 'b')? > ? ? pylab.plot(x, zList, 'r') > ? ? pylab.legend(('Rabbits','Foxes'),loc='upper left') > ? ? pylab.show() > > The issue i'm having is the logic in the lists. ?How can I create the simulation function using lists > and make it perform the expected task of creating a graph? ?I can't seem to get the logic right. Posting an image of what you expect, and what you got instead to imgur or some other free hosting site would be a good thing to do. When asking a question you should always post what you wanted to happen, and what happened instead. HTH, Wayne From eryksun at gmail.com Fri Sep 28 23:07:11 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 28 Sep 2012 17:07:11 -0400 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: <506599F6.8050103@pearwood.info> Message-ID: On Fri, Sep 28, 2012 at 9:17 AM, Mark Lawrence wrote: > On 28/09/2012 13:37, Steven D'Aprano wrote: > >> Deprecating and dropping features causes pain to developers who are >> already using them correctly. There is strong opposition on deprecating >> round. > > And there is strong support for deprecating round. Personally I'm staying > out of the blood bath as I've never used it :) That would be an odd back-step since Python 3 generalized the built-in: >>> class Test: ... def __round__(self, ndigits=None): ... return 1 ... >>> round(Test()) 1 Also, float, Decimal, and Fraction in Python 3 return an int when the ndigits argument is omitted. For example, float rounds using the math lib's round function, then rounds that to even, and returns PyLong_FromDouble. Is the discussion just about removing the ndigits aspect but keeping the round-to-int aspect? From jeanpierreda at gmail.com Fri Sep 28 23:27:38 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 28 Sep 2012 17:27:38 -0400 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: <506599F6.8050103@pearwood.info> References: <506599F6.8050103@pearwood.info> Message-ID: On Fri, Sep 28, 2012 at 8:37 AM, Steven D'Aprano wrote: > On 28/09/12 22:15, Mark Lawrence wrote: > >> The Python round function is itself problematic. The idea of deprecating >> it is currently being discussed on Python ideas. This quote from Calvin >> Spealman is typical "Also, I'd be completely in support of dropping >> round() >> and agree it gets misused and leads to too much confusion. We should >> promote the right ways, and sometimes to show the right path you need to >> lock another door and throw away the key.". > > > Isn't that the same Calvin Spealman who wrote the blog post spreading FUD > that > Python was at risk of dying because, well, frankly because he was utterly > ignorant of just how much Python code is written in the places where he > thought no Python was written? > > I'm not impressed. He sprouts off about how you can't use Python on mobile > devices, when you can. What makes you think his opinions on breaking > working code just because he thinks he knows the "right ways" are any less > ignorant? I don't think the newbie mailing list is the right place to show that kind of hostility, if indeed there is a right place. -- Devin From oscar.j.benjamin at gmail.com Sat Sep 29 00:46:08 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Sep 2012 23:46:08 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On 28 September 2012 21:32, Jim Apto wrote: > Hello folks, > > I'm relatively new to python, and was asked to program a lotka-volterra > model (predator and prey relation) simulator. The program basically will > basically have a menu that takes user input, collect data, and then create > a graph. Currently i've been working on the simulator section; I can't > seem to get the lists right. I've assigned the following variables and > parameters to the model for the program: > > x represents prey population > y represents predator population > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey > b is the rate at which predators kill prey > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > dx = x*(a-b*y) > > def deltaY(g,d,x,y): > dy = -y*(g-d*x) > The normal way to program an ODE solver is to define a function that takes a vector input X and returns a vector dX/dt. The idea is that rather than keeping a separate state for x and y you keep a combined state [x, y]. This makes sense since the state of your system at any time is defined by both values. Keeping that in mind I would write a function like def derivative(Z): x, y = Z dxdt = ... dydt = ... dZdt = [dxdt, dydt] return dZdt This function uses lists of numbers to represent the state vector. You can then plug this into a function that uses a particular ODE solving algorithm: def euler(f, Z1, dt): dZdt = f(Z1) Z2 = [] for i in range(len(Z1)): Z2.append(Z1[i] + dt * dZdt[i]) return Z2 Or a shorter version: def euler(f, Z1, dt): return [z + dt * dz for z, dz in zip(Z, f(Z))] You then get the new state by plugging the old state into the euler function repeatedly, e.g.: dt = .001 Z0 = [0.5, 0.5] # Initial condition Z1 = euler(derivative, Z0, dt) Z2 = euler(derivative, Z1, dt) ... Once you can get all the simulation values you will be in a position to think about how to rearrange the lists so that you can plot them. By the way, this sort of thing is usually done with numpy (that makes a few of these things a bit easier). Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 29 03:23:38 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2012 02:23:38 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On 28/09/12 21:32, Jim Apto wrote: > I'm relatively new to python, and was asked to program a lotka-volterra > model (predator and prey relation) simulator. No idea what that means in practice but commenting purely on the code provided... > x represents prey population > y represents predator population so use names that say so, like preyPop and predatorPop Its only a few extra letters typing but makes things much more readable. > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey so call it preyGrowth? > b is the rate at which predators kill prey or killRate? you get the idea... > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > dx = x*(a-b*y) Normally you define a function such that it returns a value. Here you simply define a local variable(dx), assign a value then throw it way when the function finishes. You probably want: def deltaX(a,b,x,y): return x*(a-b*y) > def deltaY(g,d,x,y): > dy = -y*(g-d*x) same here > The simulation function is where I am having trouble. possibly because of some of the things above? > For the simulation function, I need to ask the user for the number of > runs and then save it in a variable, create a list for prey and > predator. > For each run, i need to calculate the increment of change in > prey and predator populations by calling the deltaX and deltaY > functions, then save these in a variable, and then update the population > information. > The newly calculated populations then need to be added to > the existing lists. After this is completed, a function for the graph > is called. So three basic blocks of code required? Is your function structured like that? Which blocks work? Which ones don't? Can you test (eg print) each block separately? Hint: Can each block be a function? > The following is my current simulation function: > > def simulation(): > a=eval(input("Growth rate of prey:")) > b=eval(input("Rate at which predators eat prey:")) > g=eval(input("Death rate of predators:")) > d=eval(input("Rate at which predators increase by consuming prey:")) > x=eval(input("Current prey population:")) > y=eval(input("Current predator population:")) Don't use eval.... convert types directly using int() or float() Convert the above to a standalone function getSimulationData() or somesuch that returns the validated and converted input values. Test it. > deltaX(a,b,x,y) > deltaY(g,d,x,y) Here are the calls with no return values and so have no effect. They are effectively wasted space. You need something like dx = deltaX(a,b,x,y) dy = deltaY(g,d,x,y) after adding return statements as described above. > n=eval(input("Number of runs:") > r = 0 The indentation suggests you are missing a loop structure somewhere? > count=0 > yList = [0] > while r <= n: > r = r + 1 > count = count + 1 > yList.append(dx + dx) dx does not exist as you wrote it, you need the changes above... But even then you are adding the same value (2dx) each time, is that right? > zList= [0] > while r <= n: > r = r + 1 > count = count +1 > zList.append(dy + dy) Same applies for dy. > It seems terribly wrong. Yep, I'm pretty sure it is wrong. Also I'd try putting it into a separate function, populateData() maybe? The simulate looks like: def simulate: a,b,g,d,x,y = getSimulationData() xList,YList = populateData(a,b,g,d,x,y) drawCurve(yList,xList) The following is my graph function: > > def drawCurve(yList,zList,n): > x = pylab.arange(n) > pylab.title("Foxes and Rabbits") > pylab.ylabel("Number of predator (Foxes)") > pylab.xlabel("\nNumber of prey (Rabbits)") > pylab.plot(x, yList, 'b') > pylab.plot(x, zList, 'r') > pylab.legend(('Rabbits','Foxes'),loc='upper left') > pylab.show() I don't use pyLab so will assume that is all OK... > The issue i'm having is the logic in the lists. The biggest issue is the naming and location of your variables and how you assign values to them (via returns from functions). Fix that first and things will start to improve. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Sat Sep 29 03:29:27 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 29 Sep 2012 02:29:27 +0100 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: <506599F6.8050103@pearwood.info> Message-ID: On 28/09/2012 22:07, eryksun wrote: > On Fri, Sep 28, 2012 at 9:17 AM, Mark Lawrence wrote: >> On 28/09/2012 13:37, Steven D'Aprano wrote: >> >>> Deprecating and dropping features causes pain to developers who are >>> already using them correctly. There is strong opposition on deprecating >>> round. >> >> And there is strong support for deprecating round. Personally I'm staying >> out of the blood bath as I've never used it :) > > That would be an odd back-step since Python 3 generalized the built-in: > > >>> class Test: > ... def __round__(self, ndigits=None): > ... return 1 > ... > >>> round(Test()) > 1 > > Also, float, Decimal, and Fraction in Python 3 return an int when the > ndigits argument is omitted. For example, float rounds using the math > lib's round function, then rounds that to even, and returns > PyLong_FromDouble. Is the discussion just about removing the ndigits > aspect but keeping the round-to-int aspect? I don't have figures (ouch :) but some people appear to support complete deprecation, some leaving the status quo and some removing the ndigits aspect as you have asked. Also remember that the idea is only being floated (double ouch:) on Python ideas so anything could happen. Don't watch this space!!! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Sat Sep 29 03:30:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2012 02:30:26 +0100 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: On 28/09/12 13:15, Mark Lawrence wrote: > from Calvin Spealman is typical "Also, I'd be completely in support of > dropping round() and agree it gets misused > and leads to too much confusion. We should promote the right ways, and > sometimes to show the right path you need to lock another door and throw > away the key.". As a matter of interest what is the "right path" that is being proposed? If it takes much more than 7 keypresses then I suspect it will be opposed! (I'm too lazy to look up the thread myself! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sat Sep 29 04:09:53 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 28 Sep 2012 22:09:53 -0400 Subject: [Tutor] Translate PHP to Python In-Reply-To: <000901cd9d99$badcebd0$3096c370$@com> References: <5065D198.4090602@gmail.com> <000901cd9d99$badcebd0$3096c370$@com> Message-ID: <50665871.2030703@gmail.com> On 9/28/2012 12:52 PM, Fation Beqirllari wrote: > > This php is for map cache,it reads cache file created,but im creating > all the web server to python because it works faster..I use this for > openlayers web server. > > I run Python 3.2.if you want to help me..i will send te php > code..thank you! > Thanks for the information. Please always reply-all so a copy goes to the list. I will cc this for that purpose. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Sep 29 05:02:56 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Sep 2012 13:02:56 +1000 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: Message-ID: <506664E0.4010408@pearwood.info> On 29/09/12 11:30, Alan Gauld wrote: > On 28/09/12 13:15, Mark Lawrence wrote: > >> from Calvin Spealman is typical "Also, I'd be completely in support of >> dropping round() and agree it gets misused >> and leads to too much confusion. We should promote the right ways, and >> sometimes to show the right path you need to lock another door and throw >> away the key.". > > As a matter of interest what is the "right path" that is being proposed? > If it takes much more than 7 keypresses then I suspect it will be opposed! >(I'm too lazy to look up the thread myself! :-) It is already opposed because it breaks existing, working code unnecessarily. The replacements suggested are: - use Decimal values, and round them instead; - use string formatting Neither suggestion has really thought things through clearly. The first has identified the problem correctly -- it is *binary floats*, not round, which causes the problem, but to round a Decimal you need the round built-in (or at least a replacement): py> from decimal import Decimal as D py> x = D('2.123456') py> x.round Traceback (most recent call last): File "", line 1, in AttributeError: 'Decimal' object has no attribute 'round' py> round(x, 3) Decimal('2.123') The second is, well, poorly thought out. Here is an example of the sort of thing where round can give funny results. You expect that on half-way cases, it should round to the nearest EVEN number: # as expected py> round(1.125, 2) 1.12 py> round(1.135, 2) 1.14 # but unexpected py> round(2.675, 2) 2.67 Why? Because 2.675 is not actually a half-way case, it is actually a binary float a tiny bit under the decimal 2.675: py> print("%.17f" % 2.675) 2.67499999999999982 Fair enough. So let's try the recommended solution: py> "%.2f" % 2.675 '2.67' Wait, that gives the same result as rounding. So how is this better? -- Steven From steve at pearwood.info Sat Sep 29 05:35:01 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Sep 2012 13:35:01 +1000 Subject: [Tutor] floating point rounding inconsistency In-Reply-To: References: <506599F6.8050103@pearwood.info> Message-ID: <50666C65.1010307@pearwood.info> On 29/09/12 07:27, Devin Jeanpierre wrote: > On Fri, Sep 28, 2012 at 8:37 AM, Steven D'Aprano wrote: [...] >> I'm not impressed. He sprouts off about how you can't use Python on mobile >> devices, when you can. What makes you think his opinions on breaking >> working code just because he thinks he knows the "right ways" are any less >> ignorant? > > I don't think the newbie mailing list is the right place to show that > kind of hostility, if indeed there is a right place. Did I break some unwritten law? "Thou shall not puncture newbie's illusion that all Python users and developers are part of one great big happy family where everyone agrees with everyone else all the time." I think that Calvin's blog post was FUD. It may have been genuinely held, and not intentionally FUD, but the comments on his blog demonstrate that he was out of touch of the state of Python in at least one of the areas he was most concerned about. I think his argument against round(x, n) is equally ignorant and wrong-headed. I'm sorry that you consider this frank expression of my opinion to be hostility. -- Steven From oscar.j.benjamin at gmail.com Sat Sep 29 10:41:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 29 Sep 2012 09:41:06 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Sep 29, 2012 2:25 AM, "Alan Gauld" wrote: > > On 28/09/12 21:32, Jim Apto wrote: > >> I'm relatively new to python, and was asked to program a lotka-volterra >> model (predator and prey relation) simulator. > > > No idea what that means in practice but commenting purely on the code provided... > > >> x represents prey population >> y represents predator population > > > so use names that say so, like preyPop and predatorPop > Its only a few extra letters typing but makes things much more readable. As a mathematician I'd have to disagree with you there Alan. This model already has an established notation: http://en.m.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equation -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Sat Sep 29 10:56:07 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 29 Sep 2012 09:56:07 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Sep 29, 2012 9:41 AM, "Oscar Benjamin" wrote: > > > On Sep 29, 2012 2:25 AM, "Alan Gauld" wrote: > > > > On 28/09/12 21:32, Jim Apto wrote: > > > >> I'm relatively new to python, and was asked to program a lotka-volterra > >> model (predator and prey relation) simulator. > > > > > > No idea what that means in practice but commenting purely on the code provided... > > > > > >> x represents prey population > >> y represents predator population > > > > > > so use names that say so, like preyPop and predatorPop > > Its only a few extra letters typing but makes things much more readable. > > As a mathematician I'd have to disagree with you there Alan. This model already has an established notation: > http://en.m.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equation Accidentally sent that prematurely. I meant to say that changing the notation will only lead to confusion. Also there are good reasons for using short names in equations. It makes it much easier to see the whole equation at once, which makes it easier to understand the equations and easier to check your code. If you make the variable names too long, even simple equations like these will have to split over several lines and be more difficult to read/check. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 29 11:16:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2012 10:16:40 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On 29/09/12 09:41, Oscar Benjamin wrote: > > so use names that say so, like preyPop and predatorPop > > Its only a few extra letters typing but makes things much more readable. > > As a mathematician I'd have to disagree with you there Alan. This model > already has an established notation: I did say I had no idea about the original algorithm so yes, if the variable names are industry standardised and the people working with the code are familiar with them then it may be better to stick with them, even if nobody else on the planet understands the resultant code. As to using short names to keep things on a single line, there is a huge body of research in Comp Science that shows that meaningful names outweigh single line expressions every time in terms of reliability, comprehension, ease of maintenance etc. Of course we shouldn't go overboard but keeping to a single line is not a good reason, on its own, to use single char variable names. Industry standards however may be... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Sep 29 12:42:10 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Sep 2012 20:42:10 +1000 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: <5066D082.7050301@pearwood.info> On 29/09/12 19:16, Alan Gauld wrote: > On 29/09/12 09:41, Oscar Benjamin wrote: > >> > so use names that say so, like preyPop and predatorPop >> > Its only a few extra letters typing but makes things much more readable. >> >> As a mathematician I'd have to disagree with you there Alan. This model >> already has an established notation: > > I did say I had no idea about the original algorithm so yes, if the >variable names are industry standardised and the people working with the > code are familiar with them then it may be better to stick with them, > even if nobody else on the planet understands the resultant code. :) One advantage of using single-letter names in a function when the rest of your module uses descriptive names is that it immediately screams "mathematical formula". If that means the programmer seeks help from an expert sooner, that's a good thing :) > As to using short names to keep things on a single line, there is a huge >body of research in Comp Science that shows that meaningful names outweigh >single line expressions every time in terms of reliability, comprehension, >ease of maintenance etc. Yes, but "meaningful names" is relative to the reader, and depends on their familiarity with the topic on hand. To *some* degree, you can overcome a lack of familiarity with longer, more descriptive names, but that soon becomes painful and even unreadable. To a mathematician, "pi" or "?" is meaningful, and "constant_ratio_of_diameter_to_circumference" would be much harder to read. To a physicist, the names "E", "p", "m", "c", "e", "v", "a", etc. are all meaningful, and while it wouldn't hurt *that* much to write them as "energy", "momentum", "rest_mass", "speed_of_light", "charge_on_the_electron", "velocity", "acceleration" that soon gets tedious and frankly it doesn't help that much. If somebody doesn't understand: p = m*v*(1-(c/v)**2)**-0.5 they aren't likely to be much enlightened by: momentum = rest_mass*velocity*(1-(speed_of_light/velocity)**2)**-0.5 and of course, the longer names aren't likely to help the programmer find the bug in the expression if he doesn't know the subject well. Meaningful names are vital. But short names, even single letters, are not necessarily less meaningful than longer, more descriptive names. -- Steven From breamoreboy at yahoo.co.uk Sat Sep 29 13:13:41 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 29 Sep 2012 12:13:41 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: <5066D082.7050301@pearwood.info> References: <5066D082.7050301@pearwood.info> Message-ID: On 29/09/2012 11:42, Steven D'Aprano wrote: > On 29/09/12 19:16, Alan Gauld wrote: >> On 29/09/12 09:41, Oscar Benjamin wrote: > > Meaningful names are vital. But short names, even single letters, are not > necessarily less meaningful than longer, more descriptive names. > I suspect that every experienced programmer has worked on a project where naming standards are enforced so you end up with aVeryLongPackageNameAVeryLongModuleNameI. IMHO as useful as a chocolate teapot. -- Cheers. Mark Lawrence. From oscar.j.benjamin at gmail.com Sat Sep 29 15:24:24 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 29 Sep 2012 14:24:24 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: <5066D082.7050301@pearwood.info> References: <5066D082.7050301@pearwood.info> Message-ID: On Sep 29, 2012 11:52 AM, "Steven D'Aprano" wrote: > > On 29/09/12 19:16, Alan Gauld wrote: >> >> As to using short names to keep things on a single line, there is a huge >> body of research in Comp Science that shows that meaningful names outweigh >> single line expressions every time in terms of reliability, comprehension, >> ease of maintenance etc. > > If somebody doesn't understand: > > p = m*v*(1-(c/v)**2)**-0.5 It should be v/c not c/v. To give some relevance to this otherwise pedantic post I'll say that I find it much easier to spot the mistake in the line above than the line below. This is precisely because the line above resembles the way the equation would normally be written in a book or on the blackboard etc. > > they aren't likely to be much enlightened by: > > momentum = rest_mass*velocity*(1-(speed_of_light/velocity)**2)**-0.5 > Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Sat Sep 29 16:08:51 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 29 Sep 2012 09:08:51 -0500 (CDT) Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Sat, 29 Sep 2012, Oscar Benjamin wrote: > On Sep 29, 2012 2:25 AM, "Alan Gauld" wrote: > > > > On 28/09/12 21:32, Jim Apto wrote: > > > >> I'm relatively new to python, and was asked to program a lotka-volterra > >> model (predator and prey relation) simulator. > > > > > >> x represents prey population > >> y represents predator population > > > > > > so use names that say so, like preyPop and predatorPop > > Its only a few extra letters typing but makes things much more readable. > > As a mathematician I'd have to disagree with you there Alan. This model > already has an established notation: Regardless of established notation, unless only mathematicians will be reading the code, and only those intimately familiar with the equation, it makes much more sense to use meaningful names. Because that way, when sending the code to a mailing list full of non-mathematician programmers, they'll know exactly what the variables are supposed to be for, so they wont have to look anything up on wikipedia. After all, they've got a finite amount of volunteer time, and would you prefer to get more advice about logic errors, or the guarenteed responses about variable names? I for one, prefer to get the most value from my question as possible. It shows respect to the people I'm asking, and to everything else that they could possibly be spending their time on, including answering other questions. Respectfully-and-somewhat-tongue-in-cheekily, Wayne From wayne at waynewerner.com Sat Sep 29 16:39:52 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 29 Sep 2012 09:39:52 -0500 (CDT) Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Sat, 29 Sep 2012, Wayne Werner wrote: > On Sat, 29 Sep 2012, Oscar Benjamin wrote: >> On Sep 29, 2012 2:25 AM, "Alan Gauld" wrote: >> > >> > On 28/09/12 21:32, Jim Apto wrote: >> > >> >> I'm relatively new to python, and was asked to program a lotka-volterra >> >> model (predator and prey relation) simulator. >> > >> > >> >> x represents prey population >> >> y represents predator population >> > >> > >> > so use names that say so, like preyPop and predatorPop >> > Its only a few extra letters typing but makes things much more readable. >> >> As a mathematician I'd have to disagree with you there Alan. This model >> already has an established notation: > > Regardless of established notation, unless only mathematicians will be > reading > the code, and only those intimately familiar with the equation, it makes much > more sense to use meaningful names. And lest I sound like I'm completely ignoring the mathematical aspect - what *does* make sense to do is this: x = prey_popluation y = pred_population # insert mathematical formula here. This satesfies all parties: 1) It gives us programmers nice, meaningful names 2) It gives mathematicians the formula that screams "FORMULA!" 3) It clearly separates the math-y bits from the program-y bits. Because let's face it, x = float(input("Starting Prey Population: ")) isn't exactly something you find in (most) math classes. And I think clearly separating concerns is always a good thing. -Wayne From fomcl at yahoo.com Sat Sep 29 22:15:29 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 29 Sep 2012 13:15:29 -0700 (PDT) Subject: [Tutor] generic repr method? Message-ID: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> Hi, I've written a __repr__ method that is supposed to *always* work. That is, it returns an eval-able text representation of any class instance. Will this really always work? I'd find it useful is this is standard behavior of Python. Or am I overlooking something? import inspect class X (object): ??? def __init__(self, x=1, y='n'): ??????? self.x = x ??????? self.y = y ??? def __repr__(self):??? ??? ??? ??????? code = self.__class__.__name__ + "(" ??????? for arg in inspect.getargspec(self.__init__).args [1:]? : ??????????? if isinstance(eval("self." + arg), basestring): ??????????????? code += ("%(" + arg + ")r, ") ??????????? else: ??????????????? code += ("%(" + arg + ")s, ") ??????? code = code[:-2] + ")" ??????? return code % self.__dict__ x = X() eval(repr(x)) ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From oscar.j.benjamin at gmail.com Sat Sep 29 23:20:46 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 29 Sep 2012 22:20:46 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On 28 September 2012 21:32, Jim Apto wrote: > Hello folks, > > I'm relatively new to python, and was asked to program a lotka-volterra > model (predator and prey relation) simulator. The program basically will > basically have a menu that takes user input, collect data, and then create > a graph. Currently i've been working on the simulator section; I can't > seem to get the lists right. > Jim, I apologise if the responses to your original post seem to have gotten distracted from the problems you're having. Also I'm sorry if my first post was a bit abstract. Have the responses so far been helpful? Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Sep 29 23:57:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2012 22:57:09 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: <5066D082.7050301@pearwood.info> References: <5066D082.7050301@pearwood.info> Message-ID: On 29/09/12 11:42, Steven D'Aprano wrote: > On 29/09/12 19:16, Alan Gauld wrote: >> I did say I had no idea about the original algorithm so yes, if the >> variable names are industry standardised and the people working with the >> code are familiar with them then it may be better to stick with them, > >> As to using short names to keep things on a single line, there is a huge >> body of research in Comp Science that shows that meaningful names >> outweigh single line expressions every time in terms of... > Yes, but "meaningful names" is relative to the reader, Absolutely, see the first para above. This latter comment was explicitly in response to the snipped (by me) context: "Also there are good reasons for using short names in equations. It makes it much easier to see the whole equation at once, which makes it easier to understand the equations and easier to check your code. If you make the variable names too long, even simple equations like these will have to split over several lines and be more difficult to read/check." > To a mathematician, "pi" or "?" is meaningful, and > "constant_ratio_of_diameter_to_circumference" would be much harder to read. Totally agree. My point is that we should not choose short names just to keep an expression on a single line. The evidence suggests that the advantages of longer names outweigh the advantage of a single line. But in the cases here where single letters evidently have expressive power in their own right the familiar term is preferable over a longer descriptive name. Of course, care is needed when splitting an expression over multi lines to keep the readability so if the terms can be naturally split by operator then that's the place to split them. But this is the same in written math too. (Most of the equations I remember reading from my quantum mechanics days were split over at least 3 lines... trying to force them into a single line would not have made them any more palatable!) > p = m*v*(1-(c/v)**2)**-0.5 > > they aren't likely to be much enlightened by: > > momentum = rest_mass*velocity*(1-(speed_of_light/velocity)**2)**-0.5 I'm slightly less convinced by that. I rarely learned Physics formulae by wrote because I could usually work them out from first principles easily enough. So knowing what the variables represent would help me more than an equation of single letters if it was an equation I hadn't seen before. But where it is an industry standard equation using industry standard symbols then for sure, stick to the standard. > and of course, the longer names aren't likely to help the programmer find > the bug in the expression if he doesn't know the subject well. Agreed, but if he knows the subject area but not the specific algorithm it might help (again assuming standard symbology is used appropriately). > Meaningful names are vital. But short names, even single letters, are not > necessarily less meaningful than longer, more descriptive names. Absolutely. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Sun Sep 30 00:57:38 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 29 Sep 2012 23:57:38 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: On 29 September 2012 22:57, Alan Gauld wrote: > On 29/09/12 11:42, Steven D'Aprano wrote: > >> On 29/09/12 19:16, Alan Gauld wrote: >> > Totally agree. > My point is that we should not choose short names just to keep an > expression on a single line. The evidence suggests that the advantages of > longer names outweigh the advantage of a single line. But in the cases here > where single letters evidently have expressive power in their own right the > familiar term is preferable over a longer descriptive name. > > Of course, care is needed when splitting an expression over multi lines > to keep the readability so if the terms can be naturally split by operator > then that's the place to split them. But this is the same in written math > too. (Most of the equations I remember reading from my quantum mechanics > days were split over at least 3 lines... trying to force them into a single > line would not have made them any more palatable!) I wouldn't advocate forcing an equation onto a single line if it doesn't fit on a single line. However, I'm sure that the equations you're refering to would have already been using lots of symbols described by very succinct single-greek/latin-letters and other simple glyphs. Naturally, these equations would not be meaningful to someone lacking prior experience of quantum mechanics. Now imagine replacing each of those single letter symbols with English underscore-separated words so instead of letter capital psi you would have 'time_dependent_wave_function' and instead of hbar you would have 'planks_constant_over_twopi' and so on. Your equation would go from three lines to thirty and noone would be able to understand it *even if they were familiar with the subject*. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Sun Sep 30 01:09:41 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 29 Sep 2012 16:09:41 -0700 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On Sat, Sep 29, 2012 at 2:16 AM, Alan Gauld wrote: > As to using short names to keep things on a single line, there is a huge > body of research in Comp Science that shows that meaningful names outweigh > single line expressions every time in terms of reliability, comprehension, > ease of maintenance etc. With the nod to what exactly is meaningful vs noise, I'm in subjective agreement. Can you point to any of the research you mention? I'd like to read into to see how my personal experience equates with the overall study - I might learn something! One point of curiousity for me: in Perl there was a attempt a decade ago to promote a change in how hashes (dicts) were named to better match their usage (that is, rather than having a hash named for the collection, e.g. %addresses, have your hash named to match the singular usage: %address_of, which leads to $address_of{$student} ). No idea if that caught on or not, as I spent a few years trapped in Java, where the trend is to disguise everything in a mass of Verbed Nouns. Googling coughed up this link ( http://infoscience.epfl.ch/record/138586?ln=en&of=HD ), but I'm awash in results about general discussions of variables in research rather than studies about programming variable names (my google-fu is weak) -- Brett Ritter / SwiftOne swiftone at swiftone.org From oscar.j.benjamin at gmail.com Sun Sep 30 01:16:48 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 30 Sep 2012 00:16:48 +0100 Subject: [Tutor] generic repr method? In-Reply-To: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> References: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> Message-ID: On 29 September 2012 21:15, Albert-Jan Roskam wrote: > Hi, > > I've written a __repr__ method that is supposed to *always* work. That is, > it returns an eval-able text representation of any class instance. > Will this really always work? No. > I'd find it useful is this is standard behavior of Python. Or am I > overlooking something? > Yes. > > > import inspect > > class X (object): > > def __init__(self, x=1, y='n'): > self.x = x > self.y = y > > def __repr__(self): > code = self.__class__.__name__ + "(" > for arg in inspect.getargspec(self.__init__).args [1:] : > if isinstance(eval("self." + arg), basestring): > I'd prefer getattr(self, arg) to eval("self." + arg). > code += ("%(" + arg + ")r, ") > else: > code += ("%(" + arg + ")s, ") > code = code[:-2] + ")" > return code % self.__dict__ > > x = X() > eval(repr(x)) > This repr method assumes that every argument to __init__ is stored as an attribute with the same name as the parameter to __init__. Consider: def __init__(self, name): self.other_name = name Also how do you handle: def __init__(self, *args, **kwargs): Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sun Sep 30 01:46:56 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 29 Sep 2012 19:46:56 -0400 Subject: [Tutor] generic repr method? In-Reply-To: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> References: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> Message-ID: On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam wrote: > > def __repr__(self): > code = self.__class__.__name__ + "(" > for arg in inspect.getargspec(self.__init__).args [1:] : > if isinstance(eval("self." + arg), basestring): > code += ("%(" + arg + ")r, ") > else: > code += ("%(" + arg + ")s, ") > code = code[:-2] + ")" > return code % self.__dict__ __init__ could use *args and **kwds. Keyword-only arguments in Python 3 require using inspect.getfullargspec. A class with __slots__ probably lacks a __dict__. Use the repr of all values. The current value of an attribute isn't necessarily the value needed for initialization, nor do all initialization arguments necessarily map to attributes. So you can't expect a general-purpose __repr__ to capture everything that's needed to recreate the object. It's nice to try for this, but not necessary. It is important, however, to include information relevant for debugging: http://docs.python.org/py3k/reference/datamodel.html#object.__repr__ Also see: http://docs.python.org/py3k/library/copy http://docs.python.org/py3k/library/pickle.html#pickling-class-instances From eryksun at gmail.com Sun Sep 30 01:50:51 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 29 Sep 2012 19:50:51 -0400 Subject: [Tutor] generic repr method? In-Reply-To: References: <1348949729.97991.YahooMailNeo@web110705.mail.gq1.yahoo.com> Message-ID: On Sat, Sep 29, 2012 at 7:46 PM, eryksun wrote: > > A class with __slots__ probably lacks a __dict__. That didn't come out clearly. I meant *instances* of a class that defines __slots__. From malcolm.newsome at gmail.com Sun Sep 30 02:36:52 2012 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Sat, 29 Sep 2012 19:36:52 -0500 Subject: [Tutor] Apprenticeships In-Reply-To: References: Message-ID: <50679424.5020204@gmail.com> Hey group, I have a bit of a non-technical question. I've seen quite a bit recently about the rise of software apprenticeships. As a self-taught developer, this looks quite appealing for a number of reasons. I'm wondering if anyone in the group knows of any apprenticeships (or, if not a formal apprenticeship, a shop that's looking for a very self-motivated Junior Dev that is quite eager to learn, contribute, and be mentored). I apologize if this is an improper request for this forum. Many thanks in advance! Malcolm Newsome malcolm.newsome at gmail.com On 09/29/2012 06:16 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 > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Lotka-Volterra Model Simulation Questions (Oscar Benjamin) > 2. Re: Lotka-Volterra Model Simulation Questions (Alan Gauld) > 3. Re: Lotka-Volterra Model Simulation Questions (Oscar Benjamin) > 4. Re: Lotka-Volterra Model Simulation Questions (Brett Ritter) > 5. Re: generic repr method? (Oscar Benjamin) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 29 Sep 2012 22:20:46 +0100 > From: Oscar Benjamin > To: Jim Apto > Cc: tutor at python.org > Subject: Re: [Tutor] Lotka-Volterra Model Simulation Questions > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On 28 September 2012 21:32, Jim Apto wrote: > >> Hello folks, >> >> I'm relatively new to python, and was asked to program a lotka-volterra >> model (predator and prey relation) simulator. The program basically will >> basically have a menu that takes user input, collect data, and then create >> a graph. Currently i've been working on the simulator section; I can't >> seem to get the lists right. >> > Jim, I apologise if the responses to your original post seem to have gotten > distracted from the problems you're having. Also I'm sorry if my first post > was a bit abstract. > > Have the responses so far been helpful? > > Oscar > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Sat, 29 Sep 2012 22:57:09 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Lotka-Volterra Model Simulation Questions > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 29/09/12 11:42, Steven D'Aprano wrote: >> On 29/09/12 19:16, Alan Gauld wrote: >>> I did say I had no idea about the original algorithm so yes, if the >>> variable names are industry standardised and the people working with the >>> code are familiar with them then it may be better to stick with them, >>> As to using short names to keep things on a single line, there is a huge >>> body of research in Comp Science that shows that meaningful names >>> outweigh single line expressions every time in terms of... >> Yes, but "meaningful names" is relative to the reader, > Absolutely, see the first para above. This latter comment was explicitly > in response to the snipped (by me) context: > > "Also there are good reasons for using short names in equations. It > makes it much easier to see the whole equation at once, which makes it > easier to understand the equations and easier to check your code. If you > make the variable names too long, even simple equations like these will > have to split over several lines and be more difficult to read/check." > >> To a mathematician, "pi" or "?" is meaningful, and >> "constant_ratio_of_diameter_to_circumference" would be much harder to read. > Totally agree. > My point is that we should not choose short names just to keep an > expression on a single line. The evidence suggests that the advantages > of longer names outweigh the advantage of a single line. But in the > cases here where single letters evidently have expressive power in their > own right the familiar term is preferable over a longer descriptive name. > > Of course, care is needed when splitting an expression over multi lines > to keep the readability so if the terms can be naturally split by > operator then that's the place to split them. But this is the same in > written math too. (Most of the equations I remember reading from my > quantum mechanics days were split over at least 3 lines... trying to > force them into a single line would not have made them any more palatable!) > >> p = m*v*(1-(c/v)**2)**-0.5 >> >> they aren't likely to be much enlightened by: >> >> momentum = rest_mass*velocity*(1-(speed_of_light/velocity)**2)**-0.5 > I'm slightly less convinced by that. I rarely learned Physics formulae > by wrote because I could usually work them out from first principles > easily enough. So knowing what the variables represent would help me > more than an equation of single letters if it was an equation I hadn't > seen before. But where it is an industry standard equation using > industry standard symbols then for sure, stick to the standard. > >> and of course, the longer names aren't likely to help the programmer find >> the bug in the expression if he doesn't know the subject well. > Agreed, but if he knows the subject area but not the specific algorithm > it might help (again assuming standard symbology is used appropriately). > >> Meaningful names are vital. But short names, even single letters, are not >> necessarily less meaningful than longer, more descriptive names. > Absolutely. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 30 10:22:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2012 09:22:40 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: Message-ID: On 30/09/12 00:09, Brett Ritter wrote: > agreement. Can you point to any of the research you mention? I'd > like to read into to see how my personal experience equates with the > overall study - I might learn something! I can probably dig out some references but a good place to start if you have access (and every programmer should! :-) is Steve McConnell's book Code Complete. Wikipedia should also have plenty stuff on the subject. I'll try to dig a bit deeper later today. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 30 10:37:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2012 09:37:51 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: On 29/09/12 23:57, Oscar Benjamin wrote: > On 29 September 2012 22:57, Alan Gauld My point is that we should not choose short names just to keep an > expression on a single line.... > > in written math too. (Most of the equations I remember reading from > my quantum mechanics days were split over at least 3 lines... trying > > I wouldn't advocate forcing an equation onto a single line if it doesn't > fit on a single line. However, I'm sure that the equations you're > refering to would have already been using lots of symbols described by > very succinct single-greek/latin-letters and other simple glyphs. Yes which made them even more difficult to understand. > Now imagine replacing each of those single letter symbols > with English underscore-separated words so instead of letter > capital psi you would have 'time_dependent_wave_function' > and instead of hbar you would have 'planks_constant_over_twopi' > and so on. Your equation would go from three lines to thirty One of the things I like about programming is that I can take those types of equations and break them into chunks and put them in separate named functions. Then each term gets evaluated separately and has a name that represents what it means in physical terms. One of the things that makes math hard for people to grasp is its insistence on abstracting functions/values to single letter names etc. (especially when those names are in a foreign language/symbology, like Greek!) Of course, the abstraction is powerful in its own right because it can then be applied in multiple domains, but that abstraction is often the barrier to people understanding the principle. Those that are "good at math" are often really those who are "good at abstraction". > Now imagine replacing each of those single letter symbols with English > underscore-separated words so instead of letter capital psi you would > have 'time_dependent_wave_function' and instead of hbar you would have > 'planks_constant_over_twopi' and so on. Your equation would go from > three lines to thirty -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Sun Sep 30 12:50:54 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 30 Sep 2012 11:50:54 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: On 30 September 2012 09:37, Alan Gauld wrote: > On 29/09/12 23:57, Oscar Benjamin wrote: > >> On 29 September 2012 22:57, Alan Gauld > > > My point is that we should not choose short names just to keep an >> expression on a single line.... >> >> >> in written math too. (Most of the equations I remember reading from >> my quantum mechanics days were split over at least 3 lines... trying >> >> I wouldn't advocate forcing an equation onto a single line if it doesn't >> fit on a single line. However, I'm sure that the equations you're >> refering to would have already been using lots of symbols described by >> very succinct single-greek/latin-letters and other simple glyphs. >> > > Yes which made them even more difficult to understand. Quantum mechanics is hard for anyone. I don't think that an alternative notation will make it any easier for people in the business of learning/teaching/using quantum mechanics (there are already several notations developed specifically for quantum mechanics). I also don't think that it is possible to find a notation that will make quantum mechanics intelligible to a layperson: whether you call it psi or time_dependent_wave_function you will still be assuming that the reader knows what a wave function is. > > > Now imagine replacing each of those single letter symbols > > with English underscore-separated words so instead of letter > > capital psi you would have 'time_dependent_wave_function' > > and instead of hbar you would have 'planks_constant_over_twopi' > > and so on. Your equation would go from three lines to thirty > > One of the things I like about programming is that I can take those types > of equations and break them into chunks and put them in > separate named functions. Then each term gets evaluated separately > and has a name that represents what it means in physical terms. > I often write scripts like the one that the OP is tasked with writing. While I can write a script like the OP's in less than 5 minutes, in practise it takes longer to convince myself that the code is correct (if it is important for it to be so). I spend most of the time when developing such a script simply looking at the code and comparing it with the mathematical problem I was trying to solve. The further your code diverges from the original problem statement the harder it becomes to really convince yourself that the code is correct. Renaming all of your variables (any more than you need to) so that cross-referencing always requires a mental table would be a waste of time and would increase the likelihood of bugs. > > > One of the things that makes math hard for people to grasp is its > insistence on abstracting functions/values to single letter names etc. > (especially when those names are in a foreign language/symbology, > like Greek!) Of course, the abstraction is powerful in its own right > because it can then be applied in multiple domains, but that abstraction is > often the barrier to people understanding the > principle. Those that are "good at math" are often really those > who are "good at abstraction". > I'll agree with the last sentence. The conventions used in mathematical symbols convey a lot of meaning (to me). If you look at the Lotka-Volterra equations on Wikipedia, you'll see that the letters x and y are used for the variables and greek letters are used for the constants. That distinction between the variables and constants ("parameters" in dynamics jargon) is very important when trying to understand the model. It is also the only thing you need to know about this model to correctly write the code that solves the system (and is obscured by renaming the variables). In any case I guess you won't be pleased by my discovery that, thanks to PEP 3131, the following is valid code in Python 3 (I've attached the code in case it doesn't display properly): ''' #!/usr/bin/env python3 # -*- encoding: utf-8 -*- # Parameters ? = 1 ? = 0.1 ? = 1.5 ? = 0.075 # Initial conditions x? = 10 y? = 5 Z? = x?, y? # Solution parameters t? = 0 ?t = 0.001 T = 10 # Lotka-Volterra derivative def f(Z, t): x, y = Z x? = x * (? - ?*y) y? = -y * (? - ?*x) return x?, y? # Accumulate results from Euler stepper t? = t? Z? = Z? Z?, t = [], [] while t? <= t? + T: Z?.append(Z?) t.append(t?) Z? = [Z??+ ?t*Z??? for Z??, Z??? in zip(Z?, f(Z?, t?))] t? += ?t # Output since I don't have plotting libraries in Python 3 print('t', 'x', 'y') for t?, (x?, y?) in zip(t, Z?): print(t?, x?, y?) ''' Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: sim.py Type: application/octet-stream Size: 735 bytes Desc: not available URL: From afzal.pcc at gmail.com Sun Sep 30 13:47:18 2012 From: afzal.pcc at gmail.com (Afzal Hossain) Date: Sun, 30 Sep 2012 17:47:18 +0600 Subject: [Tutor] Tutor Digest, Vol 103, Issue 145 In-Reply-To: References: Message-ID: unsubscribe On 9/30/12, 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 > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Lotka-Volterra Model Simulation Questions (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 30 Sep 2012 09:37:51 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Lotka-Volterra Model Simulation Questions > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 29/09/12 23:57, Oscar Benjamin wrote: >> On 29 September 2012 22:57, Alan Gauld >> My point is that we should not choose short names just to keep an >> expression on a single line.... >> >> in written math too. (Most of the equations I remember reading from >> my quantum mechanics days were split over at least 3 lines... trying >> >> I wouldn't advocate forcing an equation onto a single line if it doesn't >> fit on a single line. However, I'm sure that the equations you're >> refering to would have already been using lots of symbols described by >> very succinct single-greek/latin-letters and other simple glyphs. > > Yes which made them even more difficult to understand. > > > Now imagine replacing each of those single letter symbols > > with English underscore-separated words so instead of letter > > capital psi you would have 'time_dependent_wave_function' > > and instead of hbar you would have 'planks_constant_over_twopi' > > and so on. Your equation would go from three lines to thirty > > One of the things I like about programming is that I can take those > types of equations and break them into chunks and put them in > separate named functions. Then each term gets evaluated separately > and has a name that represents what it means in physical terms. > > > One of the things that makes math hard for people to grasp is its > insistence on abstracting functions/values to single letter names etc. > (especially when those names are in a foreign language/symbology, > like Greek!) Of course, the abstraction is powerful in its own right > because it can then be applied in multiple domains, but that abstraction > is often the barrier to people understanding the > principle. Those that are "good at math" are often really those > who are "good at abstraction". > > >> Now imagine replacing each of those single letter symbols with English >> underscore-separated words so instead of letter capital psi you would >> have 'time_dependent_wave_function' and instead of hbar you would have >> 'planks_constant_over_twopi' and so on. Your equation would go from >> three lines to thirty > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 103, Issue 145 > *************************************** > -- afzal From oscar.j.benjamin at gmail.com Sun Sep 30 13:54:14 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 30 Sep 2012 12:54:14 +0100 Subject: [Tutor] Tutor Digest, Vol 103, Issue 145 In-Reply-To: References: Message-ID: On 30 September 2012 12:47, Afzal Hossain wrote: > unsubscribe > > Apologies if we're boring you. You need to click the link at the bottom of the email to unsubscribe: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sun Sep 30 13:59:10 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 30 Sep 2012 07:59:10 -0400 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: On Sun, Sep 30, 2012 at 6:50 AM, Oscar Benjamin wrote: > > In any case I guess you won't be pleased by my discovery that, thanks to PEP > 3131, the following is valid code in Python 3 (I've attached the code in > case it doesn't display properly): > > # Parameters > ? = 1 > ? = 0.1 > ? = 1.5 > ? = 0.075 Latin, Greek, Cyrillic, Arabic, etc -- it's not the alphabet that's the problem. Well, in a way it is because if you really used Greek words as variable names I'd have to run your code through a translator. It seems OK to me, however, if the intended audience is only Greek-speaking programmers. That said, using arbitrary Unicode characters does have the potential to introduce bugs when character glyphs look similar or even identical: >>> ?, A = 5, 10 >>> ?, A (5, 10) >>> list(map(unicodedata.name, "A?")) ['LATIN CAPITAL LETTER A', 'GREEK CAPITAL LETTER ALPHA'] From wprins at gmail.com Sun Sep 30 16:20:20 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 30 Sep 2012 15:20:20 +0100 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: Oscar, On 30 September 2012 11:50, Oscar Benjamin wrote: > In any case I guess you won't be pleased by my discovery that, thanks to PEP > 3131, the following is valid code in Python 3 (I've attached the code in > case it doesn't display properly): > > ''' > #!/usr/bin/env python3 > # -*- encoding: utf-8 -*- > > # Parameters > ? = 1 > ? = 0.1 > ? = 1.5 > ? = 0.075 Hey thanks for posting this, I wasn't aware that this is possible! I really like the fact that you are able to do this if required. (If your problem domain and hence the target audience is a group of people where a certain set of symbols have a well established conventional set of meanings [and hence will be quite readable to them] then I think it's quite sensible to just use the conventional lingo, incl. symbols when suitable, so as I say, I really like the fact that Python can support the above directly. ) Thanks again for posting! Walter From eryksun at gmail.com Sun Sep 30 17:12:55 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 30 Sep 2012 11:12:55 -0400 Subject: [Tutor] Lotka-Volterra Model Simulation Questions In-Reply-To: References: <5066D082.7050301@pearwood.info> Message-ID: On Sun, Sep 30, 2012 at 10:20 AM, Walter Prins wrote: > > your problem domain and hence the target audience is a group of people > where a certain set of symbols have a well established conventional > set of meanings [and hence will be quite readable to them] then I > think it's quite sensible to just use the conventional lingo, incl. > symbols when suitable You can use any kind of (L)etter, but not (S)ymbols: >>> list(map(unicodedata.category, "??")) ['Lo', 'Lo'] >>> ?, ? = "Chinese Python", "Japanese Python" >>> list(map(unicodedata.category, "??")) ['Sm', 'Sm'] >>> ? = "Partial Differential" File "", line 1 ? = "Partial Differential" ^ SyntaxError: invalid character in identifier >>> ? = "Integral" File "", line 1 ? = "Integral" ^ SyntaxError: invalid character in identifier From mark.rourke7 at gmail.com Sun Sep 30 21:31:47 2012 From: mark.rourke7 at gmail.com (Mark Rourke) Date: Sun, 30 Sep 2012 15:31:47 -0400 Subject: [Tutor] HELP! Message-ID: <50689E23.4050901@gmail.com> hello, I am a college student in my first year of computer programming, I was wondering if you could look at my code to see whats wrong with it. # Mark Rourke # Sept 29, 2012 # Write a program to calculate the sales tax at the rate of 4% and 2% respectively # Thereafter compute the total sales tax (sum of the state tax and the county tax) # and the total purchase amount (sum of the purchase amount and the total sales tax). # Finally, display the amount of purchase, the state sales tax, the county sales tax, #the total sales tax and the total amount of the sale. #Variable Declarations #Real purchaseAmount, stateSalesTax, countySalesTax, totalSalesTax, totalPurchaseAmount #Constant Real SALES_TAX = 0.4, COUNTY_TAX = 0.02 #Display "Input Purchase Amount: $" #input the hours worked and hourly wage wage SALES_TAX = 0.4 COUNTY_TAX = 0.02 print("----------------------------------------------------------") print(("This program calculates the sales tax at the rate of 4% and 2% respectively, as well sum of the state tax")) print("----------------------------------------------------------") purchaseAmount = input("Please input the Purchase Amount: $") #Calculate the State Sales Tax, County Sales Tax, Total Sales Tax, Total Purchase Amount purchaseAmount = int(purchaseAmount) stateSalesTax = int(purchaseAmount * SALES_TAX) countySalesTax = int(purchaseAmount * COUNTY_TAX) totalSalesTax = int(stateSalesTax + countySalesTax) totalPurchaseAmount = int(purchaseAmount + totalSalesTax) #Output the results Display ("Purchase Amount:$") purchaseAmount Display ("The State Sales Tax $") SALES_TAX Display ("The County Sales Tax: $") COUNTY_TAX Display ("The Total Sales Tax: $") totalSalesTax Display ("The Total Amount of the Purchase: $") totalPurchaseAmount -- Mark Rourke T: 705-728-6169 M: 705-331-0175 E: Mark.Rourke7 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From philoant at gmail.com Sun Sep 30 08:02:57 2012 From: philoant at gmail.com (patrick Howard) Date: Sun, 30 Sep 2012 01:02:57 -0500 Subject: [Tutor] python help? Message-ID: I have to write a program that takes an input file, with students names and various grades. My vindictive teacher also added grades that are not supposed to count, so I need to pick the grades that are 'HM1-4"; not HW, or TEST or anything else. Then when these are listed in order with that persons name, sort the list alphabetically. I know that this is '.sort; But, how do I get it to sort only names, AND keep the right grades with them. Below is a list of parameters? Can you help me please? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: parameters.png Type: image/png Size: 111589 bytes Desc: not available URL: