Re: Newbie question about evaluating raw_input() responses
On Thu, May 23, 2013 at 2:47 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: But all joking aside, eval is dangerous, yes, but it is not evil. It needs to be handled with caution, but there are good uses for it. In fact, there are a few -- a very few -- things which can *only* be done with eval or exec. That's why it is part of the language! ... So while it is right and proper to treat eval with great respect as a powerful (and therefore dangerous) tool, and avoid it whenever you don't *need* it, there is no reason to be irrational about it :-) No need to be irrational about eval(), but I do agree that input() should never be used. Especially now that Py3 has changed the meaning of input(), it's potentially very confusing to call the old function; be explicit and use eval(raw_input()) if you actually want that. Quite apart from the extreme danger of eval'ing something tainted (which isn't a problem if you KNOW the user's trusted - eg if you're effectively writing an interactive interpreter for yourself), input() is just too concealing; it's not obvious that code will be executed. Above all, I don't want to see people advised to eval things as a solution to simple problems. Maybe it's safe *right now*, but any advice that solves today's problem will be used to solve tomorrow's problem too, and tomorrow's problem will involve code going to someone untrusted who suddenly gets full code execution. But this is why we have a mailing list, not one-on-one advice. Kevin's post is bound to get a follow-up, just as my posts are when I say something incorrect. It gives that measure of extra confidence: Correct me if I'm wrong, but... is implicitly prefixed to everything :) So Kevin, please don't get me wrong: I'm not hating on you, I'm not wishing you hadn't posted. But I *will* speak strongly against the Py2 input() function. :) Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On 23 May 2013 03:39, llanitedave llanited...@veawb.coop wrote: On Wednesday, May 22, 2013 7:24:15 AM UTC-7, Chris Angelico wrote: On Wed, May 22, 2013 at 11:42 PM, Wolfgang Keller felip...@gmx.net wrote: ... there's another option that is available to every platform and (practially) every high level language: the web browser. Make your app serve HTTP and do up your UI in HTML5/CSS3 - your facilities are pretty extensive. Plus you get networking support for free! Obviously this option isn't for everyone, but don't discount it out of hand. ChrisA I've been thinking about that myself for some future app ideas. If you have a stand-alone app working from your web browser, don't you need an embedded web server to utilize the file system? Is a system like Django for an app overkill? Or is its embedded development server underkill for a single-user browser-based application? -- http://mail.python.org/mailman/listinfo/python-list JavaScript has this: http://appjs.org/ It's a node.js server app serving a folder of plain old HTML files to a chrome embedded browser. You can code in a node.js server using anything you like, serve requests for your client app (or use the server code directly, you can just put the functions you would like to share with the client in the window object), etc. I'm using it for a peer to peer configurable application. To do that I serve up the web application for me and my peers (by using a regular server instead of the fake server it comes with), and the browser is just a client which can connect wherever I want it to. Someone should fork this and make it work in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On Thu, May 23, 2013 at 4:43 PM, Fábio Santos fabiosantos...@gmail.com wrote: On 23 May 2013 03:39, llanitedave llanited...@veawb.coop wrote: On Wednesday, May 22, 2013 7:24:15 AM UTC-7, Chris Angelico wrote: there's another option that is available to every platform and (practially) every high level language: the web browser. Make your app serve HTTP and do up your UI in HTML5/CSS3 - your facilities are pretty extensive. Plus you get networking support for free! Obviously this option isn't for everyone, but don't discount it out of hand. ChrisA I've been thinking about that myself for some future app ideas. If you have a stand-alone app working from your web browser, don't you need an embedded web server to utilize the file system? Is a system like Django for an app overkill? Or is its embedded development server underkill for a single-user browser-based application? -- http://mail.python.org/mailman/listinfo/python-list JavaScript has this: http://appjs.org/ It's a node.js server app serving a folder of plain old HTML files to a chrome embedded browser. You can code in a node.js server using anything you like, serve requests for your client app (or use the server code directly, you can just put the functions you would like to share with the client in the window object), etc. Many high level languages today come with simple HTTP server modules. They may not scale to infinity and beyond, but they'll work fine for a single-user system using a browser for its UI. Chances are they'll do well for everything up to a single CPU core. Depends on the language and library, of course. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
RE: Future standard GUI library
You don't! If your app needs local content just use a regular open() (or your browser) to read the files and render them as you see fit. For remote content you just need the 'urllib2' module or something like 'requests' module to get the data. Date: Wed, 22 May 2013 19:31:55 -0700 Subject: Re: Future standard GUI library From: llanited...@veawb.coop [...] I've been thinking about that myself for some future app ideas. If you have a stand-alone app working from your web browser, don't you need an embedded web server to utilize the file system? Is a system like Django for an app overkill? Or is its embedded development server underkill for a single-user browser-based application? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On Thu, May 23, 2013 at 4:58 PM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: You don't! If your app needs local content just use a regular open() (or your browser) to read the files and render them as you see fit. For remote content you just need the 'urllib2' module or something like 'requests' module to get the data. BTW, forgot the link. The part you DO need is something like this: http://docs.python.org/3/library/http.server.html It takes care of the irrelevant and lets you just write your app. The same sort of thing is available in quite a few languages. Great for knocking something together quickly; not designed for thousand-TPS web servers. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about evaluating raw_input() responses
On 5/23/2013 12:47 AM, Steven D'Aprano wrote: On Wed, 22 May 2013 22:31:04 +, Alister wrote: Please write out 1000 time (without using any form of loop) NEVER use input in python 3.0 it is EVIL* But all joking aside, eval is dangerous, yes, but it is not evil. He put that label on *input*, not eval -- I presume for hiding dangerous eval. -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing from unittest
Am 22.05.2013 17:32, schrieb Charles Smith: I'd like to subclass from unittest.TestCase. I observed something interesting and wonder if anyone can explain what's going on... some subclasses create null tests. I can perhaps guess what's going on, though Terry is right: Your question isn't very helpful and informative. I can create this subclass and the test works: class StdTestCase (unittest.TestCase): blahblah and I can create this subsubclass and the test works: class aaaTestCase (StdTestCase): moreblahblah but if I create this subsubclass (or any where the first letter is capital): class AaaTestCase (StdTestCase): differentblahblah the test completes immediately without any work being done. Well, per PEP 8, classes use CamelCaps, so your naming might break automatic test discovery. Then, there might be another thing that could cause this, and that is that if you have an intermediate class derived from unittest.TestCase, that class on its own will be considered as test case! If this is not what you want but you still want common functionality in a baseclass, create a mixin and then derive from both the mixin and unittest.TestCase for the actual test cases. Good luck! Uli -- http://mail.python.org/mailman/listinfo/python-list
newbie question about subprocess.Popen() arguments
Hello, I'm trying to call new process with some parameters. The problem is that the last parameter is a string that has a lot of spaces and different symbols like slash and so on. I can save it in file and use name of this file as parameter, but my question is: how to make it without additional saving? import subprocess as sp rc = sp.Popen([prog, --options, , msg], stdin=sp.PIPE, stdout=sp.PIPE) stdout = rc.communicate()[0] print stdout Thank you, Alex p.s. type(msg) = type 'str' -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about evaluating raw_input() responses
On Thu, May 23, 2013 at 5:11 PM, Terry Jan Reedy tjre...@udel.edu wrote: On 5/23/2013 12:47 AM, Steven D'Aprano wrote: On Wed, 22 May 2013 22:31:04 +, Alister wrote: Please write out 1000 time (without using any form of loop) NEVER use input in python 3.0 it is EVIL* But all joking aside, eval is dangerous, yes, but it is not evil. He put that label on *input*, not eval -- I presume for hiding dangerous eval. Aside: Why was PHP's /e regexp option ever implemented? I can understand evalling inputted text - that's how you write an interactive interpreter. But why would you arbitrarily eval the result of a regexp replacement? That seems... really weird. Like building a gun with a Reverse switch that fires the bullet down the butt instead of the barrel. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question about subprocess.Popen() arguments
Alex Naumov wrote: I'm trying to call new process with some parameters. The problem is that the last parameter is a string that has a lot of spaces and different symbols like slash and so on. I can save it in file and use name of this file as parameter, but my question is: how to make it without additional saving? import subprocess as sp rc = sp.Popen([prog, --options, , msg], stdin=sp.PIPE, stdout=sp.PIPE) stdout = rc.communicate()[0] print stdout p.s. type(msg) = type 'str' The operator is a shell feature, not an argument, and msg is intended to be send to prog's stdin. The communicate() method accepts a parameter for that. So: rc = sp.Popen([prog, --options], stdin=sp.PIPE, stdout=sp.PIPE) stdout = rc.communicate(msg)[0] -- http://mail.python.org/mailman/listinfo/python-list
RE: Future standard GUI library
It would be way more practical to have an embedded browser. Appjs doesn't even occupy a port on the client. We could totally benefit from that. Django applications practically make themselves. On 23 May 2013 08:02, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: You don't! If your app needs local content just use a regular open() (or your browser) to read the files and render them as you see fit. For remote content you just need the 'urllib2' module or something like 'requests' module to get the data. Date: Wed, 22 May 2013 19:31:55 -0700 Subject: Re: Future standard GUI library From: llanited...@veawb.coop [...] I've been thinking about that myself for some future app ideas. If you have a stand-alone app working from your web browser, don't you need an embedded web server to utilize the file system? Is a system like Django for an app overkill? Or is its embedded development server underkill for a single-user browser-based application? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question about subprocess.Popen() arguments
Thank you very much, Peter! It works! On Thu, May 23, 2013 at 9:32 AM, Peter Otten __pete...@web.de wrote: Alex Naumov wrote: I'm trying to call new process with some parameters. The problem is that the last parameter is a string that has a lot of spaces and different symbols like slash and so on. I can save it in file and use name of this file as parameter, but my question is: how to make it without additional saving? import subprocess as sp rc = sp.Popen([prog, --options, , msg], stdin=sp.PIPE, stdout=sp.PIPE) stdout = rc.communicate()[0] print stdout p.s. type(msg) = type 'str' The operator is a shell feature, not an argument, and msg is intended to be send to prog's stdin. The communicate() method accepts a parameter for that. So: rc = sp.Popen([prog, --options], stdin=sp.PIPE, stdout=sp.PIPE) stdout = rc.communicate(msg)[0] -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Scope of a class..help???
i had written the following code i am unable to create the instance of the class Node in the method number_to_LinkedList can any one help me how to do ?? and what is the error?? class Node: def __init__(self, value=None): self.value = value self.next = None def number_to_LinkedList(numbers): pass list_numbers = list(numbers) head_node = Node() #unable to create the instance saying UnboundedLocal head_node.value = list_numbers[0] head_node.next = None current_node = head_node for i in range(1,len(list_numbers)): new_node = Node() new_node.value = list_numbers[i] new_node.next = current_node current_node = new_node current_node.next = None while Node: print Node.data Node = Node.next -- http://mail.python.org/mailman/listinfo/python-list
2's Complement in python help.
Can anyone give me an idea of how to find the 2's Complement in python with an example -- http://mail.python.org/mailman/listinfo/python-list
Re: Ordered dictionaries compared
Dan Stromberg drsalists at gmail.com writes: What kind of ordered dictionaries? Sorted by key. Calling them sorted dictionaries avoids any confusions with Python's standard OrderedDict class: http://docs.python.org/3.3/library/collections.html#ordereddict-objects Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Re: 2's Complement in python help.
On Thu, May 23, 2013 at 7:54 PM, lokeshkopp...@gmail.com wrote: Can anyone give me an idea of how to find the 2's Complement in python with an example Do you know what two's complement is? (Not to be confused with two's compliment, which is when numbers start telling you how clever you are.) If not, you should probably look it up on Wikipedia or something. Once you know what the term means, you can start implementing in Python. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
On Thu, May 23, 2013 at 7:51 PM, lokeshkopp...@gmail.com wrote: i had written the following code i am unable to create the instance of the class Node in the method number_to_LinkedList can any one help me how to do ?? and what is the error?? It would really help if you post the actual exception and traceback. It's UnboundLocal, not Unbounded... and here's the problem: def number_to_LinkedList(numbers): head_node = Node() #unable to create the instance saying UnboundedLocal while Node: print Node.data Node = Node.next You're assigning to Node. I think you mean to have some other local variable here, for the iteration at the end. Since you assign to the name Node inside the function (and don't have a global declaration), the name Node is local to the function. Python doesn't let you reference the global prior to shadowing it with the local, so you get this error. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
lokeshkopp...@gmail.com wrote: i had written the following code i am unable to create the instance of the class Node in the method number_to_LinkedList can any one help me how to do ?? and what is the error?? class Node: def __init__(self, value=None): self.value = value self.next = None def number_to_LinkedList(numbers): pass list_numbers = list(numbers) head_node = Node() #unable to create the instance saying UnboundedLocal head_node.value = list_numbers[0] head_node.next = None current_node = head_node for i in range(1,len(list_numbers)): new_node = Node() new_node.value = list_numbers[i] new_node.next = current_node current_node = new_node current_node.next = None while Node: print Node.data Node = Node.next You have to decide if you want to use a name in a function locally or to access a global. Python treats names that are being assigned to anywhere in a function as local throughout the whole function. x = global def f(): print x # ok, access global variable x = global def g(): x = local print x # ok, accessing local variable x = global def h(): print x # error, accessing local variable that has not # been assigned a value x = local -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
Thanks Chris Angelico, i am new to python can you suggest me how to remove the error and solve it. so,how can i create an instance for Node in that function??,is, it not possible to create an instance in such a way? -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
On Thu, May 23, 2013 at 8:23 PM, lokeshkopp...@gmail.com wrote: Thanks Chris Angelico, i am new to python can you suggest me how to remove the error and solve it. so,how can i create an instance for Node in that function??,is, it not possible to create an instance in such a way? The problem isn't the instantiation; the problem's further down, where you reuse the name Node to iterate over your list. Rename that to something else and you should be right. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
ok Peter Otten, but how to make a Class global?? -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
On 23 May 2013 04:15, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: The last line of my noob piece can be improved. So this is it: Most of it can be improved. filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt'] contents = [[[int(z) for z in y.split(',')] for y in open(x).read().split()] for x in filenames] s1c = [sum([r[0] for r in f]) for f in contents] a1r = [sum(f[0])/float(len(f[0])) for f in contents] print '\n'.join(['File {} has 1st row average = {:.2f}'.format(n,a1r[i]) for i,n in enumerate(filenames) if s1c[i]==50]) You're writing repeated list comprehensions that feed into one another like this: list2 = [func1(x) for x in list1] list3 = [func2(y) for y in list2] list4 = [func3(y) for y in list2] In this case it is usually better to write a single loop for x in list1: y = func1(x) v = func2(y) w = func3(y) With that your code becomes: filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt'] for filename in filenames: contents = [[int(z) for z in y.split(',')] for y in open(filename).read().split()] s1c = sum([r[0] for r in contents]) a1r = sum(f[0])/float(len(contents[0])) if s1c == 50: print('File {} has 1st row average = {:.2f}'.format(filename,a1r)) However you shouldn't really be doing open(x).read().split() part. You should use the with statement to open the files: with open(filename, 'rb') as inputfile: contents = [map(int, line.split()) for line in inputfile] Of course if you don't have so many list comprehensions in your code then your lines will be shorter and you won't feel so much pressure to use such short variable names. It's also better to define a mean function as it makes it clearer to read: # Needed by the mean() function in Python 2.x from __future__ import division def mean(numbers): return sum(numbers) / len(numbers) filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt'] for filename in filenames: with open(filename, 'rb') as inputfile: matrix = [map(int, line.split()) for line in inputfile] column1 = [row[0] for row in matrix] row1 = matrix[0] if mean(column1) == 50: print('File {} has 1st row average = {:.2f}'.format(filename, mean(row1))) It's all a little easier if you use numpy: import numpy as np filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt'] for filename in filenames: matrix = np.loadtxt(filename, dtype=int) column1 = matrix[:, 0] row1 = matrix[0, :] if sum(column1) == 50 * len(column1): print('File {} has 1st row average = {:.2f}'.format(filename, np.mean(row1))) Then again in practise I wouldn't be testing for equality of the mean. Oscar -- http://mail.python.org/mailman/listinfo/python-list
serialize a class to XML and back
Hi list, how can I serialize a python class to XML? Plus a way to get the class back from the XML? My aim is to store instances of this class in a database. bg, Johannes -- GLOBE Development GmbH Königsberger Strasse 260 48157 MünsterGLOBE Development GmbH Königsberger Strasse 260 48157 Münster 0251/5205 390 -- http://mail.python.org/mailman/listinfo/python-list
Re: serialize a class to XML and back
On 05/23/13 13:37, Schneider wrote: Hi list, how can I serialize a python class to XML? Plus a way to get the class back from the XML? My aim is to store instances of this class in a database. Hi, I'm working on a project called Spyne (http://spyne.io). With one object definition, you can serialize to/from xml and save to database via SQLAlchemy. The code generator on the site has examples for RPC and SQL. If you're not interested in doing RPC with the resulting document, here's an example for just the xml part: https://github.com/arskom/spyne/blob/master/examples/xml_utils.py Best regards, Burak -- http://mail.python.org/mailman/listinfo/python-list
help in obtaining binary equivalent of a decimal number in python
i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's For Example if the input is 2 Output should be: the 32bit equivalent of 2 : 0010 and the 1's compliment is: 1101 is there any pre-defined function to get the above results in python?? -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
On Thu, May 23, 2013 at 10:37 AM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: From: oscar.j.benja...@gmail.com Date: Thu, 23 May 2013 01:34:37 +0100 Subject: Re: file I/O and arithmetic calculation To: carlosnepomuc...@outlook.com CC: python-list@python.org On 23 May 2013 00:49, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: The code is pretty obvious to me, I mean there's no obfuscation at all. I honestly can't tell if you're joking. I'm not! lol Reminds me of an episode of BBT where Sheldon's trying to figure out sarcasm. Leonard: obviously sarcastic comment Sheldon: Was that sarcasm? Leonard: Noo... Sheldon: Was THAT sarcasm? Leonard: -- no answer needed. Normally don't do this much list comprehension in an example. It may be fine for the code, but it doesn't help explain stuff. :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: help in obtaining binary equivalent of a decimal number in python
On Thu, May 23, 2013 at 9:30 PM, lokeshkopp...@gmail.com wrote: i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's For Example if the input is 2 Output should be: the 32bit equivalent of 2 : 0010 and the 1's compliment is: 1101 is there any pre-defined function to get the above results in python?? You're asking for bitwise negation. Now that you know the keyword(s) to look for, you should be able to figure out the rest with a few quick docs and/or web searches. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Harmonic distortion of a input signal
On 20 mai, 19:56, Christian Gollwitzer aurio...@gmx.de wrote: Oops, I thought we were posting to comp.dsp. Nevertheless, I think numpy.fft does mixed-radix (can't check it now) Am 20.05.13 19:50, schrieb Christian Gollwitzer: Am 20.05.13 19:23, schrieb jmfauth: Non sense. Dito. The discrete fft algorithm is valid only if the number of data points you transform does correspond to a power of 2 (2**n). Where did you get this? The DFT is defined for any integer point number the same way. Just if you want to get it fast, you need to worry about the length. For powers of two, there is the classic Cooley-Tukey. But there do exist FFT algorithms for any other length. For example, there is the Winograd transform for a set of small numbers, there is mixed-radix to reduce any length which can be factored, and there is finally Bluestein which works for any size, even for a prime. All of the aforementioned algorithms are O(log n) and are implemented in typical FFT packages. All of them should result (up to rounding differences) in the same thing as the naive DFT sum. Therefore, today Keywords to the problem: apodization, zero filling, convolution product, ... Not for a periodic signal of integer length. eg.http://en.wikipedia.org/wiki/Convolution How long do you read this group? Christian -- Forget what I wrote. I'm understanding what I wanted to say, it is badly formulated. jmf -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
On Thu, May 23, 2013 at 8:25 PM, lokeshkopp...@gmail.com wrote: ok Peter Otten, but how to make a Class global?? He gave some examples. It'd be helpful to quote some of his post, for context... and preferably, show some proof that you've understood it. You're starting a number of threads that look like you're trying to get us to do your homework. You need to demonstrate that you actually understand the material you're supposed to be learning. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: help in obtaining binary equivalent of a decimal number in python
On 05/23/2013 07:30 AM, lokeshkopp...@gmail.com wrote: i need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's For Example if the input is 2 Output should be: the 32bit equivalent of 2 : 0010 and the 1's compliment is: 1101 is there any pre-defined function to get the above results in python?? I'm curious as to the intent of the assignment. Are you supposed to be learning about base conversion, about ones and twos complement, or about Python? Assuming the intent is to learn about Python, the built-in function bin() will take a Python integer (which is not decimal) and convert it to a str. At that point, you can manipulate the string any way you like. x = 45 print bin(45) 0b101101 Perhaps you want to start by stripping off the leading '0b' using a slice. Then you want to pad it to 32 columns by prepending some number of zeroes. Then you want to insert some spaces at regular intervals. Presumably doing the ones-complement operation on that string is then pretty easy for you. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: A computer programmer, web developer and network admin resume
On 2013-05-22, Tim Chase python.l...@tim.thechases.com wrote: On 2013-05-22 01:15, i...@databaseprograms.biz wrote: A computer programmer, web developer and network administrator ...walk into a bar... So what's the punchline? Ow. Get it? Ow. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: A computer programmer, web developer and network admin resume
On Thu, May 23, 2013 at 10:28 PM, Neil Cerutti ne...@norwich.edu wrote: On 2013-05-22, Tim Chase python.l...@tim.thechases.com wrote: On 2013-05-22 01:15, i...@databaseprograms.biz wrote: A computer programmer, web developer and network administrator ...walk into a bar... So what's the punchline? Ow. Get it? Ow. Better, better, but Wh! Wait. This isn't getting-hit-on-the-head-with-a-bad-joke lessons? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing from unittest
In article bar07a-pca@satorlaser.homedns.org, Ulrich Eckhardt ulrich.eckha...@dominolaser.com wrote: if you have an intermediate class derived from unittest.TestCase, that class on its own will be considered as test case! If this is not what you want but you still want common functionality in a baseclass, create a mixin and then derive from both the mixin and unittest.TestCase for the actual test cases. Or, try another trick I picked up somewhere. When you're done defining your test classes, delete the intermediate base class, so it won't be autodiscovered! class MyBaseTestClass(unittest.TestCase): pass class MyRealTest1(MyBaseTestClass): pass class MyRealTest2(MyBaseTestCalss): pass del MyBaseTestClass -- http://mail.python.org/mailman/listinfo/python-list
Debugging parallel nose tests?
I've got a suite of about 150 tests written using unittest. It takes 5-10 minutes to run, so I'd really like to use nose to run things in parallel. The problem is, when I do that, I get lots of test failures. Obviously, we've got some kind of inter-test dependency that I haven't been able to locate. Is there some way to make nose print a report of how it partitioned the tests across the various processes? If I could see that, it might help us reproduce the failures. We're using: nosetests --process-timeout=60 --processes=40 test_api.py and _multiprocess_can_split_ = True -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On May 22, 6:31 pm, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Date: Wed, 22 May 2013 13:26:23 -0700 Subject: Re: PEP 378: Format Specifier for Thousands Separator From: prueba...@latinmail.com To: python-l...@python.org [...] Maybe a cformat(formatstring, variables) function should be created in the string module so people who prefer that can use it. I don't mind the C formatting syntax but I don't like the fact that the % operator does something totally different when the first variable is an integer and the fact that it misbehaves if the second variable is a tuple. -- http://mail.python.org/mailman/listinfo/python-list I still don't understand why % benefits from literals optimization ('%d'%12345) while '{:d}'.format(12345) doesn't. What totally different you talking about? Please give me an example. def eggs(spam, ham): return spam % ham def milk(beef, steak): return beef.format(steak) a='%s' c=9 d=4 e=[1,2] f=(3,5) d='{}' eggs(a,4) '4' eggs(c,4) 1 eggs(a,e) '[1, 2]' eggs(a,f) Traceback (most recent call last): File pyshell#29, line 1, in module eggs(a,f) File pyshell#1, line 1, in eggs def eggs(spam, ham): return spam % ham TypeError: not all arguments converted during string formatting '%s'%(5%3) '2' milk(d,4) '4' milk(c,4) Traceback (most recent call last): File pyshell#53, line 1, in module milk(c,4) File pyshell#49, line 1, in milk def milk(beef, steak): return beef.format(steak) AttributeError: 'int' object has no attribute 'format' milk(d,e) '[1, 2]' milk(d,f) '(3, 5)' '{}'.format(5%3) '2' -- http://mail.python.org/mailman/listinfo/python-list
how to get the socket module compiled with SSL support
I am trying to make an HTTPS connection and read that HTTPS support is only available if the socket module was compiled with SSL support. http://www.jython.org/docs/library/httplib.html Can someone elaborate on this? Where can I get the socket module for HTTPS, or how do I build one if I have to? Thanks, - Kihup-- http://mail.python.org/mailman/listinfo/python-list
Re: how to get the socket module compiled with SSL support
On Thu, May 23, 2013 at 11:58 PM, Kihup Boo k...@ca.ibm.com wrote: I am trying to make an HTTPS connection and read that HTTPS support is only available if the socket module was compiled with SSL support. http://www.jython.org/docs/library/httplib.html Can someone elaborate on this? Where can I get the socket module for HTTPS, or how do I build one if I have to? If you got a standard download, chances are it's going to have SSL support. What error are you getting? Is it specifically telling you that SSL support is not available? Post a minimal script and its actual failure. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
Dear all who involved with responding to my question - Thank you so much for your nice code which really helped me. -- http://mail.python.org/mailman/listinfo/python-list
RE: PEP 378: Format Specifier for Thousands Separator
Date: Thu, 23 May 2013 06:44:05 -0700 Subject: Re: PEP 378: Format Specifier for Thousands Separator From: prueba...@latinmail.com To: python-list@python.org [...] eggs(a,f) Traceback (most recent call last): File pyshell#29, line 1, in module eggs(a,f) File pyshell#1, line 1, in eggs def eggs(spam, ham): return spam % ham TypeError: not all arguments converted during string formatting '%s'%(5%3) '2' So % doesn't handle tuples! Why's that? Is it intentional (by design)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
But there's another option that is available to every platform and (practially) every high level language: the web browser. Make your app serve HTTP and do up your UI in HTML5/CSS3 - your facilities are pretty extensive. Plus you get networking support for free! Obviously this option isn't for everyone, but don't discount it out of hand. Both the concept and actually implemented examples of so-called web applications prove that they are just plain garbage and hopelessly unusable for anything remotely resembling actual screenwork. HTML forms may be at best useful for web shops, but for actual screenwork, HTML is not a valid GUI, no matter how much javascript you add to it. Sincerely, Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Error with python 3.3.2 and https
I am trying to write a program that requires me hitting a https web link. However, I can't seem to get it to work. The program works fine when dealing with http sites, however, when I try it with a https site I get socket.gaierror: [Errno 11001] getaddrinfo failed It seems like it has something to do with the ssl not working, however, I do have the ssl.py in the python library and I have no problem importing it. My code is below. Any help would be greatly appreciated. import urllib.request auth = urllib.request.HTTPSHandler() proxy = urllib.request.ProxyHandler({'http':'my proxy'}) opener = urllib.request.build_opener(proxy, auth) f = opener.open('http://www.google.ca/') -- http://mail.python.org/mailman/listinfo/python-list
Re: Error with python 3.3.2 and https
On Fri, May 24, 2013 at 1:48 AM, asianava...@gmail.com wrote: I am trying to write a program that requires me hitting a https web link. However, I can't seem to get it to work. The program works fine when dealing with http sites, however, when I try it with a https site I get socket.gaierror: [Errno 11001] getaddrinfo failed It seems like it has something to do with the ssl not working, however, I do have the ssl.py in the python library and I have no problem importing it. My code is below. Any help would be greatly appreciated. import urllib.request auth = urllib.request.HTTPSHandler() proxy = urllib.request.ProxyHandler({'http':'my proxy'}) opener = urllib.request.build_opener(proxy, auth) f = opener.open('http://www.google.ca/') Check the name of your proxy; maybe you can't resolve it. Can you identify your proxy by IP address? By omitting the proxy part, I can quite happily make a direct request using code like yours. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On Fri, May 24, 2013 at 1:41 AM, Wolfgang Keller felip...@gmx.net wrote: But there's another option that is available to every platform and (practially) every high level language: the web browser. Make your app serve HTTP and do up your UI in HTML5/CSS3 - your facilities are pretty extensive. Plus you get networking support for free! Obviously this option isn't for everyone, but don't discount it out of hand. Both the concept and actually implemented examples of so-called web applications prove that they are just plain garbage and hopelessly unusable for anything remotely resembling actual screenwork. HTML forms may be at best useful for web shops, but for actual screenwork, HTML is not a valid GUI, no matter how much javascript you add to it. All depends on your requirements. For the Yosemite Project, I wanted the networking aspect, so the web browser UI was a good one. It's been working beautifully for... what, four or six years now, I think; and it's just a few pages of Python. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Accessing Json data (I think I am nearly there) complete beginner
Hey guys I think its worth stating that I have been trying to code for 1 week. I am trying to access some Json data. My innitial code was the below: import mechanize import urllib import re def getData(): post_url = http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/all_time; browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Firefox')] #These are the parameters you've got from checking with the aforementioned tools parameters = {'page' : '1', 'rp' : '10', 'sortname' : 'total_pl', 'sortorder' : 'desc'} #Encode the parameters data = urllib.urlencode(parameters) trans_array = browser.open(post_url,data).read().decode('UTF-8') #print trans_array myfile = open(test.txt, w) myfile.write(trans_array) myfile.close() getData() raw_input(Complete) I was recommended to use the following code to access the Json data directly, however I cannot get it to return anything. I think the guy that recommended me this method must have got something wrong? Or perhaps I am simply incompetent: import mechanize import urllib import json def getData(): post_url = http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/current_week; browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Firefox')] #These are the parameters you've got from checking with the aforementioned tools parameters = {'page' : '1', 'rp' : '50', 'sortname' : 'total_pl', 'sortorder' : 'desc' } #Encode the parameters data = urllib.urlencode(parameters) trans_array = browser.open(post_url,data).read().decode('UTF-8') text1 = json.loads(trans_array) print text1['rows'][0]['id'] #play around with these values to access different data.. getData() He told me to #play around with these values to access different data.. really cant get anything out of this, any ideas? Many thanks AEA -- http://mail.python.org/mailman/listinfo/python-list
Re: Error with python 3.3.2 and https
I only have the http of the proxy. I guess I could find out the ip of it. However, even if I use the http proxy address, why would it work for a http site and not a https site if its the proxy that can't resolve. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error with python 3.3.2 and https
On Fri, May 24, 2013 at 2:12 AM, asianava...@gmail.com wrote: I only have the http of the proxy. I guess I could find out the ip of it. However, even if I use the http proxy address, why would it work for a http site and not a https site if its the proxy that can't resolve. Can you post working code for HTTP and nonworking for HTTPS? There was no SSL in the code you posted. Or are you saying it's really just that you change the URL and it stops working? If so, I don't think we can test it without having your proxy... you may want to talk to whoever controls the proxy. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Pulp problem _dummy
Hello! I'm using pulp for linear optimization but when I run my code I get the following output: Central Optimization: MAXIMIZE 0*__dummy + 0 SUBJECT TO _C1: 2 T0 = 0 _C2: 2 T0 = 0 _C3: 0.0686928673545 Frigorifico0 = 0 _C4: 0.0686928673545 Frigorifico0 = 0 _C5: 2 Termo0 = 0 _C6: 2 Termo0 = 0 _C7: 0.0686928673545 F0 = 0 _C8: 0.0686928673545 F0 = 0 _C9: 2 T1 = 0 _C10: 2 T1 = 0 _C11: 0.0686928673545 Frigorifico1 = 0 _C12: 0.0686928673545 Frigorifico1 = 0 _C13: 2 Termo0 = 0 _C14: 2 Termo0 = 0 _C15: 0.0686928673545 F0 = 0 _C16: 0.0686928673545 F0 = 0 _C17: - AC0 - VE0 - 2 T0 - 0.0686928673545 F0 - AC1 - VE1 - 2 T1 - 0.0686928673545 F1 = -15 VARIABLES AC0 = 2.75 Continuous VE0 = 0 Continuous 0 = T0 = 1 Integer 0 = F0 = 1 Integer AC1 = 2.75 Continuous VE1 = 0 Continuous 0 = T1 = 1 Integer 0 = F1 = 1 Integer __dummy = 0 Continuous I don't know if this is enough information for you but if you couold help me I would be very very grateful Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:09, Andrew Edwards-Adams wrote: I was recommended to use the following code to access the Json data directly, however I cannot get it to return anything. Where exactly is the problem? Do you not get JSON back? Do you get the wrong values? Do you get a KeyError or IndexError trying to get values from text1? Are there gremlins going around flipping bits in memory? It's good that you posted code, but really cant get anything out of this isn't very useful. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Ordered dictionaries compared
On 23/05/13 04:31, Dan Stromberg wrote: What kind of ordered dictionaries? Sorted by key. I've redone the previous comparison, this time with a better red-black tree implementation courtesy of Duncan G. Smith. The comparison is at http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/just-trees/ The Red-Black tree gave a much better showing this time, but it gave just one 2nd place on one workload-interpreter - still kinda lackluster. It took 1st place 0 times. A quick test of my Red Black Tree and Treap (Python 2.7). def test_trees(data, randomize=True): cpy = data[:] # for deletion if randomize: random.shuffle(data) random.shuffle(cpy) t = binary_trees.RedBlackTree() start = time.time() for datum in data: t.insert(datum) print 'Red Black Tree insertion %s' % (time.time() - start) start = time.time() for datum in data: t.find(datum) print 'Red Black Tree find %s' % (time.time() - start) start = time.time() for datum in cpy: t.delete(datum) print 'Red Black Tree deletion %s' % (time.time() - start) t = binary_trees.Treap() start = time.time() for datum in data: t.insert(datum) print print 'Treap insertion %s' % (time.time() - start) start = time.time() for datum in data: t.find(datum) print 'Treap find %s' % (time.time() - start) start = time.time() for datum in cpy: t.delete(datum) print 'Treap deletion %s' % (time.time() - start) test_trees(range(10)) Red Black Tree insertion 5.42807197571 Red Black Tree find 1.58799219131 Red Black Tree deletion 3.87580800056 Treap insertion 6.79647684097 Treap find 2.11693120003 Treap deletion 4.61243915558 test_trees(range(10), False) Red Black Tree insertion 6.29647898674 Red Black Tree find 1.157143116 Red Black Tree deletion 2.74785804749 Treap insertion 3.87288999557 Treap find 1.48776102066 Treap deletion 1.88962197304 RBT is quicker than Treap for insertion with randomized data, but slower with ordered data. Randomized data will tend to minimize the number of tree rotations needed to keep the RBT balanced, whilst the Treap will be performing rotations to maintain the heap property in an already reasonably well balanced tree. With ordered data the RBT will have to work harder to keep the tree balanced, whilst the Treap will be able to maintain the heap property with fewer rotations. No surprise that find() is generally quicker for RBTs, they tend to be better balanced. Deletion is a bit more confusing. I suppose deletion from a better balanced tree will tend to be quicker, but deletion from a treap constructed from ordered data is (for some reason) quickest of all. All these operations require a call to find(), and that is generally going to be quicker for RBTs. Treaps tend to require fewer subsequent rotations, but they have variable worth (in terms of rebalancing). Looks like RBTs are better than treaps if they are being populated with randomly ordered data, but not if they are being populated with ordered data. RBTs are better for use cases that are heavy on finds. Both types of tree appear to be better balanced (on the basis of the find results) if populated from ordered data. Treaps appear to perform better on insertion, find and deletion when populated from ordered data. Duncan -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 23/05/2013 17:09, Andrew Edwards-Adams wrote: Hey guys I think its worth stating that I have been trying to code for 1 week. I am trying to access some Json data. My innitial code was the below: import mechanize import urllib import re def getData(): post_url = http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/all_time; browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Firefox')] #These are the parameters you've got from checking with the aforementioned tools parameters = {'page' : '1', 'rp' : '10', 'sortname' : 'total_pl', 'sortorder' : 'desc'} #Encode the parameters data = urllib.urlencode(parameters) trans_array = browser.open(post_url,data).read().decode('UTF-8') #print trans_array myfile = open(test.txt, w) myfile.write(trans_array) myfile.close() getData() raw_input(Complete) I was recommended to use the following code to access the Json data directly, however I cannot get it to return anything. I think the guy that recommended me this method must have got something wrong? Or perhaps I am simply incompetent: import mechanize import urllib import json def getData(): post_url = http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/current_week; browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Firefox')] #These are the parameters you've got from checking with the aforementioned tools parameters = {'page' : '1', 'rp' : '50', 'sortname' : 'total_pl', 'sortorder' : 'desc' } #Encode the parameters data = urllib.urlencode(parameters) trans_array = browser.open(post_url,data).read().decode('UTF-8') text1 = json.loads(trans_array) print text1['rows'][0]['id'] #play around with these values to access different data.. getData() He told me to #play around with these values to access different data.. really cant get anything out of this, any ideas? Many thanks AEA I've just tried it. It prints 1048. -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On Thursday, May 23, 2013 5:40:49 PM UTC+1, Andrew Berg wrote: On 2013.05.23 11:09, Andrew Edwards-Adams wrote: I was recommended to use the following code to access the Json data directly, however I cannot get it to return anything. Where exactly is the problem? Do you not get JSON back? Do you get the wrong values? Do you get a KeyError or IndexError trying to get values from text1? Are there gremlins going around flipping bits in memory? It's good that you posted code, but really cant get anything out of this isn't very useful. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 Hi thanks for the reply Andrew, my first bit of code was heading in the right direction I was managing to pull out the usernames from the JSON, using REGEX. I was told that the second piece of code is the more efficient way to pull data from the JSON. When I say it doesnt do anything I can adjust the areas suggested. But it returns nothing, I just get the = Restart = line appear in the python shell. If there was a trackback/debug I might know where to look, but its not yielding errors, its simply yielding nothing. What i dont know, is if it is the code that isnt working, or what I am inputting in the print text1['rows'][0]['id'] that isnt working. Since this code: import mechanize import urllib import json def getData(): post_url = http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/current_week; browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Firefox')] #These are the parameters you've got from checking with the aforementioned tools parameters = {'page' : '1', 'rp' : '50', 'sortname' : 'total_pl', 'sortorder' : 'desc' } #Encode the parameters data = urllib.urlencode(parameters) trans_array = browser.open(post_url,data).read().decode('UTF-8') appears in both examples and my first attempt is definitely returning data from the JSON, I can only assume that the error is in the last two lines of his code, or as stated my imputing incorrect parameters. :S -- http://mail.python.org/mailman/listinfo/python-list
Re: Ordered dictionaries compared
On Thu, May 23, 2013 at 9:41 AM, duncan smith buzzard@invalid.invalidwrote: RBT is quicker than Treap for insertion with randomized data, but slower with ordered data. Randomized data will tend to minimize the number of tree rotations needed to keep the RBT balanced, whilst the Treap will be performing rotations to maintain the heap property in an already reasonably well balanced tree. With ordered data the RBT will have to work harder to keep the tree balanced, whilst the Treap will be able to maintain the heap property with fewer rotations. No surprise that find() is generally quicker for RBTs, they tend to be better balanced. Deletion is a bit more confusing. I suppose deletion from a better balanced tree will tend to be quicker, but deletion from a treap constructed from ordered data is (for some reason) quickest of all. All these operations require a call to find(), and that is generally going to be quicker for RBTs. Treaps tend to require fewer subsequent rotations, but they have variable worth (in terms of rebalancing). Looks like RBTs are better than treaps if they are being populated with randomly ordered data, but not if they are being populated with ordered data. RBTs are better for use cases that are heavy on finds. Both types of tree appear to be better balanced (on the basis of the find results) if populated from ordered data. Treaps appear to perform better on insertion, find and deletion when populated from ordered data. Strange. I was comparing randomized data (95% get, 50-50 get and set, 95% set) when I found that treaps were quite a bit faster than red black trees. The code I used is here: http://stromberg.dnsalias.org/svn/python-tree-and-heap-comparison/trunk/ See also https://en.wikipedia.org/wiki/Binary_search_tree#Performance_comparisons , which found that treaps were faster on average the red black trees. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error with python 3.3.2 and https
Yeah that is the case. Once I change the f = opener.open('website') line to a link that has a https I get that socket error. Nothing else changes. I was reading online and came across this site which shows you how if the version of python installed supports ssl. http://morlockhq.blogspot.ca/2008/05/python-tip-checking-to-see-if-your.html When I followed the instructions I got that it wasn't supported, although the ssl.py is in the lib directory. Python was installed from the official python page using the windows installer. Is somehow ssl disabled by default? Do I need to get a third party ssl module? -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:58, Andrew Edwards-Adams wrote: If there was a trackback/debug I might know where to look, but its not yielding errors, its simply yielding nothing. What i dont know, is if it is the code that isnt working, or what I am inputting in the print text1['rows'][0]['id'] that isnt working. If fed a valid JSON object, json.loads() will return a regular dictionary. You can print (or pretty print with the pprint module) text1 to see everything. If you're not familiar with dictionaries and lists, thoroughly read the tutorial before writing or modifying any more code. http://docs.python.org/2/library/json.html#json.loads -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:58, Andrew Edwards-Adams wrote: Hi thanks for the reply Andrew, my first bit of code was heading in the right direction I was managing to pull out the usernames from the JSON, using REGEX. It's also worth mentioning that regexes are almost always the wrong tool, especially for standardized formats like JSON. They can be very useful when nothing saner will get the job done, but are a nasty mess with no real benefit otherwise. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On Thursday, May 23, 2013 7:11:28 PM UTC+1, Andrew Berg wrote: On 2013.05.23 11:58, Andrew Edwards-Adams wrote: Hi thanks for the reply Andrew, my first bit of code was heading in the right direction I was managing to pull out the usernames from the JSON, using REGEX. It's also worth mentioning that regexes are almost always the wrong tool, especially for standardized formats like JSON. They can be very useful when nothing saner will get the job done, but are a nasty mess with no real benefit otherwise. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 Thanks Andrew, yes I believe this is what the guy who provided me with the code was thinking. I was about to embark on what was definitely going to be an inefficient long regex. -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging parallel nose tests?
On 05/23/2013 09:09 AM, Roy Smith wrote: SNIP nosetests --process-timeout=60 --processes=40 test_api.py Do you have a 40-processor system? And do you have enough RAM to run all of those processes? -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On 05/23/2013 11:26 AM, Carlos Nepomuceno wrote: Date: Thu, 23 May 2013 06:44:05 -0700 Subject: Re: PEP 378: Format Specifier for Thousands Separator From: prueba...@latinmail.com To: python-list@python.org [...] You left out the part where a and f are initialized: a='%s' f=(3,5) eggs(a,f) Traceback (most recent call last): File pyshell#29, line 1, in module eggs(a,f) File pyshell#1, line 1, in eggs def eggs(spam, ham): return spam % ham TypeError: not all arguments converted during string formatting '%s'%(5%3) '2' So % doesn't handle tuples! Why's that? Is it intentional (by design)? It's a conflict in the design. A tuple is used to supply multiple arguments to the % operator. So if you want to have a tuple as the first argument, you need to enclose it in another tuple. try the following: print a % (f,) The trouble is, it doesn't generalize very readily, so it's difficult to use in a function like eggs() -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Non-identifiers in dictionary keys for **expression syntax
This is a question regarding the documentation around dictionary unpacking. The documentation for the call syntax (http://docs.python.org/3/reference/expressions.html#grammar-token-call) says: If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. Using Cpython, we can do the following: def func(**kwargs): print kwargs d = {'foo bar baz':3} So that might lead us to believe that the keys of the mapping do not need to be valid identifiers. However, the previous function does not work with the following dictionary: d = {1:3} because not all the keys are strings. Is there a way to petition to get this more rigorously defined? Thanks, ~Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 23/05/2013 19:19, Andrew Edwards-Adams wrote: On Thursday, May 23, 2013 7:11:28 PM UTC+1, Andrew Berg wrote: On 2013.05.23 11:58, Andrew Edwards-Adams wrote: Hi thanks for the reply Andrew, my first bit of code was heading in the right direction I was managing to pull out the usernames from the JSON, using REGEX. It's also worth mentioning that regexes are almost always the wrong tool, especially for standardized formats like JSON. They can be very useful when nothing saner will get the job done, but are a nasty mess with no real benefit otherwise. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 Thanks Andrew, yes I believe this is what the guy who provided me with the code was thinking. I was about to embark on what was definitely going to be an inefficient long regex. Funny old world, there doesn't appear to be working code but someone is already thinking about definite inefficiency. What evidence do you have to support this claim? -- If you're using GoogleCrap™ please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On 2013-05-23, Matthew Gilson m.gils...@gmail.com wrote: That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. I don't see any ambiguity. A keyword argument is an argument preceded by an identifier according to the definition. Where are you perceiving wiggle room? -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing from unittest
On 5/23/2013 2:58 AM, Ulrich Eckhardt wrote: Well, per PEP 8, classes use CamelCaps, so your naming might break automatic test discovery. Then, there might be another thing that could cause this, and that is that if you have an intermediate class derived from unittest.TestCase, that class on its own will be considered as test case! If this is not what you want but you still want common functionality in a baseclass, create a mixin and then derive from both the mixin and unittest.TestCase for the actual test cases. This is now standard practice, gradually being implemented everywhere in the CPython test suite, for testing C and Py versions of a module. class TestXyz(): mod = None test_a, etc, methods class TestXyz_C(TestXyz, TextCase): # Test C version mod = support.import_fresh_module('_xyz') # approximately right class TestXyz_Py(TestXyz, TextCase): # Test Python version mod = support.import_fresh('xyz') This minimizes duplication and ensures that both implementations get exactly the same tests. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On 05/23/2013 12:20 PM, Neil Cerutti wrote: On 2013-05-23, Matthew Gilson m.gils...@gmail.com wrote: That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. I don't see any ambiguity. A keyword argument is an argument preceded by an identifier according to the definition. Where are you perceiving wiggle room? -- def func(**kwargs): ... print(kwargs) ... -- d = {'foo bar baz':3} -- func(**d) {'foo bar baz': 3} Even though 'foo bar baz' is not a valid identifier, and could not be passed as `func(foo bar baz = 3)`, it still worked when going through a dict. -- ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
On Thu, 23 May 2013 07:17:58 -0700, Keira Wilson wrote: Dear all who involved with responding to my question - Thank you so much for your nice code which really helped me. Hold on a sec? Someone posted code that gave the correct answer to a homework question? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On Thu, May 23, 2013 at 12:52 PM, Matthew Gilson m.gils...@gmail.com wrote: Using Cpython, we can do the following: def func(**kwargs): print kwargs d = {'foo bar baz':3} So that might lead us to believe that the keys of the mapping do not need to be valid identifiers. However, the previous function does not work with the following dictionary: d = {1:3} because not all the keys are strings. Is there a way to petition to get this more rigorously defined? The string requirement is probably for optimization, but if the argument is both sent and received using the ** syntax, is there a good reason why only identifiers should be allowed? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get the socket module compiled with SSL support
On 5/23/2013 9:58 AM, Kihup Boo wrote: I am trying to make an HTTPS connection and read that HTTPS support is only available if the socket module was compiled with SSL support. _http://www.jython.org/docs/library/httplib.html_ Can someone elaborate on this? Where can I get the socket module for HTTPS, or how do I build one if I have to? This is mostly a CPython oriented list. Any prebuilt CPython binary you get likely has SSL support compiled in. If you want to know about the jython socket module, you should check on a jython list, or just try it. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On 5/23/2013 2:42 PM, Dave Angel wrote: On 05/23/2013 11:26 AM, Carlos Nepomuceno wrote: eggs(a,f) Traceback (most recent call last): File pyshell#29, line 1, in module eggs(a,f) File pyshell#1, line 1, in eggs def eggs(spam, ham): return spam % ham TypeError: not all arguments converted during string formatting '%s'%(5%3) '2' So % doesn't handle tuples! Why's that? Is it intentional (by design)? It's a conflict in the design. A tuple is used to supply multiple arguments to the % operator. So if you want to have a tuple as the first argument, you need to enclose it in another tuple. The problem is that interpolating 1 to many items into a string is *not* a binary operation. The needed hack to pretend that it is, using a tuple to represent multiple items rather than just itself, was one of the reasons for making string formatting a honest function, where multiple items to be formatted are passed as multiple arguments. -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On 2013-05-23, Wolfgang Keller felip...@gmx.net wrote: But there's another option that is available to every platform and (practially) every high level language: the web browser. Make your app serve HTTP and do up your UI in HTML5/CSS3 - your facilities are pretty extensive. Plus you get networking support for free! Obviously this option isn't for everyone, but don't discount it out of hand. Both the concept and actually implemented examples of so-called web applications prove that they are just plain garbage and hopelessly unusable for anything remotely resembling actual screenwork. What is screenwork? -- Grant Edwards grant.b.edwardsYow! Am I elected yet? at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
suppress newlines in my script
I am importing lines from an external csv file and when I iterate through the lines and increment, new lines are introduced. How would I cut out the newlines. I have attempted several pythonic strip() and rstrip() how can i implent this? import sys, os f=open('europe_csv') lines=f.readlines() BU = 'Company,,' PPP = 'Pre-ProdProd,,' C1 = ',,' Title = 'Site,Environment,' NET1 = lines[4] GW1 = lines[5] M1 = lines[6] PS1 = lines[7] PE1 = lines[8] C2 = ',,' NET2 = lines[10] GW2 = lines[11] M2 = lines[12] PS2 = lines[13] PE2 = lines[14] for count in range(64, 127): print NET1.format(count) print GW1.format(count) print M1 print PS1.format(count) print PE1.format(count) print C2 print NET2.format(count) print GW2.format(count) print M2 print PS2.format(count) print PE2.format(count) -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On 5/23/2013 2:52 PM, Matthew Gilson wrote: This is a question regarding the documentation around dictionary unpacking. The documentation for the call syntax (http://docs.python.org/3/reference/expressions.html#grammar-token-call) says: If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. It appears that the requirement has been relaxed (in the previous quote), so that 'dictionary' should also be changed to 'mapping'. It might not hurt to add 'The key for the value should be an identifier.' As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. I think you are being too lawyerly. The pretty clear and sensible implication is that the key for the value should be a string with a valid identifier. If it is anything else, you are on your own and deserve any joy or pain that results ;=) Using Cpython, we can do the following: def func(**kwargs): print kwargs d = {'foo bar baz':3} So that might lead us to believe that the keys of the mapping do not need to be valid identifiers. There are two ways to pass args to func to be gathered into kwargs; explicit key=val pairs and **mapping, or both. func(a=1, b='hi', **{'foo bar baz':3}) # {'foo bar baz': 3, 'a': 1, 'b': 'hi'} So func should not expect anything other than identifier strings. However, the previous function does not work with the following dictionary: d = {1:3} because not all the keys are strings. So CPython checks that keys are strings, because that is cheap, but not that the strings are identifiers, because that would be more expensive. Just because an implementation allow somethings (omits a check) for efficiency does not mean you should do it. globals()[1] = 1 works, but is not normally very sensible or useful. Is there a way to petition to get this more rigorously defined? bugs.python.org The problem is that mandating a rigorous check by implementations makes Python slower to the detriment of sensible programmers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On 05/23/2013 03:20 PM, Neil Cerutti wrote: On 2013-05-23, Matthew Gilson m.gils...@gmail.com wrote: That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. I don't see any ambiguity. A keyword argument is an argument preceded by an identifier according to the definition. Where are you perceiving wiggle room? The wiggle room comes from the or passed as a value in a dictionary clause. We sort of get caught in a infinite loop there because the stuff that can be passed in a dictionary is a keyword which is an identifer=expression or something passed as a value in a dictionary ... Also the fact that: func(**{foo bar baz:1}) works even though `foo bar baz` isn't a valid identifier, but: func(**{1:3}) doesn't work. -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On 05/23/2013 04:52 PM, Terry Jan Reedy wrote: On 5/23/2013 2:52 PM, Matthew Gilson wrote: This is a question regarding the documentation around dictionary unpacking. The documentation for the call syntax (http://docs.python.org/3/reference/expressions.html#grammar-token-call) says: If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. That's fine, but what is a keyword argument? According to the glossary (http://docs.python.org/3.3/glossary.html): /keyword argument/: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. It appears that the requirement has been relaxed (in the previous quote), so that 'dictionary' should also be changed to 'mapping'. It might not hurt to add 'The key for the value should be an identifier.' As far as I'm concerned, this leads to some ambiguity in whether the keys of the mapping need to be valid identifiers or not. I think you are being too lawyerly. The pretty clear and sensible implication is that the key for the value should be a string with a valid identifier. If it is anything else, you are on your own and deserve any joy or pain that results ;=) Using Cpython, we can do the following: def func(**kwargs): print kwargs d = {'foo bar baz':3} So that might lead us to believe that the keys of the mapping do not need to be valid identifiers. There are two ways to pass args to func to be gathered into kwargs; explicit key=val pairs and **mapping, or both. func(a=1, b='hi', **{'foo bar baz':3}) # {'foo bar baz': 3, 'a': 1, 'b': 'hi'} So func should not expect anything other than identifier strings. However, the previous function does not work with the following dictionary: d = {1:3} because not all the keys are strings. So CPython checks that keys are strings, because that is cheap, but not that the strings are identifiers, because that would be more expensive. Just because an implementation allow somethings (omits a check) for efficiency does not mean you should do it. globals()[1] = 1 works, but is not normally very sensible or useful. Is there a way to petition to get this more rigorously defined? bugs.python.org The problem is that mandating a rigorous check by implementations makes Python slower to the detriment of sensible programmers To be clear, you're saying that func(**{'foo bar baz':3}) is not supported (officially), but it works in CPython because checking that every string in the dict is a valid identifier would be costly. Of course that is sensible and I don't think the behaviour should be changed to the detriment of sensible programmers. However, it would be nice if it was documented somewhere that the above function call is something that a non-sensible programmer would do. Perhaps with a CPython implementation detail type of block. -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On Thursday, May 23, 2013 7:56:19 PM UTC+1, Mark Lawrence wrote: On 23/05/2013 19:19, Andrew Edwards-Adams wrote: On Thursday, May 23, 2013 7:11:28 PM UTC+1, Andrew Berg wrote: On 2013.05.23 11:58, Andrew Edwards-Adams wrote: Hi thanks for the reply Andrew, my first bit of code was heading in the right direction I was managing to pull out the usernames from the JSON, using REGEX. It's also worth mentioning that regexes are almost always the wrong tool, especially for standardized formats like JSON. They can be very useful when nothing saner will get the job done, but are a nasty mess with no real benefit otherwise. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 Thanks Andrew, yes I believe this is what the guy who provided me with the code was thinking. I was about to embark on what was definitely going to be an inefficient long regex. Funny old world, there doesn't appear to be working code but someone is already thinking about definite inefficiency. What evidence do you have to support this claim? -- If you're using GoogleCrap™ please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence haha true Mark, I have made mistakes like this before become ok at coding VBA to achieve things in the most inefficient manner possible. Something that I will learn from for the current python coding project. -- http://mail.python.org/mailman/listinfo/python-list
RE: PEP 378: Format Specifier for Thousands Separator
To: python-list@python.org From: tjre...@udel.edu [...] It's a conflict in the design. A tuple is used to supply multiple arguments to the % operator. So if you want to have a tuple as the first argument, you need to enclose it in another tuple. The problem is that interpolating 1 to many items into a string is *not* a binary operation. The needed hack to pretend that it is, using a tuple to represent multiple items rather than just itself, was one of the reasons for making string formatting a honest function, where multiple items to be formatted are passed as multiple arguments. Thanks so much guys! Now I understand why some people hate %-formatting! I don't think that's a problem because there's no format specifier for tuples in the %-formatting definition[1]. So it's up to the user to make the necessary conversion. I still love the %-formatting style! Can str.format() do the following? f = '%d %d %d' v = '1,2,3' print f % eval(v) If yes, how? [1] http://docs.python.org/2/library/stdtypes.html#string-formatting -- http://mail.python.org/mailman/listinfo/python-list
RE: file I/O and arithmetic calculation
From: denismfmcma...@gmail.com [...] Dear all who involved with responding to my question - Thank you so much for your nice code which really helped me. Hold on a sec? Someone posted code that gave the correct answer to a homework question? -- Denis McMahon, denismfmcma...@gmail.com Not sure what she've asked, but mine certainly do what I think she've asked. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error with python 3.3.2 and https
On Fri, May 24, 2013 at 3:49 AM, asianava...@gmail.com wrote: Yeah that is the case. Once I change the f = opener.open('website') line to a link that has a https I get that socket error. Nothing else changes. I was reading online and came across this site which shows you how if the version of python installed supports ssl. http://morlockhq.blogspot.ca/2008/05/python-tip-checking-to-see-if-your.html When I followed the instructions I got that it wasn't supported, although the ssl.py is in the lib directory. Python was installed from the official python page using the windows installer. Is somehow ssl disabled by default? Do I need to get a third party ssl module? Hrm. Unfortunately those instructions don't work for Python 3... or at least, if they do, then both of my handy installations (one Windows, one Linux) don't have SSL. However, I *can* do 'import ssl' and 'import _ssl', the latter of which is what Lib/socket.py checks for. In Python 3.3's Lib/socket.py there's no mention of ssl anywhere, so I'd be inclined to look elsewhere for support checks. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: What was the project that made you feel skilled in Python?
Chris Angelico ros...@gmail.com writes: Ben Finney ben+pyt...@benfinney.id.au wrote: This resulted in a library for rolling dice in different combinations, and looking up result tables URL:https://pypi.python.org/pypi/alea. Fun fun! Of course, when I hear rolling dice in different combinations, my mind immediately turns to Dungeons and Dragons, where it's plausible to roll d20+7, then roll 2d8+d6+12 to figure out how much damage you did... Yeah, and lots of board games use custom dice with faces specific to that game (symbols, non-consecutive numbers, etc.), so the Die class allows the faces to be any object the application needs. But the hard part of board games is usually the board. A lot of the board games I'm intrigued by don't have much of a board; they use custom cards and tokens and (maybe) dice, and the “board” is an abstraction of where all the pieces are on the table. I used to spend ages trying to draw up a half-decent board, and ended up giving up. By simulate, I'm guessing you mean that you didn't actually draw anything of the sort? Right. The (never completed) application was to simulate the mechanics of that particular game so I could see how it would play out, not be an interactive playable game. I've long been aware there is an enormous amount of UI-programming work involved with interactive playable games. My ambition for that work was quenched from attempting it in my teenage years :-) -- \“With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.” —Raymond Hettinger | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
authentication with python-ldap
import ldap conn = ldap.initialize(ldap://ldap.uci.cu;) conn.protocol_version = ldap.VERSION3 conn.simple_bind_s( uid=xxx,dc=uci,dc=cu, xxx ) Result: Traceback (most recent call last): File console, line 1, in module File /usr/lib/python2.7/dist-packages/ldap/ldapobject.py, line 207, in simple_bind_s return self.result(msgid,all=1,timeout=self.timeout) File /usr/lib/python2.7/dist-packages/ldap/ldapobject.py, line 422, in result res_type,res_data,res_msgid = self.result2(msgid,all,timeout) File /usr/lib/python2.7/dist-packages/ldap/ldapobject.py, line 426, in result2 res_type, res_data, res_msgid, srv_ctrls = self.result3(msgid,all,timeout) File /usr/lib/python2.7/dist-packages/ldap/ldapobject.py, line 432, in result3 ldap_result = self._ldap_call(self._l.result3,msgid,all,timeout) File /usr/lib/python2.7/dist-packages/ldap/ldapobject.py, line 96, in _ldap_call result = func(*args,**kwargs) INVALID_CREDENTIALS: {'desc': 'Invalid credentials'} what is my mistake -- http://mail.python.org/mailman/listinfo/python-list
Re: Ordered dictionaries compared
On 23/05/13 18:44, Dan Stromberg wrote: On Thu, May 23, 2013 at 9:41 AM, duncan smith buzzard@invalid.invalid mailto:buzzard@invalid.invalid wrote: RBT is quicker than Treap for insertion with randomized data, but slower with ordered data. Randomized data will tend to minimize the number of tree rotations needed to keep the RBT balanced, whilst the Treap will be performing rotations to maintain the heap property in an already reasonably well balanced tree. With ordered data the RBT will have to work harder to keep the tree balanced, whilst the Treap will be able to maintain the heap property with fewer rotations. No surprise that find() is generally quicker for RBTs, they tend to be better balanced. Deletion is a bit more confusing. I suppose deletion from a better balanced tree will tend to be quicker, but deletion from a treap constructed from ordered data is (for some reason) quickest of all. All these operations require a call to find(), and that is generally going to be quicker for RBTs. Treaps tend to require fewer subsequent rotations, but they have variable worth (in terms of rebalancing). Looks like RBTs are better than treaps if they are being populated with randomly ordered data, but not if they are being populated with ordered data. RBTs are better for use cases that are heavy on finds. Both types of tree appear to be better balanced (on the basis of the find results) if populated from ordered data. Treaps appear to perform better on insertion, find and deletion when populated from ordered data. Strange. I was comparing randomized data (95% get, 50-50 get and set, 95% set) when I found that treaps were quite a bit faster than red black trees. The code I used is here: http://stromberg.dnsalias.org/svn/python-tree-and-heap-comparison/trunk/ See also https://en.wikipedia.org/wiki/Binary_search_tree#Performance_comparisons , which found that treaps were faster on average the red black trees. Dan, Faster on average, but it depends what you're averaging over. As far as insertion and deletions are concerned my results agree with those in the paper, except they have treaps performing slightly faster than RBTs for insertion with randomly ordered data. Deletion in your code is slightly different to that in mine. It might make a difference. Also, your code doesn't use sentinels (pros and cons). It could be down to implementation details. Duncan -- http://mail.python.org/mailman/listinfo/python-list
Re: serialize a class to XML and back
On May 23, 8:37 pm, Schneider j...@globe.de wrote: My aim is to store instances of this class in a database. Have you considered just pickling the classes instead? -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On Thu, May 23, 2013 at 6:20 PM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Can str.format() do the following? f = '%d %d %d' v = '1,2,3' print f % eval(v) Sure: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 f = {} {} {} v = 1,2,3 print(f.format(*eval(v))) 1 2 3 The * unpacks the tuple returned from eval(), so that you get 3 separate parameters passed to format(), instead of the single tuple. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
not exactly for the homework, but as my starting point of learning thank you so much. -- http://mail.python.org/mailman/listinfo/python-list
RE: PEP 378: Format Specifier for Thousands Separator
Thank you! Hail Eris!!! :) Date: Thu, 23 May 2013 21:17:54 -0400 Subject: Re: PEP 378: Format Specifier for Thousands Separator From: malaclyp...@gmail.com To: carlosnepomuc...@outlook.com CC: python-list@python.org On Thu, May 23, 2013 at 6:20 PM, Carlos Nepomuceno carlosnepomuc...@outlook.commailto:carlosnepomuc...@outlook.com wrote: Can str.format() do the following? f = '%d %d %d' v = '1,2,3' print f % eval(v) Sure: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 f = {} {} {} v = 1,2,3 print(f.format(*eval(v))) 1 2 3 The * unpacks the tuple returned from eval(), so that you get 3 separate parameters passed to format(), instead of the single tuple. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging parallel nose tests?
In article mailman.2027.1369333910.3114.python-l...@python.org, Dave Angel da...@davea.name wrote: On 05/23/2013 09:09 AM, Roy Smith wrote: SNIP nosetests --process-timeout=60 --processes=40 test_api.py Do you have a 40-processor system? No, but many of the tests are I/O bound. And do you have enough RAM to run all of those processes? Yes. The box I'm on now has 8 gig. I'd doing a 40 process run right now, and I've still got 1/2 gig free. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
Carlos Nepomuceno於 2013年5月22日星期三UTC+8上午2時49分28秒寫道: From: alyssonbr...@gmail.com Date: Tue, 21 May 2013 09:03:13 -0300 Subject: Re: PEP 378: Format Specifier for Thousands Separator To: python-list@python.org This work in 3.1+: $ python3 Python 3.1.3 (r313:86834, Nov 28 2010, 11:28:10) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. one_number = 1234567 print('number={:,}'.format(one_number)) number=1,234,567 Thank you, but let me rephrase it. I'm already using str.format() but I'd like to use '%' (BINARY_MODULO) operator instead. I've looked into the source code of CPython 2.7.5 and I've found no evidence of the thousands separator been implemented on formatint() in Objects/unicodeobject.c. I also didn't find the _PyString_FormatLong() used in formatlong(). Where is _PyString_FormatLong() located? So, the question is: Where would I change the CPython 2.7.5 source code to enable '%' (BINARY_MODULO) to format using the thousands separator like str.format() does, such as: sys.stderr.write('%,d\n' % 1234567) 1,234,567 Could a separate instance like the I/O device of a subprocess to be easily available in Python? The next question would be whether the flow of several I/O data streams could be easily piped and manipulated in the high level programming designs without consuming too much resources. -- http://mail.python.org/mailman/listinfo/python-list
Read txt file, add to iptables not working on new host
First, let me say that I have no knowledge of or experience with Python or Linux/Unix. I have a script which was written by a host tech person that ran via cron on my old server. It was designed to read IP addresses from a text file and add them to be blocked on iptables. That way, we could add or remove IPs without involving tech support daily. It worked great. Then we changed hosts and this script is now throwing errors on the new server. This host runs Python 2.6.6. This is the script: #!/usr/bin/python import os,time ##Input, Output, and TimeStamp inFile = open('/var/www/html/mydomain.com/banlist.txt','r') logFile = open('/var/log/banList.log','w') stamp = time.asctime(time.localtime()) ##Daily Flush of blockList rules before re-applying Blocks os.popen('/sbin/iptables -F INPUT') logFile.write(stamp), logFile.write('\n'), logFile.write('Flushing Rules..\n') ##Loop to read in file and Apply rules to IPtables for line in inFile.readlines(): tmp = line.split(';') IP = tmp[0] outPut = os.popen( '/sbin/iptables -A INPUT -s' + ' ' + IP + ' ' + '-j REJECT' ) logFile.write(IP), logFile.write(' - Has been blocked '), logFile.write(stamp),logFile.write The errors we're getting are like these: Bad argument `174.37.65.204' Try `iptables -h' or 'iptables --help' for more information. Bad argument `94.159.162.182' Try `iptables -h' or 'iptables --help' for more information. Bad argument `95.134.132.98' Try `iptables -h' or 'iptables --help' for more information. etc. Entries from the banlist.txt are like these: 200.193.54.138; February 9, 2013, 7:42 am br 87.120.57.4; February 9, 2013, 7:42 am br 82.206.129.160; February 9, 2013, 7:43 am br etc. I know the error points to a bad iptables command. Can someone tell me what change(s) I need to make to this script to get it working again? Thanks. -- My email address on the header is a non-monitored spam catching account. I can be reached via http://www.wvnh.net/contact.htm -- http://mail.python.org/mailman/listinfo/python-list
RE: Read txt file, add to iptables not working on new host
Send the output of the following commands: uname -a /sbin/iptables -V From: notr...@earthlink.net Subject: Read txt file, add to iptables not working on new host Date: Thu, 23 May 2013 22:44:38 -0400 To: python-list@python.org First, let me say that I have no knowledge of or experience with Python or Linux/Unix. I have a script which was written by a host tech person that ran via cron on my old server. It was designed to read IP addresses from a text file and add them to be blocked on iptables. That way, we could add or remove IPs without involving tech support daily. It worked great. Then we changed hosts and this script is now throwing errors on the new server. This host runs Python 2.6.6. This is the script: #!/usr/bin/python import os,time ##Input, Output, and TimeStamp inFile = open('/var/www/html/mydomain.com/banlist.txt','r') logFile = open('/var/log/banList.log','w') stamp = time.asctime(time.localtime()) ##Daily Flush of blockList rules before re-applying Blocks os.popen('/sbin/iptables -F INPUT') logFile.write(stamp), logFile.write('\n'), logFile.write('Flushing Rules..\n') ##Loop to read in file and Apply rules to IPtables for line in inFile.readlines(): tmp = line.split(';') IP = tmp[0] outPut = os.popen( '/sbin/iptables -A INPUT -s' + ' ' + IP + ' ' + '-j REJECT' ) logFile.write(IP), logFile.write(' - Has been blocked '), logFile.write(stamp),logFile.write The errors we're getting are like these: Bad argument `174.37.65.204' Try `iptables -h' or 'iptables --help' for more information. Bad argument `94.159.162.182' Try `iptables -h' or 'iptables --help' for more information. Bad argument `95.134.132.98' Try `iptables -h' or 'iptables --help' for more information. etc. Entries from the banlist.txt are like these: 200.193.54.138; February 9, 2013, 7:42 am br 87.120.57.4; February 9, 2013, 7:42 am br 82.206.129.160; February 9, 2013, 7:43 am br etc. I know the error points to a bad iptables command. Can someone tell me what change(s) I need to make to this script to get it working again? Thanks. -- My email address on the header is a non-monitored spam catching account. I can be reached via http://www.wvnh.net/contact.htm -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with implementing callback functions using ctypes
On Friday, May 10, 2013 12:02:08 AM UTC+5:30, Nobody wrote: This line should be: spiro_to_bezier_strict ( src, len ( src ), byref(bc) ) Without the byref(...), it will try to pass a copy of the structure rather than passing a pointer to it. Wow silly silly mistake of mine, passing an object where a pointer is expected. Alternatively, if I specify: spro_to_bezier_strict.argtypes = [ POINTER(spiro_cp), c_int, POINTER(bezctx) ] it works equally good and apparently automatically converts the object specified to a pointer to it (which is good and intuitive, I guess, though against C practice). I guess if one wants to be safe when interfacing to C functions, one should always specify argtypes (even if not restype). But really, a segfault? I would expect a more meaningful error or an exception to be raised. Or is the black magic occurring at a level lower than where Python's control goes? If I had seen this post I might not have even spent time on Cython. (For some reason Google Groups doesn't send me email updates even if I ask it to.) Using CTYpes I was able to implement a callback with less coding (for this particular requirement) than Cython which required an extra wrapper layer on top of the library to pass through a void* representing the Python callback (or a state variable would have to be used which may mean no thread-safety). But I guess Cython would be faster for those who want that. Even though there is an extra function call every time (for the wrapper) it would be faster since it's at the C level rather than at the Python level (or something like that). Thanks to all who helped on this, and also the people over at the cython-users list who helped me on the Cython wrapper too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with implementing callback functions using ctypes
On Wed, May 8, 2013 at 10:54 PM, dieter die...@handshake.de wrote: jamadagni samj...@gmail.com writes: ... I cannot help you with ctypes. But, if you might be able to use cython, then calling callbacks is not too difficult (you can find an example in e.g. my dm.xmlsec.binding). Note, however, that properly handling the GIL (Global Interpreter Lock) may be of great importance when the Python/C boundary is crossed -- at least when you intend to use your code in a multi thread environment. Cython is good. So is the new cffi, which might be thought of as a safer (API-level) version of ctypes (which is ABI-level). -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope of a class..help???
lokeshkopp...@gmail.com wrote: ok Peter Otten, but how to make a Class global?? Your class IS global. I still don't think you understand what you did wrong. You've tripped into a strange little quirk of scoping. Here is your code with some unimportant lines removes. class Node: def __init__(self, value=None): self.value = value self.next = None ## OK, at this point, you have a global called Node, which is a class. def number_to_LinkedList(numbers): pass list_numbers = list(numbers) head_node = Node() # ... current_node.next = None while Node: print Node.data Python actually does a first scan through your function before it starts to compile it. When it does the scan, it sees you use the name Node as a local variable. At that point, it remembers that in this function scope, 'Node' is a local name. Now, it codes to compile the class. When it encounters Node() for the first time, it sees that Node is not defined locally, even though it was supposed to be a local name. You are assuming that the first Node() in that function will automatically refer to the global class. It won't. The only way to solve this dilemma is to change the name you use in the while loop. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
[issue13483] Use VirtualAlloc to allocate memory arenas
Martin v. Löwis added the comment: Ah ok. I guess tuples.py then indeed demonstrates a saving. I'll apply the patch. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue13483 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7727] xmlrpc library returns string which contain null ( \x00 )
Martin v. Löwis added the comment: I'm still skeptical that a new exception should be introduced in 2.7.x, or 3.3 (might this break existing setups?). I suggest to ask the release manager for a decision. But if this is done, then I propose to add the following text to ServerProxy: versionchanged (2.7.6): Sending strings with characters that are ill-formed in XML (e.g. \x00) now raises ValueError. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7727 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18031] The Python Tutorial says % string formatting will be removed
Roundup Robot added the comment: New changeset ef037ad304c1 by Raymond Hettinger in branch '2.7': Issue #18031: %-formatting isn't dead yet and might pull through. http://hg.python.org/cpython/rev/ef037ad304c1 -- nosy: +python-dev ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18031 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18031] The Python Tutorial says % string formatting will be removed
Roundup Robot added the comment: New changeset e1d6140b02f0 by Raymond Hettinger in branch '3.3': Issue #18031: %-formatting isn't dead yet and might pull through. http://hg.python.org/cpython/rev/e1d6140b02f0 -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18031 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18031] The Python Tutorial says % string formatting will be removed
Changes by Raymond Hettinger raymond.hettin...@gmail.com: -- resolution: - fixed status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18031 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18042] Provide enum.unique class decorator
New submission from Nick Coghlan: Another attempt at tackling the but I want to ensure my enum values are unique problem that PEP 435 deliberately chose not to handle. My previous suggestion (in issue 17959) was rightly rejected due to the other problems it caused, but this idea is much cleaner and simpler. All we would need to do is provide the following class decorator in the enum module: def unique(new_enum): for name, member in new_enum.__members__.items(): if name != member.name: msg = Alias {!r} for {!r} not permitted in unique Enum raise TypeError(msg.format(name, member)) return new_enum Used as so: @enum.unique ... class MyEnum(enum.Enum): ... a = 1 ... b = 2 ... c = 1 ... Traceback (most recent call last): File stdin, line 2, in module File stdin, line 6, in unique TypeError: Alias 'c' for MyEnum.a: 1 not permitted in unique Enum -- components: Library (Lib) messages: 189854 nosy: ncoghlan priority: normal severity: normal status: open title: Provide enum.unique class decorator type: enhancement versions: Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18042 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18042] Provide enum.unique class decorator
Changes by Nick Coghlan ncogh...@gmail.com: -- dependencies: +Code, test, and doc review for PEP-0435 Enum nosy: +eli.bendersky, ethan.furman ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18042 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17986] Alternative async subprocesses (pep 3145)
Charles-François Natali added the comment: I'm not familiar with windows, but if I understand the patch correctly, you can only select from a single subprocess at a time, which is IMO an important limitation. Also, the fact that close() can fail with BlockingIOError is really a pain, and makes writing portable code complicated, but I know you can't do anything about it ;-) In short, that would be nice, but Windows seems to make it so limited/complicated that I'm not sure that would be really useful, but once again I don't use Windows, so I can't make a call. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17986 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17844] Add link to alternatives for bytes-to-bytes codecs
Roundup Robot added the comment: New changeset 85e8414060b4 by Nick Coghlan in branch '3.3': Issue 17844: Clarify meaning of different codec tables http://hg.python.org/cpython/rev/85e8414060b4 New changeset 801567d6302c by Nick Coghlan in branch 'default': Merge issue 17844 from 3.3 http://hg.python.org/cpython/rev/801567d6302c -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17844 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17844] Add link to alternatives for bytes-to-bytes codecs
Nick Coghlan added the comment: Thanks for initiating this Serhiy :) -- resolution: - fixed stage: patch review - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17844 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com