content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: CPython/Jython cross-implementation GUI I need to make some GUIs for a Jython application, but would like to minimize translation time should the project switch over to CPython. HTML or XUL are possibilities, but ones that I'd like to avoid. Any ideas on a cross-implementation pythonic GUI toolkit? A: From the d...
CPython/Jython cross-implementation GUI
I need to make some GUIs for a Jython application, but would like to minimize translation time should the project switch over to CPython. HTML or XUL are possibilities, but ones that I'd like to avoid. Any ideas on a cross-implementation pythonic GUI toolkit?
[ "From the discussion here, it doesn't look as though there is a single GUI toolkit that can be used across both Jython and CPython. There have been attempts like wx4j (wxWindows for Java) but these are not actively maintained.\n" ]
[ 0 ]
[]
[]
[ "jython", "python", "user_interface" ]
stackoverflow_0001948925_jython_python_user_interface.txt
Q: permutations of two lists in python I have two lists like: list1 = ['square','circle','triangle'] list2 = ['red','green'] How can I create all permutations of these lists, like this: [ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'triang...
permutations of two lists in python
I have two lists like: list1 = ['square','circle','triangle'] list2 = ['red','green'] How can I create all permutations of these lists, like this: [ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'trianglered', 'trianglegreen', 'redtriangle',...
[ "You want the itertools.product method, which will give you the Cartesian product of both lists.\n>>> import itertools\n>>> a = ['foo', 'bar', 'baz']\n>>> b = ['x', 'y', 'z', 'w']\n\n>>> for r in itertools.product(a, b): print r[0] + r[1]\nfoox\nfooy\nfooz\nfoow\nbarx\nbary\nbarz\nbarw\nbazx\nbazy\nbazz\nbazw\n\nYo...
[ 103, 45, 17, 11, 6 ]
[]
[]
[ "python" ]
stackoverflow_0001953194_python.txt
Q: Retrieving doubly raised exceptions original stack trace in python If I have a scenario where an exception is raised, caught, then raised again inside the except: block, is there a way to capture the initial stack frame from which it was raised? The stack-trace that gets printed as python exits describes the pla...
Retrieving doubly raised exceptions original stack trace in python
If I have a scenario where an exception is raised, caught, then raised again inside the except: block, is there a way to capture the initial stack frame from which it was raised? The stack-trace that gets printed as python exits describes the place where the exception is raised a second time. Is there a way to raise...
[ "It's a common mistake to re-raise an exception by specifying the exception instance again, like this:\nexcept Exception, ex:\n # do something\n raise ex\n\nThis strips the original traceback info and starts a new one. What you should do instead is this, without explicitly specifying the exception (i.e. us...
[ 11 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001953237_exception_python.txt
Q: email last lines from a text file in python I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i ha...
email last lines from a text file in python
I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciated. ...
[ "There is no way for your machine to send mail without connecting to a server (otherwise how would the mail get out of your machine?). Most people have a readily available SMTP server provided for them, either by their company (if this is on an intranet) or by their ISP (if a home user). You would need the host n...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "email", "python", "smtp" ]
stackoverflow_0001952734_email_python_smtp.txt
Q: How do I display notifications from `django-notification`? I've been reading the docs for django-notification, and they seem to cover creating notifications just fine, but not how to display them to users. Is there a good reference for this out there, and my Google-fu has just failed me? If not, can someone give m...
How do I display notifications from `django-notification`?
I've been reading the docs for django-notification, and they seem to cover creating notifications just fine, but not how to display them to users. Is there a good reference for this out there, and my Google-fu has just failed me? If not, can someone give me some pointers here? Thanks.
[ "The answer is you have to build it into your own templates. This can be as simple as the following snippet:\n<table>\n <caption>{% trans \"Notices\" %}</caption> \n <thead>\n <tr>\n <th>{% trans \"Type\" %}</th>\n <th>{% trans \"Message\" %}</th>\n <th>{% trans \"Date ...
[ 4, 2 ]
[]
[]
[ "django", "django_notification", "python" ]
stackoverflow_0001609775_django_django_notification_python.txt
Q: Building a weakref cache in python I'm currently coding a project in python where I need a sort of cache of generic objects, I have settled on using WeakValueDictionaries for this. These generic objects are often referenced by many other non-generic objects. My main problem though is that I can't seem to wrap my h...
Building a weakref cache in python
I'm currently coding a project in python where I need a sort of cache of generic objects, I have settled on using WeakValueDictionaries for this. These generic objects are often referenced by many other non-generic objects. My main problem though is that I can't seem to wrap my head around a way of making these WeakVal...
[ "Maybe I'm not understanding your question, but making a dictionary of weakly referenced values available to your code isn't really any different from making a dictionary of anything else available to your code. I would store a reference to the WeakValueDictionary on:\n\neach instance (referenced via self)\na clas...
[ 3 ]
[]
[]
[ "caching", "python", "weak_references" ]
stackoverflow_0001953666_caching_python_weak_references.txt
Q: Are CPython, IronPython, Jython scripts compatible with each other? I am pretty sure that python scripts will work in all three, but I want to make sure. I have read here and there about editors that can write CPython, Jython, IronPython and I am hoping that I am looking to much into the distinction. My situation...
Are CPython, IronPython, Jython scripts compatible with each other?
I am pretty sure that python scripts will work in all three, but I want to make sure. I have read here and there about editors that can write CPython, Jython, IronPython and I am hoping that I am looking to much into the distinction. My situation is I have 3 different api's that I want to test. Each api performs the ...
[ "The short answer is: Sometimes.\nSome projects built on top of IronPython may not work with CPython, and some CPython modules that are written in C (e.g. NumPy) will not work with IronPython.\nOn a similar note, while Jython implements the language specification, it has several incompatibilities with CPython (for ...
[ 10 ]
[]
[]
[ "boost_python", "ironpython", "jython", "python", "testing" ]
stackoverflow_0001953989_boost_python_ironpython_jython_python_testing.txt
Q: PyODBC and Microsoft Access: Inconsistent results from simple query I am using pyodbc, via Microsoft Jet, to access the data in a Microsoft Access 2003 database from a Python program. The Microsoft Access database comes from a third-party; I am only reading the data. I have generally been having success in extract...
PyODBC and Microsoft Access: Inconsistent results from simple query
I am using pyodbc, via Microsoft Jet, to access the data in a Microsoft Access 2003 database from a Python program. The Microsoft Access database comes from a third-party; I am only reading the data. I have generally been having success in extracting the data I need, but I recently noticed some discrepancies. I have bo...
[ "can you give us an obfuscated database that shows this problem? I've never experienced this. At least give the table definitions -- are any of the columns floats or decimal?\n", "This might sound stupid. But...\nIs the path to actual database & connection string (DSN) point to same file location?\n", "Do you...
[ 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "jet", "ms_access", "odbc", "pyodbc", "python" ]
stackoverflow_0000827502_jet_ms_access_odbc_pyodbc_python.txt
Q: Changing properties of inherited field I want to alter properties of a model field inherited from a base class. The way I try this below does not seem to have any effect. Any ideas? def __init__(self, *args, **kwargs): super(SomeModel, self).__init__(*args, **kwargs) f = self._meta.get_field('some_field')...
Changing properties of inherited field
I want to alter properties of a model field inherited from a base class. The way I try this below does not seem to have any effect. Any ideas? def __init__(self, *args, **kwargs): super(SomeModel, self).__init__(*args, **kwargs) f = self._meta.get_field('some_field') f.blank = True f.help_text = 'This ...
[ "So.. You need to change blank and help_text attributes.. And I assume that you want this feature just so the help_text is displayed in forms, and form does not raise \"this field is required\"\nSo do this in forms:\nclass MyForm(ModelForm):\n class Meta:\n model = YourModel\n\n some_field = forms.CharFiel...
[ 3, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001940459_django_django_models_python.txt
Q: How can I debug a problem calling Python's copy.deepcopy() against a custom type? In my code I'm trying to take copies of instances a class using copy.deepcopy. The problem is that under some circumstances it is erroring with the following error: TypeError: 'object.__new__(NotImplementedType) is not safe, use Not...
How can I debug a problem calling Python's copy.deepcopy() against a custom type?
In my code I'm trying to take copies of instances a class using copy.deepcopy. The problem is that under some circumstances it is erroring with the following error: TypeError: 'object.__new__(NotImplementedType) is not safe, use NotImplementedType.__new__()' After much digging I have found that I am able to reproduce...
[ "In the end I did some digging in the copy source code and came up with the following solution:\nfrom copy import deepcopy, _deepcopy_dispatch\nfrom types import ModuleType\n\nclass MyType(object):\n\n def __init__(self):\n self.module = __builtins__\n\n def copy(self):\n ''' Patch the deepcopy ...
[ 3, 1, 1 ]
[]
[]
[ "deep_copy", "python" ]
stackoverflow_0001941887_deep_copy_python.txt
Q: How can I run 2 servers at once in Python? I need to run 2 servers at once in Python using the threading module, but to call the function run(), the first server is running, but the second server does not run until the end of the first server. This is the source code: import os import sys import threading n_serve...
How can I run 2 servers at once in Python?
I need to run 2 servers at once in Python using the threading module, but to call the function run(), the first server is running, but the second server does not run until the end of the first server. This is the source code: import os import sys import threading n_server = 0 n_server_lock = threading.Lock() class Se...
[ "You don't want to join() in your __init__ function. This is causing the system to block until each thread finishes.\nI would recommend you restructure your program so your main function looks more like the following:\nif name == \"__main__\":\n servers = [MainServer(), DownloadServer()]\n for s in servers:\n...
[ 6 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001954549_multithreading_python.txt
Q: Python instance method in C Consider the following Python (3.x) code: class Foo(object): def bar(self): pass foo = Foo() How to write the same functionality in C? I mean, how do I create an object with a method in C? And then create an instance from it? Edit: Oh, sorry! I meant the same functionality ...
Python instance method in C
Consider the following Python (3.x) code: class Foo(object): def bar(self): pass foo = Foo() How to write the same functionality in C? I mean, how do I create an object with a method in C? And then create an instance from it? Edit: Oh, sorry! I meant the same functionality via Python C API. How to create a...
[ "You can't! C does not have \"classes\", it only has structs. And a struct cannot have code (methods or functions).\nYou can, however, fake it with function pointers:\n/* struct object has 1 member, namely a pointer to a function */\nstruct object {\n int (*class)(void);\n};\n\n/* create a variable of type `stru...
[ 3, 3, 2 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0001954494_c_python_python_c_api.txt
Q: Can I store a python dictionary in google's BigTable datastore without serializing it explicitly? I have a python dictionary that I would like to store in Google's BigTable datastore (it is an attribute in a db.Model class). Is there an easy way to do this? i.e. using a db.DictionaryProperty? Or do I have to use ...
Can I store a python dictionary in google's BigTable datastore without serializing it explicitly?
I have a python dictionary that I would like to store in Google's BigTable datastore (it is an attribute in a db.Model class). Is there an easy way to do this? i.e. using a db.DictionaryProperty? Or do I have to use pickle to serialize my dictionary? My dictionary is relatively straight forward. It consists of strings...
[ "Here's another approach:\nclass DictProperty(db.Property):\n data_type = dict\n\n def get_value_for_datastore(self, model_instance):\n value = super(DictProperty, self).get_value_for_datastore(model_instance)\n return db.Blob(pickle.dumps(value))\n\n def make_value_from_datastore(self, value):\n if val...
[ 8, 1, 1 ]
[]
[]
[ "google_app_engine", "pickle", "python" ]
stackoverflow_0001953784_google_app_engine_pickle_python.txt
Q: What's the point of a main function and/or __name__ == "__main__" check in Python? I occasionally notice something like the following in Python scripts: if __name__ == "__main__": # do stuff like call main() What's the point of this? A: Having all substantial Python code live inside a function (i.e., not at...
What's the point of a main function and/or __name__ == "__main__" check in Python?
I occasionally notice something like the following in Python scripts: if __name__ == "__main__": # do stuff like call main() What's the point of this?
[ "Having all substantial Python code live inside a function (i.e., not at module top level) is a crucial performance optimization as well as an important factor in good organization of code (the Python compiler can optimize access to local variables in a function much better than it can optimize \"local\" variables ...
[ 26, 8, 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001954700_python.txt
Q: How do I access a object's method when the method's name is in a variable? Say I have a class object named test. test has various methods, one of them is whatever() . I have a variable named method = "whatever" How can I access the method using the variable with test? Thanks! A: Get the attribute with getattr: m...
How do I access a object's method when the method's name is in a variable?
Say I have a class object named test. test has various methods, one of them is whatever() . I have a variable named method = "whatever" How can I access the method using the variable with test? Thanks!
[ "Get the attribute with getattr:\nmethod = \"whatever\"\ngetattr(test, method)\n\nYou can also call it:\ngetattr(test, method)()\n\n", "To access the method, getattr(test, test.method); this way you can bind it to a variable, return it as a function result, pass it as an argument, and so forth. To call it as wel...
[ 9, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001954840_python.txt
Q: call python modules from java classes? is it possible, by using jython to call jython classes from java code? If yes, how please? A: Yes - the Jython FAQ has a specific entry about this. A: Nice article regarding this issue Or just try Jython Jython Project Page
call python modules from java classes?
is it possible, by using jython to call jython classes from java code? If yes, how please?
[ "Yes - the Jython FAQ has a specific entry about this.\n", "Nice article regarding this issue\nOr just try Jython\nJython Project Page\n" ]
[ 3, 3 ]
[]
[]
[ "class", "java", "jython", "module", "python" ]
stackoverflow_0001954887_class_java_jython_module_python.txt
Q: Basics of SymPy I am just starting to play with SymPy and I am a bit surprised by some of its behavior, for instance this is not the results I would expect: >>> import sympy as s >>> (-1)**s.I == s.E**(-1* s.pi) False >>> s.I**s.I == s.exp(-s.pi/2) False Why are these returning False and is there a way to get it ...
Basics of SymPy
I am just starting to play with SymPy and I am a bit surprised by some of its behavior, for instance this is not the results I would expect: >>> import sympy as s >>> (-1)**s.I == s.E**(-1* s.pi) False >>> s.I**s.I == s.exp(-s.pi/2) False Why are these returning False and is there a way to get it to convert from one w...
[ "From the FAQ:\nWhy does SymPy say that two equal expressions are unequal?\nThe equality operator (==) tests whether expressions have identical form, not whether they are mathematically equivalent.\nTo make equality testing useful in basic cases, SymPy tries to rewrite mathematically equivalent expressions to a can...
[ 9, 0 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0001954799_python_sympy.txt
Q: Python: which XML parsing library will work out-of-the-box for Python 2.4 and up? How can I make sure that my Python script, which will be doing some XML parsing, will Just Work with Python 2.4, 2.5 and 2.6? Specifically, which (if any) XML parsing library is present in, and compatible between, all those versions?...
Python: which XML parsing library will work out-of-the-box for Python 2.4 and up?
How can I make sure that my Python script, which will be doing some XML parsing, will Just Work with Python 2.4, 2.5 and 2.6? Specifically, which (if any) XML parsing library is present in, and compatible between, all those versions? Edit: the working-out-of-the-box requirement is in place because the XML parsing I'm g...
[ "minidom is available in Python 2.0 and later.\nHowever, if I were you, I would strongly consider using ElementTree which is available in Python 2.5 and later. Its syntax is much more pleasant.\n2.4 users can reasonably easily download ElementTree, 2.5+ it will work without any additional dependencies. But I may ...
[ 8, 5, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001954923_python_xml.txt
Q: Get html output from python code I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code? A: output = "<html><body><table>" for key in your_dict: output += "<tr><td>%s</td><td>%s</td></tr>" % (key, your_dict[key]) out...
Get html output from python code
I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?
[ "output = \"<html><body><table>\"\nfor key in your_dict:\n output += \"<tr><td>%s</td><td>%s</td></tr>\" % (key, your_dict[key])\noutput += \"</table></body></html>\nprint output\n\n", "You can use a template engine like Jinja. A list of engines for templating is available here.\n", "You maybe interested by ma...
[ 10, 2, 1, 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0001953649_html_python.txt
Q: python foreign character in csv I have a little csv which contains foreign characters, like Chinese. How can I display them in Chinese instead of those \xa5\\xa4\ string??? Thanks A: Have you read the docs for the csv module? It includes examples of how to wrap csv to handle Unicode data.
python foreign character in csv
I have a little csv which contains foreign characters, like Chinese. How can I display them in Chinese instead of those \xa5\\xa4\ string??? Thanks
[ "Have you read the docs for the csv module? It includes examples of how to wrap csv to handle Unicode data.\n" ]
[ 3 ]
[]
[]
[ "encode", "python" ]
stackoverflow_0001955301_encode_python.txt
Q: __getattr__ keeps returning None even when I attempt to return values Try running the following code: class Test(object): def func_accepting_args(self,prop,*args): msg = "%s getter/setter got called with args %s" % (prop,args) print msg #this is prented return msg #Why is None returned? def __getattr_...
__getattr__ keeps returning None even when I attempt to return values
Try running the following code: class Test(object): def func_accepting_args(self,prop,*args): msg = "%s getter/setter got called with args %s" % (prop,args) print msg #this is prented return msg #Why is None returned? def __getattr__(self,name): if name.startswith("get_") or name.startswith("set_"): ...
[ "return_method() doesn't return anything. It should return the result of the wrapped func_accepting_args():\ndef return_method(*args):\n return self.func_accepting_args(prop,*args)\n\n", "Because return_method() doesn't return a value. It just falls out the bottom, hence you get None.\n" ]
[ 6, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0001955363_metaprogramming_python.txt
Q: Why is this a python syntax error during an initialisation? This code: class Todo: def addto(self, list_name="", text=""): """ Adds an item to the specified list. """ if list_name == "": list_name = sys.argv[2] text = ''.join(sys.argv[3:] todo_li...
Why is this a python syntax error during an initialisation?
This code: class Todo: def addto(self, list_name="", text=""): """ Adds an item to the specified list. """ if list_name == "": list_name = sys.argv[2] text = ''.join(sys.argv[3:] todo_list = TodoList(getListFilename(list_name)) produces a syntax erro...
[ "you need to close this )\ntext = ''.join(sys.argv[3:]\n\n" ]
[ 11 ]
[]
[]
[ "python", "syntax", "syntax_error" ]
stackoverflow_0001955448_python_syntax_syntax_error.txt
Q: Comparison of the multiprocessing module and pyro? I use pyro for basic management of parallel jobs on a compute cluster. I just moved to a cluster where I will be responsible for using all the cores on each compute node. (On previous clusters, each core has been a separate node.) The python multiprocessing mo...
Comparison of the multiprocessing module and pyro?
I use pyro for basic management of parallel jobs on a compute cluster. I just moved to a cluster where I will be responsible for using all the cores on each compute node. (On previous clusters, each core has been a separate node.) The python multiprocessing module seems like a good fit for this. I notice it can al...
[ "EDIT: I'm changing my answer so you avoid pain. multiprocessing is immature, the docs on BaseManager are INCORRECT, and if you're an object-oriented thinker that wants to create shared objects on the fly at run-time, USE PYRO OR YOU WILL SERIOUSLY REGRET IT! If you are just doing functional programming using a s...
[ 15 ]
[]
[]
[ "multiprocessing", "pyro", "python", "rpc" ]
stackoverflow_0001171767_multiprocessing_pyro_python_rpc.txt
Q: Writing a manager to filter query set results I have the following code: class GroupDepartmentManager(models.Manager): def get_query_set(self): return super(GroupDepartmentManager, self).get_query_set().filter(group='1') class Department(models.Model): name = models.CharField(max_length=128) group = model...
Writing a manager to filter query set results
I have the following code: class GroupDepartmentManager(models.Manager): def get_query_set(self): return super(GroupDepartmentManager, self).get_query_set().filter(group='1') class Department(models.Model): name = models.CharField(max_length=128) group = models.ForeignKey(Group) def __str__(self): return ...
[ "I have a hunch that replacing the default Manager on objects in this manner might not be good idea, especially if you're planning on using the admin site... Even if it helps you with your Employees, it won't help you at all when handling Departments. How about a second property providing a restricted view on Depar...
[ 4, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001954664_django_django_models_python.txt
Q: i don't know __iter__ in python,who can give me a good code example my code run wrong class a(object): def __iter(self): return 33 b={'a':'aaa','b':'bbb'} c=a() print b.itervalues() print c.itervalues() Please try to use the code, rather than text, because my English is not very good, thank you A: a...
i don't know __iter__ in python,who can give me a good code example
my code run wrong class a(object): def __iter(self): return 33 b={'a':'aaa','b':'bbb'} c=a() print b.itervalues() print c.itervalues() Please try to use the code, rather than text, because my English is not very good, thank you
[ "a. Spell it right: not\n def __iter(self):\n\nbut:\n def __iter__(self):\n\nwith __ before and after iter.\nb. Make the body right: not\nreturn 33\n\nbut:\nyield 33\n\nor\n return iter([33])\nIf you return a value from __iter__, return an iterator (an iterable, as in return [33], is almost as good but not q...
[ 17, 5, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0001956623_iterator_python.txt
Q: Adding authentication to beanstalkd from Python (or any UNIX) client So what I like about beanstalkd: small, lightweight, has priorities for messages, has a great set of clients, easy to use. What I dislike about beanstalkd: the lack of authentication menaing if you can connect to the port you can insert messages...
Adding authentication to beanstalkd from Python (or any UNIX) client
So what I like about beanstalkd: small, lightweight, has priorities for messages, has a great set of clients, easy to use. What I dislike about beanstalkd: the lack of authentication menaing if you can connect to the port you can insert messages into it. So my thoughts are to either firewall it to trusted systems (wh...
[ "I have to disagree about the practice of just having connections being held open indefinitely, since I use BeanstalkD from a web-scripting language (php) for various events. The overhead of opening a secure connection would be something I would have to think very carefully over.\nLike Memcached, beanstalkd is des...
[ 4, 1, 0 ]
[]
[]
[ "beanstalkd", "python" ]
stackoverflow_0001692346_beanstalkd_python.txt
Q: How to get latest timestamp in a column? I have a timestamp column in my t1 table. The format is as: 2009-12-24 06:17:34 There are many entries as such. How do we query from views to get the latest timestamp A: ModelClass.objects.latest(timestamp_field)
How to get latest timestamp in a column?
I have a timestamp column in my t1 table. The format is as: 2009-12-24 06:17:34 There are many entries as such. How do we query from views to get the latest timestamp
[ "ModelClass.objects.latest(timestamp_field)\n\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001957021_django_python.txt
Q: why my "eval" function doesn't work ,i think it can be print 'b',but not a='''b="ddd"''' eval(repr(a)) print str(a) print b Please try to use the code, rather than text, because my English is not very good, thank you A: Use: eval(compile(a,'<string>','exec')) instead of: eval(repr(a)) Transcript: >>> a='''b="...
why my "eval" function doesn't work ,i think it can be print 'b',but not
a='''b="ddd"''' eval(repr(a)) print str(a) print b Please try to use the code, rather than text, because my English is not very good, thank you
[ "Use:\neval(compile(a,'<string>','exec'))\n\ninstead of:\neval(repr(a))\n\nTranscript:\n>>> a='''b=\"ddd\"'''\n>>> eval(compile(a,'<string>','exec'))\n>>> print str(a)\nb=\"ddd\"\n>>> print b\nddd\n\nThe problem is that you're actually executing the statement 'b=\"ddd\"' which is not an assignment to b but an evalu...
[ 3, 2, 0 ]
[]
[]
[ "eval", "exec", "python" ]
stackoverflow_0001957086_eval_exec_python.txt
Q: How do I generate a random string (of length X, a-z only) in Python? Possible Duplicate: python random string generation with upper case letters and digits How do I generate a String of length X a-z in Python? A: ''.join(random.choice(string.lowercase) for x in range(X)) A: If you want no repetitions: import...
How do I generate a random string (of length X, a-z only) in Python?
Possible Duplicate: python random string generation with upper case letters and digits How do I generate a String of length X a-z in Python?
[ "''.join(random.choice(string.lowercase) for x in range(X))\n\n", "If you want no repetitions:\nimport string, random\n''.join(random.sample(string.ascii_lowercase, X))\n\nIf you DO want (potential) repetitions:\nimport string, random\n''.join(random.choice(string.ascii_lowercase) for _ in xrange(X)))\n\nThat's a...
[ 64, 31 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001957273_python_string.txt
Q: i don't know why iter(not __iter__) function use in this place,what is the mean of iter in this code i don't know "self._iterator = iter(self._container)"in next code. in django.http : class HttpResponse(object): def __iter__(self): self._iterator = iter(self._container) return self def ne...
i don't know why iter(not __iter__) function use in this place,what is the mean of iter in this code
i don't know "self._iterator = iter(self._container)"in next code. in django.http : class HttpResponse(object): def __iter__(self): self._iterator = iter(self._container) return self def next(self): chunk = self._iterator.next() if isinstance(chunk, unicode): chunk =...
[ "An iterator can be iterated:\nfor item in mylist:\n print item\n\nfor key,item in enumerate(mylist):\n print key,\":\",item\n\nfor i in range(0,50):\n print i\n\nTo use for item in X, X must be iterable.\nYou can make your class iterable by adding next(self) etc, as in your sample. So with\nclass a(object...
[ 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0001957329_iterator_python.txt
Q: Why python super does not accept only instance? In python 2.x, super accepts the following cases class super(object) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | ...
Why python super does not accept only instance?
In python 2.x, super accepts the following cases class super(object) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: ...
[ "super(ClassType, self).__init__() is not redundant in a cooperative multiple inheritance scheme -- ClassType is not necessarily the type of self, but the class from which you want to do the cooperative call to __init__.\nIn the class hierarchy C inherits B inherits A, in C.__init__ you want to call superclass' ini...
[ 6, 3 ]
[]
[]
[ "language_design", "python" ]
stackoverflow_0001957251_language_design_python.txt
Q: How to override the [] operator in Python? What is the name of the method to override the [] operator (subscript notation) for a class in Python? A: You need to use the __getitem__ method. class MyClass: def __getitem__(self, key): return key * 2 myobj = MyClass() myobj[3] #Output: 6 And if you're ...
How to override the [] operator in Python?
What is the name of the method to override the [] operator (subscript notation) for a class in Python?
[ "You need to use the __getitem__ method.\nclass MyClass:\n def __getitem__(self, key):\n return key * 2\n\nmyobj = MyClass()\nmyobj[3] #Output: 6\n\nAnd if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:\n>>> myobj[5] = 1\nTraceback (most ...
[ 406, 80, 22 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0001957780_operator_overloading_python.txt
Q: deleting old folders with datetime function I am trying to delete old folders and I am asking does anyone know how to set up a variable that allows me to check the variable 'todaystr' which is today's date and minus 7 days of this string and store it another variable. I am wanting to automatically delete old files...
deleting old folders with datetime function
I am trying to delete old folders and I am asking does anyone know how to set up a variable that allows me to check the variable 'todaystr' which is today's date and minus 7 days of this string and store it another variable. I am wanting to automatically delete old files after a week. Below shows the variable 'todaystr...
[ "import datetime\nimport os\nimport shutil\n\nthreshold = datetime.datetime.now() + datetime.timedelta(days=-7)\nfile_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folder_name'))\n\nif file_time < threshold:\n shutil.rmtree('/folder_name')\n\n", "I relation to the above answer it works very well, t...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001953958_python.txt
Q: mapping two list I have two list like this: list1 = [{'id':1, 'name':'foo', 'age':20}, {'id':2, 'name':'foo', 'age':20}] list2 = [{'id':2, 'created':'2004-12-23'}, {'id':12, 'created':'2004-12-23'}, {'id':1, 'created':'2004-12-23'}] list1 = [{'id':1, 'name':'foo', 'age':20, 'match':True}, {'i...
mapping two list
I have two list like this: list1 = [{'id':1, 'name':'foo', 'age':20}, {'id':2, 'name':'foo', 'age':20}] list2 = [{'id':2, 'created':'2004-12-23'}, {'id':12, 'created':'2004-12-23'}, {'id':1, 'created':'2004-12-23'}] list1 = [{'id':1, 'name':'foo', 'age':20, 'match':True}, {'id':2, 'name':'foo', 'a...
[ "set2 = set(x['id'] for x in list2)\nfor entry in list1:\n if entry['id'] in set2:\n entry['match'] = True\n\nOR\nset2 = set(x['id'] for x in list2)\nfor entry in list1:\n entry['match'] = entry['id'] in set2\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001957877_python.txt
Q: char to keycode in python I want to be able to translate a string to keycode to write it with Xlib (to simulate user action on linux). The keycode are not the ascii but the code you get when you do use xev on linuxKeyPress event, serial 33, synthetic NO, window 0x6400001, root 0x13c, subw 0x0, time 51212100, ...
char to keycode in python
I want to be able to translate a string to keycode to write it with Xlib (to simulate user action on linux). The keycode are not the ascii but the code you get when you do use xev on linuxKeyPress event, serial 33, synthetic NO, window 0x6400001, root 0x13c, subw 0x0, time 51212100, (259,9), root:(262,81), sta...
[ "I've found this code which is doing exactly what I wanted.\nIt uses the function display.keysym_to_keycode(Xlib.XK.string_to_keysym(char))\n", "The keycodes depend not only on the keyboard hardware, but also on the user's preference for keyboard layout -- a user may use a dvorak layout on a qwerty keyboard, for ...
[ 6, 4 ]
[]
[]
[ "keycode", "linux", "python" ]
stackoverflow_0001957867_keycode_linux_python.txt
Q: Functions not executing in Python I have a program that runs when the functions have not been defined. When I put code into a function, it does not execute the code it contains. Why? Some of the code is: def new_directory(): if not os.path.exists(current_sandbox): os.mkdir(current_sandbox) A: Your c...
Functions not executing in Python
I have a program that runs when the functions have not been defined. When I put code into a function, it does not execute the code it contains. Why? Some of the code is: def new_directory(): if not os.path.exists(current_sandbox): os.mkdir(current_sandbox)
[ "Your code is actually a definition of a new_directory function. It won't be executed unless you make a call to new_directory().\nSo, when you want to execute the code from your post, just add a function call like this:\ndef new_directory():\n\n if not os.path.exists(current_sandbox):\n os.mkdir(current_sandbox)\...
[ 4, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001958134_python.txt
Q: django templatetags template , combine {{ }} method call with template tag context variable i m trying to make the result of a template tag dependent from another template tag. the use case is the following. i have a headers list which contains all the columns i want to show in a table + the column of the model th...
django templatetags template , combine {{ }} method call with template tag context variable
i m trying to make the result of a template tag dependent from another template tag. the use case is the following. i have a headers list which contains all the columns i want to show in a table + the column of the model they are showing +whether they are visible or not. LIST_HEADERS = ( ('Title', 'title', True), ...
[ "I would do this as a filter, as they provide an easy way to render a result dependent on the value of a variable.\n@register.filter\ndef field_from_name(instance, field_name):\n return getattr(instance, field_name, None)\n\nand then in the template:\n{{ model_instance|field_from_name:header.model_column }} \n\n...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001958286_django_python.txt
Q: why my extjs combobox is not filled dynamically? Here is my Extjs onReady function var store = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({ url: '/loginjson.json' }), rea...
why my extjs combobox is not filled dynamically?
Here is my Extjs onReady function var store = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({ url: '/loginjson.json' }), reader: new Ext.data.JsonReader( ...
[ "If you are expecting the ComboBox to behave more like an HTML select field then add to your ComboBox config the property:\ntriggerAction: 'all'\n\nThis will ensure that all items in the store will be displayed when the field's trigger button is clicked.\nThe ComboBox config will also be needing a valueField proper...
[ 4, 0 ]
[]
[]
[ "combobox", "django", "extjs", "python" ]
stackoverflow_0001957578_combobox_django_extjs_python.txt
Q: Why are there dummy modules in sys.modules? Importing the standard "logging" module pollutes sys.modules with a bunch of dummy entries: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 >>> import sys >>> import logging >>> sorted(x for x in sys.modules.keys() if 'log' in x) ['l...
Why are there dummy modules in sys.modules?
Importing the standard "logging" module pollutes sys.modules with a bunch of dummy entries: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 >>> import sys >>> import logging >>> sorted(x for x in sys.modules.keys() if 'log' in x) ['logging', 'logging.atexit', 'logging.cStringIO', '...
[ "None values in sys.modules are cached failures of relative lookups.\nSo when you're in package foo and you import sys, Python looks first for a foo.sys module, and if that fails goes to the top-level sys module. To avoid having to check the filesystem for foo/sys.py again on further relative imports, it stores Non...
[ 23 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001958417_import_python.txt
Q: Python2.4 and 2.6 behaves differently for os.path.getmtime() on Windows Getting two different modification time when calculated from different Python versions on Windows XP. Python2.4 C:\Copy of elisp>c:\python24\python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "co...
Python2.4 and 2.6 behaves differently for os.path.getmtime() on Windows
Getting two different modification time when calculated from different Python versions on Windows XP. Python2.4 C:\Copy of elisp>c:\python24\python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.p...
[ "\nThere is a difference of 3600 seconds ...\n\nThis should be the kicker. It's a timezone problem, pure and simple.\nNow all you have to do is find out why 2.4 and 2.6 are using different timezone information :-)\n", "It's a bug in Microsoft's implementation of the C standard library. Python 2.4 used to use the ...
[ 2, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0001957866_python_windows.txt
Q: Python - Idiom to check if string is empty, print default I'm just wondering, is there a Python idiom to check if a string is empty, and then print a default if it's is? (The context is Django, for the __unicode__(self) function for UserProfile - basically, I want to print the first name and last name, if it exist...
Python - Idiom to check if string is empty, print default
I'm just wondering, is there a Python idiom to check if a string is empty, and then print a default if it's is? (The context is Django, for the __unicode__(self) function for UserProfile - basically, I want to print the first name and last name, if it exists, and then the username if they don't both exist). Cheers, Vic...
[ "displayname = firstname+' '+lastname if firstname and lastname else username\n\n", "displayname = firstname + lastname or username\n\nwill work if firstname and last name has 0 length blank string\n", "I think this issue is better handled in the templates with something like:\n{{ user.get_full_name|default:use...
[ 6, 4, 4, 2, 1, 0 ]
[]
[]
[ "django", "idioms", "python" ]
stackoverflow_0001956249_django_idioms_python.txt
Q: How to remove blocks surrounded by curly brackets via python Sample text: String -> content within the rev tag (via lxml). I'm trying to remove the {{BLOCKS}} within the text. I've used the following regex to remove simple, one line blocks: p = re.compile('\{\{*.*\}\}') nonBracketedString = p.sub('', bracketedStri...
How to remove blocks surrounded by curly brackets via python
Sample text: String -> content within the rev tag (via lxml). I'm trying to remove the {{BLOCKS}} within the text. I've used the following regex to remove simple, one line blocks: p = re.compile('\{\{*.*\}\}') nonBracketedString = p.sub('', bracketedString) However this does not remove the first multi line bracketed s...
[ "Set the dotall flag.\np = re.compile('\\{\\{*.*?\\}\\}', re.DOTALL)\nnonBracketedString = p.sub('', bracketedString)\n\nIn the default mode, . matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.\nhttp://docs.python.org/library/re.html\nAlso...
[ 2, 2, 1 ]
[]
[]
[ "api", "python", "regex", "wikipedia" ]
stackoverflow_0001956970_api_python_regex_wikipedia.txt
Q: Absolute import failing in subpackage that shadows a stdlib package name Basically I have a subpackage with the same name as a standard library package ("logging") and I'd like it to be able to absolute-import the standard one no matter how I run it, but this fails when I'm in the parent package. It really looks l...
Absolute import failing in subpackage that shadows a stdlib package name
Basically I have a subpackage with the same name as a standard library package ("logging") and I'd like it to be able to absolute-import the standard one no matter how I run it, but this fails when I'm in the parent package. It really looks like either a bug, or an undocumented behaviour of the new "absolute import" su...
[ "sys.path[0] is by default '', which means \"current directory\". So if you are sitting in a directory with logging in it, that will be chosen first.\nI ran into this recently, until I realized that I was actually sitting in that directory and that sys.path was picking up my current directory FIRST, before looking...
[ 10 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001959188_import_python.txt
Q: str.format() problem So I made this class that outputs '{0}' when x=0 or '{1}' for every other value of x. class offset(str): def __init__(self,x): self.x=x def__repr__(self): return repr(str({int(bool(self.x))})) def end(self,end_of_loop): #ignore this def it works fine ...
str.format() problem
So I made this class that outputs '{0}' when x=0 or '{1}' for every other value of x. class offset(str): def __init__(self,x): self.x=x def__repr__(self): return repr(str({int(bool(self.x))})) def end(self,end_of_loop): #ignore this def it works fine if self.x==end_of_loop:...
[ "Your subclass of str does not override format, so when you call format on one of its instances it just uses the one inherited from str which uses self's \"intrinsic value as str\", i.e., the string form of whatever you passed to offset().\nTo change that intrinsic value you might override __new__, e.g.:\nclass off...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001959364_python.txt
Q: Get physical map location of object based off user input I am getting user input into a python application of a local landmark. With this data I am trying to get the longitude and latitude of their object using Google maps. I am trying to work with the Google gdata api for the maps but I did not find a way to ge...
Get physical map location of object based off user input
I am getting user input into a python application of a local landmark. With this data I am trying to get the longitude and latitude of their object using Google maps. I am trying to work with the Google gdata api for the maps but I did not find a way to get long and lat data from a search query when working in python...
[ "Are you trying to geocode a street or POI (point of interest)? In that case, geopy is perfect:\nIn [1]: from geopy import geocoders\n\nIn [2]: g = geocoders.Google(GOOGLE_MAPS_API_KEY)\n\nIn [3]: (place, point) = g.geocode('Eiffel Tower, Paris')\nFetching http://maps.google.com/maps/geo?q=Eiffel+Tower%2C+Paris&out...
[ 5, 1, 0 ]
[]
[]
[ "gdata_api", "google_maps", "python" ]
stackoverflow_0001851722_gdata_api_google_maps_python.txt
Q: Python list problem python: m=[[0]*3]*2 for i in range(3): m[0][i]=1 print m I expect that this code should print [[1, 1, 1], [0, 0, 0]] but it prints [[1, 1, 1], [1, 1, 1]] A: This is by design. When you use multiplication on elements of a list, you are reproducing the references. See the section "List...
Python list problem
python: m=[[0]*3]*2 for i in range(3): m[0][i]=1 print m I expect that this code should print [[1, 1, 1], [0, 0, 0]] but it prints [[1, 1, 1], [1, 1, 1]]
[ "This is by design. When you use multiplication on elements of a list, you are reproducing the references.\nSee the section \"List creation shortcuts\" on the Python Programming/Lists wikibook which goes into detail on the issues with list references to mutable objects.\nTheir recommended workaround is a list comp...
[ 18, 8 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001959744_list_python.txt
Q: Django uploading image error I'm trying to upload an image using normal form for normal admin for normal model with normal image field. thumb = fields.ThumbnailField(upload_to=make_upload_path, sizes=settings.VIDEO_THUMB_SIZE, blank=True, null=True) But I'm getting an error: Upload a valid image. The file you upl...
Django uploading image error
I'm trying to upload an image using normal form for normal admin for normal model with normal image field. thumb = fields.ThumbnailField(upload_to=make_upload_path, sizes=settings.VIDEO_THUMB_SIZE, blank=True, null=True) But I'm getting an error: Upload a valid image. The file you uploaded was either not an image or a...
[ "You probably have PIL (Python Imaging Library) installed without JPEG support. If you don't have the libjpeg header files it'll happily compile and install, just with no JPEG support. You need to uninstall PIL, make sure you install libjpeg and the libjpeg development header files, and then reinstall PIL. How you ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001959447_django_python.txt
Q: Dealing with db.Timeout on Google App Engine I'm testing my application (on Google App Engine live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes). I keep getting db.Timeout very often though. How do I deal with this? I was going to surround all my...
Dealing with db.Timeout on Google App Engine
I'm testing my application (on Google App Engine live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes). I keep getting db.Timeout very often though. How do I deal with this? I was going to surround all my queries with really brutal code like this: que...
[ "Here's a decorator to retry on db.Timeout, adapted from one from Kay framework:\nimport logging, time\nfrom google.appengine.ext import db\n\ndef retry_on_timeout(retries=3, interval=1.0, exponent=2.0):\n \"\"\"A decorator to retry a given function performing db operations.\"\"\"\n def _decorator(func):\n ...
[ 7, 6, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001456070_google_app_engine_python.txt
Q: Which ldap object mapper for python can you recommend? I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such fu...
Which ldap object mapper for python can you recommend?
I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality: pumpkin 0.1.0-beta1: Pumpkin is LDAP ORM (with...
[ "If I were you I would either use python-ldap or ldaptor. Python-ldap is a wrapper for OpenLDAP so you may have problems with using it on Windows unless you are able to build from source.\nLDAPtor, is pure python so you avoid that problem. Also, there is a very well written, and graphical description of ldaptor on ...
[ 4, 3, 0 ]
[]
[]
[ "ldap", "orm", "python" ]
stackoverflow_0001544535_ldap_orm_python.txt
Q: Python if else micro-optimization In pondering optimization of code, I was wondering which was more expensive in python: if x: d = 1 else: d = 2 or d = 2 if x: d = 1 Any thoughts? I like the reduced line count in the second but wondered if reassignment was more costly than the condition switching. ...
Python if else micro-optimization
In pondering optimization of code, I was wondering which was more expensive in python: if x: d = 1 else: d = 2 or d = 2 if x: d = 1 Any thoughts? I like the reduced line count in the second but wondered if reassignment was more costly than the condition switching.
[ "Don't ponder, don't wonder, measure -- with timeit at the shell command line (by far the best, simplest way to use it!). Python 2.5.4 on Mac OSX 10.5 on a laptop...:\n$ python -mtimeit -s'x=0' 'if x: d=1' 'else: d=2'\n10000000 loops, best of 3: 0.0748 usec per loop\n$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2...
[ 20, 5, 2, 1 ]
[]
[]
[ "micro_optimization", "python" ]
stackoverflow_0001959944_micro_optimization_python.txt
Q: GAE template code to check is item in the list How to use "in" statement to check is item in the list or not. If I use: {% for picture in pictures %} {% if picture in article.pictures %} <input type="checkbox" checked="true" name="picture" value="{{ picture.key }}" /> {% else %} <input type="che...
GAE template code to check is item in the list
How to use "in" statement to check is item in the list or not. If I use: {% for picture in pictures %} {% if picture in article.pictures %} <input type="checkbox" checked="true" name="picture" value="{{ picture.key }}" /> {% else %} <input type="checkbox" name="picture" value="{{ picture.key }}" /> ...
[ "By default, Django templates do not support full conditional expressions. You can check if one value is \"true\" with if, or you can check whether two values are equal with ifequal, etc.\nPerhaps you can decorate your pictures in the view before you render the template.\nfor picture in pictures:\n picture.is_in...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python", "templates" ]
stackoverflow_0001960022_google_app_engine_python_templates.txt
Q: Start a "throwaway" MySQL session for testing code? If I want to be able to test my application against a empty MySQL database each time my application's testsuite is run, how can I start up a server as a non-root user which refers to a empty (not saved anywhere, or in saved to /tmp) MySQL database? My application...
Start a "throwaway" MySQL session for testing code?
If I want to be able to test my application against a empty MySQL database each time my application's testsuite is run, how can I start up a server as a non-root user which refers to a empty (not saved anywhere, or in saved to /tmp) MySQL database? My application is in Python, and I'm using unittest on Ubuntu 9.10.
[ "--datadir for just the data or --basedir\n", "You can try the Blackhole and Memory table types in MySQL.\n" ]
[ 1, 0 ]
[]
[]
[ "mysql", "python", "ubuntu", "unit_testing" ]
stackoverflow_0001960155_mysql_python_ubuntu_unit_testing.txt
Q: How does this class implement the "__iter__" method without implementing "next"? I have the following code in django.template: class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) e...
How does this class implement the "__iter__" method without implementing "next"?
I have the following code in django.template: class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) except UnicodeDecodeError: raise TemplateEncodingError("Templates can only ...
[ "From the docs: \n\nIf a container object’s __iter__()\n method is implemented as a generator,\n it will automatically return an\n iterator object (technically, a\n generator object) supplying the\n __iter__() and __next__() methods.\n\nHere is your provided example using a generator:\nclass A():\n def __in...
[ 41, 16 ]
[]
[]
[ "iterator", "python", "yield" ]
stackoverflow_0001960309_iterator_python_yield.txt
Q: how can i use '@' by myself function like '@staticmethod' the next is my code,it can print 'xxx', but run wrong at last: def a(object): print 'xxx' @a def b(): return 'bbb' b() In your answers, please try to use code examples rather than text, because my English is not very good. Thank you. A: The deco...
how can i use '@' by myself function like '@staticmethod'
the next is my code,it can print 'xxx', but run wrong at last: def a(object): print 'xxx' @a def b(): return 'bbb' b() In your answers, please try to use code examples rather than text, because my English is not very good. Thank you.
[ "The decorator form @a means:\n@a\ndef b...\n\nis exactly the same as:\ndef b...\n\nb = a(b)\n\nSo, write a as a higher order function, AKA HOF: specifically, a function that takes a function object as an argument, and returns a function object.\nAs you give NO idea in your question about what a is supposed to DO, ...
[ 5, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0001960659_decorator_python.txt
Q: why does my 'join' function run wrong b=','.join([1,2,3,4,5]) print b I want it to print the string: '1,2,3,4,5' In your answers, please try to use code examples rather than text, because my English is not very good. Thank you. A: b = ','.join(map(str, [1,2,3,4,5])) # => '1,2,3,4,5' Python doesn't automaticall...
why does my 'join' function run wrong
b=','.join([1,2,3,4,5]) print b I want it to print the string: '1,2,3,4,5' In your answers, please try to use code examples rather than text, because my English is not very good. Thank you.
[ "b = ','.join(map(str, [1,2,3,4,5]))\n# => '1,2,3,4,5'\n\nPython doesn't automatically turn the ints into strings--you have to convert them to strings first, then join them.\n", "anystring.join takes an iterable of STRINGS, not one of integers, which is what you're passing to it!\nSo, use ','.join(str(x) for x in...
[ 7, 7, 4 ]
[]
[]
[ "python" ]
stackoverflow_0001960698_python.txt
Q: Write to file as Json format? I have A method for format the ouput as json. My keyword_filter will be pass in this this format: <QueryDict: {u'customer_type': [u'ABC'], u'tag': [u'2']}> <QueryDict: {u'customer_type': [u'TDO'], u'tag': [u'3']}> <QueryDict: {u'customer_type': [u'FRI'], u'tag': [u'2,3']}> In fact th...
Write to file as Json format?
I have A method for format the ouput as json. My keyword_filter will be pass in this this format: <QueryDict: {u'customer_type': [u'ABC'], u'tag': [u'2']}> <QueryDict: {u'customer_type': [u'TDO'], u'tag': [u'3']}> <QueryDict: {u'customer_type': [u'FRI'], u'tag': [u'2,3']}> In fact this I got from request.GET (keyword_...
[ "Some tips:\n\nyou can convert django's QueryDict to to Python dictionary with dict(keyword_filter) expression,\nyou can add additional record to the dictionary with dict(keyword_filter, name=filter_name) expression.\n\nThen use json module to dump JSON and write it to the file.\n", "Your question is difficult to...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001960873_django_python.txt
Q: Refreshing a window in Tkinter I am trying to make a GUI in Tkinter and am wondering how to refresh a window, namely if I fill in a rectangle, I want the GUI to delete it a specified time later. How would I go about doing this? Documentation on Tkinter seems to be thin... A: Each Tkinter widget has a after metho...
Refreshing a window in Tkinter
I am trying to make a GUI in Tkinter and am wondering how to refresh a window, namely if I fill in a rectangle, I want the GUI to delete it a specified time later. How would I go about doing this? Documentation on Tkinter seems to be thin...
[ "Each Tkinter widget has a after method, which you can use to call your rectangle delete function e.g. in the example below first I change a msg using after, and then destruct the window using after\nfrom Tkinter import *\n\ndef changeMsg():\n label.configure(text=\"I will self destruct in 2 secs\")\n label.a...
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0001960725_python_tkinter.txt
Q: Python: Regex needed This is probably simple, but I can't figure this out: I need regex expression which would extract following records (Each record may span multiple lines and delimited by one or more blank lines): TextTextTextTextTextTextText TextTextTextTextTextTextTextTextText (one or more blank lines) TextTe...
Python: Regex needed
This is probably simple, but I can't figure this out: I need regex expression which would extract following records (Each record may span multiple lines and delimited by one or more blank lines): TextTextTextTextTextTextText TextTextTextTextTextTextTextTextText (one or more blank lines) TextTextTextTextText TextTextTex...
[ "import re\nre.split('\\n\\n+', text)\n\n" ]
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001961298_python_regex.txt
Q: Where does execution resume following an exception? In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most p...
Where does execution resume following an exception?
In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?
[ "The code inside the catch block is executed and the original execution continues right after the catch block.\n", "the execution resumes where the exception is caught, that is at the beginning of the catch block which specifically address the current exception type. the catch block is executed, the other catch b...
[ 7, 4, 2, 2, 1 ]
[]
[]
[ "c++", "exception", "python" ]
stackoverflow_0001961158_c++_exception_python.txt
Q: what exactly is random.random doing random.shuffle(lst_shuffle, random.random) I know the latter part is an optional argument. But what does it do exactly. I don't understand what this mean. This is from the docs. random.random()¶ Return the next random floating point number in the range [0.0, 1.0). I ...
what exactly is random.random doing
random.shuffle(lst_shuffle, random.random) I know the latter part is an optional argument. But what does it do exactly. I don't understand what this mean. This is from the docs. random.random()¶ Return the next random floating point number in the range [0.0, 1.0). I also see this, is this what this range 0,...
[ "Existing answers do a good job of addressing the question's specific, but I think it's worth mentioning a side issue: why you're particularly likely to want to pass an alternative \"random generator\" to shuffle as opposed to other functions in the random module. Quoting the docs:\n\nNote that for even rather smal...
[ 6, 4, 1, 0, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001961340_python_random.txt
Q: efficient algorithm to perform spell check on HTML document I have a HTML document, a list of common spelling mistakes, and the correct spelling for each case. The HTML documents will be up to ~50 pages and there are ~30K spelling correction entries. What is an efficient way to correct all spelling mistakes in thi...
efficient algorithm to perform spell check on HTML document
I have a HTML document, a list of common spelling mistakes, and the correct spelling for each case. The HTML documents will be up to ~50 pages and there are ~30K spelling correction entries. What is an efficient way to correct all spelling mistakes in this HTML document? (Note: my implementation will be in Python, in c...
[ "You are correct that the first approach will be MUCH faster than the second (additionally, I would recommend looking into Tries instead of a straight hash, the space savings will be quite dramatic for 30k words).\nTo still be able to handle the multi-word cases, you could either keep track of the previous token an...
[ 3, 2 ]
[]
[]
[ "algorithm", "html", "performance", "python", "spell_checking" ]
stackoverflow_0001957131_algorithm_html_performance_python_spell_checking.txt
Q: Floating Point Concepts in Python Why Does -22/10 return -3 in python. Any pointers regarding this will be helpful for me. A: Because it's integer division by default. And integer division is rounded towards minus infinity. Take a look: >>> -22/10 -3 >>> -22/10.0 -2.2000000000000002 Positive: >>> 22/10 2 >>> 22...
Floating Point Concepts in Python
Why Does -22/10 return -3 in python. Any pointers regarding this will be helpful for me.
[ "Because it's integer division by default. And integer division is rounded towards minus infinity. Take a look:\n>>> -22/10\n-3\n>>> -22/10.0\n-2.2000000000000002\n\nPositive:\n>>> 22/10\n2\n>>> 22/10.0\n2.2000000000000002\n\nRegarding the seeming \"inaccuracy\" of floating point, this is a great article to read: W...
[ 10, 5, 5, 2, 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0001961394_floating_point_python.txt
Q: tornado - transferring a file to cdn without blocking I have the nginx upload module handling site uploads, but still need to transfer files (let's say 3-20mb each) to our cdn, and would rather not delegate that to a background job. What is the best way to do this with tornado without blocking other requests? Can ...
tornado - transferring a file to cdn without blocking
I have the nginx upload module handling site uploads, but still need to transfer files (let's say 3-20mb each) to our cdn, and would rather not delegate that to a background job. What is the best way to do this with tornado without blocking other requests? Can i do this in an async callback?
[ "You may find it useful in the overall architecture of your site to add a message queuing service such as RabbitMQ.\nThis would let you complete the upload via the nginx module, then in the tornado handler, post a message containing the uploaded file path and exit. A separate process would be watching for these mes...
[ 5, 0 ]
[]
[]
[ "cdn", "python", "tornado" ]
stackoverflow_0001950055_cdn_python_tornado.txt
Q: Polygon touches in more than one point with Shapely I have a list of Shapely polygons in Python. To find out which polygon touch is easy, using the .touches() method. However, I need something that returns True only when the polygons share more than one point (in other words shares a border). Let me illustrate: In...
Polygon touches in more than one point with Shapely
I have a list of Shapely polygons in Python. To find out which polygon touch is easy, using the .touches() method. However, I need something that returns True only when the polygons share more than one point (in other words shares a border). Let me illustrate: In [1]: from shapely.geometry import Polygon In [2]: polygo...
[ "If you truly want to check if two polygons share more than x number of points you can simply do this:\np0,p1,p2 = polygons\nx = 2\nlen(set(p1.boundary.coords).intersection(p2.boundary.coords))>=x\n\nBut I think what you may want is to determine if two edges are colinear (and overlapping).\nThis implementation of A...
[ 12, 7 ]
[]
[]
[ "polygon", "python", "shapely" ]
stackoverflow_0001960961_polygon_python_shapely.txt
Q: I've never seen 'class __proxy__' before, what does this mean(I only have seen that like def __str__) this code is in the django.utils.functional.py class __proxy__(Promise): thanks A: "Magic names", ones that start and end with double underscores, are reserved for the language in Python (but the compiler does ...
I've never seen 'class __proxy__' before, what does this mean(I only have seen that like def __str__)
this code is in the django.utils.functional.py class __proxy__(Promise): thanks
[ "\"Magic names\", ones that start and end with double underscores, are reserved for the language in Python (but the compiler does not enforce that rule at present); Django is violating that rule, or setting itself up as \"being the language\" -- not a terrible sin, but an unpleasant practice.\n", "It's just a nam...
[ 5, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001962368_django_python.txt
Q: why my code only print 'bbb' once,and it does not run wrong unexpectedly class a: class __b__(object): print 'bbb' b=a() b.__b__() b.__b__() b.__b__() a.__b__() a.__b__() a.__b__() it print 'bbb' only once, thanks A: When python creates a class, it does so by executing the code within the class def...
why my code only print 'bbb' once,and it does not run wrong unexpectedly
class a: class __b__(object): print 'bbb' b=a() b.__b__() b.__b__() b.__b__() a.__b__() a.__b__() a.__b__() it print 'bbb' only once, thanks
[ "When python creates a class, it does so by executing the code within the class definition exactly once, therefore creating the class namespace, etc...\nIf you wanted it to run each time you called it, you need to put your code in the __init__ method (which is the constructor).\nclass a:\n class b:\n def ...
[ 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001962410_python.txt
Q: How can I get more intuitive feels about django relationships(like:Many-to-one,Many-to-many ) i use xampp(it has mysql) I was Confused on this django relationships, who can give me a code example(or text) to let me feel it intuitive .thanks (like:Einstein described the theory of relativity) A: I looked all over ...
How can I get more intuitive feels about django relationships(like:Many-to-one,Many-to-many )
i use xampp(it has mysql) I was Confused on this django relationships, who can give me a code example(or text) to let me feel it intuitive .thanks (like:Einstein described the theory of relativity)
[ "I looked all over for a simple explanation of relationships, but couldn't find anything, so I'll try to summarize it here.\nRelationships aren't strictly a Django thing. If you really want to understand what Django is doing, learn about database concepts in general.\n\nWhen you have multiple tables of information,...
[ 1, 0 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0001962323_django_python_sql.txt
Q: How can i get a list of all special methods available? Special methods are for example (in Django): def __wrapper__ def __deepcopy__ def __mod__ def __cmp__ A: To print Python's reserved words just use >>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',...
How can i get a list of all special methods available?
Special methods are for example (in Django): def __wrapper__ def __deepcopy__ def __mod__ def __cmp__
[ "To print Python's reserved words just use\n>>> import keyword\n>>> print(keyword.kwlist)\n['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue',\n'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',\n'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass...
[ 9, 6, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001962559_django_python.txt
Q: GUI runner in Eclipse for Python/IronPython As much as the console runner is nice, I enjoy the instant red/green view of a graphical runner such as NUnit or MSTest for quickly glancing at broken tests. Does such a tool exist for Eclipse? I've tried Google but only found some awful standalone versions. A: PyDev h...
GUI runner in Eclipse for Python/IronPython
As much as the console runner is nice, I enjoy the instant red/green view of a graphical runner such as NUnit or MSTest for quickly glancing at broken tests. Does such a tool exist for Eclipse? I've tried Google but only found some awful standalone versions.
[ "PyDev has a feature to quickly execute the unit tests from withing the IDE. It also allows selecting the unit test cases to run. But it displays the usual textual output, no graphical representation of the test results.\nThe best solution I've ever seen (and actively used) is Wing IDE's Testing pane, which display...
[ 1 ]
[]
[]
[ "eclipse", "ironpython", "python", "unit_testing" ]
stackoverflow_0001957642_eclipse_ironpython_python_unit_testing.txt
Q: How do I make a simple file browser in wxPython? I'm starting to learn both Python and wxPython and as part of the app I'm doing, I need to have a simple browser on the left pane of my app. I'm wondering how do I do it? Or at least point me to the right direction that'll help me more on how to do one. Thanks in ad...
How do I make a simple file browser in wxPython?
I'm starting to learn both Python and wxPython and as part of the app I'm doing, I need to have a simple browser on the left pane of my app. I'm wondering how do I do it? Or at least point me to the right direction that'll help me more on how to do one. Thanks in advance! EDIT: a sort of side question, how much of wxPy...
[ "I think that the GenericDirCtrl widget could be of use for you. This tutorial has many examples, among them a simple usage of that widget in a complete script (screenshot pasted below). And I strongly recommend not to start with wxGlade, but manually layout your first few wx GUIs (with the appropriate sizers). You...
[ 8, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001962592_python_wxpython.txt
Q: Cannot use Python 2.6 C interface anymore, but 2.5 works I just noticed that I cannot use the Python 2.6 dll anymore. Python 2.5 works just fine. import ctypes py1 = ctypes.cdll.python25 py2 = ctypes.cdll.python26 # ctypes.cdll.LoadLibrary("libpython2.6.so") in linux py1.Py_Initialize() py2.Py_Initialize() # se...
Cannot use Python 2.6 C interface anymore, but 2.5 works
I just noticed that I cannot use the Python 2.6 dll anymore. Python 2.5 works just fine. import ctypes py1 = ctypes.cdll.python25 py2 = ctypes.cdll.python26 # ctypes.cdll.LoadLibrary("libpython2.6.so") in linux py1.Py_Initialize() py2.Py_Initialize() # segmentation fault in Linux py1.PyRun_SimpleString("print 'hell...
[ "What you are doing is wrong. You are clearly running Python 2.6 and then trying to initialize the shared library in the same process (and thread), which is going to crash (if you're lucky...if you're not it's going to cause you very ugly trouble later). You should never, ever, try to load Python into itself and ...
[ 2, 1 ]
[]
[]
[ "ctypes", "python", "python_2.5", "python_2.6" ]
stackoverflow_0001962545_ctypes_python_python_2.5_python_2.6.txt
Q: How to use on_mouse_motion to move around a lable via pyglet? How can one move a label around in the hello world example using the on_mouse_motion function? The docs aren't clicking for me. on_mouse-motion hello_world_example.py A: Figured it out: Don't know if this is the most efficient solution though. EDIT -...
How to use on_mouse_motion to move around a lable via pyglet?
How can one move a label around in the hello world example using the on_mouse_motion function? The docs aren't clicking for me. on_mouse-motion hello_world_example.py
[ "Figured it out: Don't know if this is the most efficient solution though.\nEDIT -> fixed for just xy.\n#!/usr/bin/env python\n\nimport pyglet\n\nwindow = pyglet.window.Window()\nfps_display = pyglet.clock.ClockDisplay()\nlabel = pyglet.text.Label('Hello World!',font_name='Arial',font_size=36, x=0, y=0)\n\n@window....
[ 2 ]
[]
[]
[ "pyglet", "python" ]
stackoverflow_0001963003_pyglet_python.txt
Q: What is the significance of a function without a 'self' argument insde a class? class a: def b(): ... what is the Significance of b thanks class a: @staticmethod def b(): return 1 def c(self): b() print a.b() print a().b() print a().c()#error and class a: @stati...
What is the significance of a function without a 'self' argument insde a class?
class a: def b(): ... what is the Significance of b thanks class a: @staticmethod def b(): return 1 def c(self): b() print a.b() print a().b() print a().c()#error and class a: @staticmethod def b(): return 1 def c(self): return self.b() p...
[ "Basically you should use b() as staticmethod so that you can call it either from Class or Object of class e.g:\nbash-3.2$ python\nPython 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more infor...
[ 7, 4, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001962983_class_python.txt
Q: I want to print 'eee fff {'e':'eee','f':'fff'}',how can i get it. (it is about __setattr__) the next is my code: class a: w={} def __setattr__(self,name,value): self.w[name]=value def __getattr__(self,name): return self.w[name] b=a() b.e='eee' b['f']='fff' print b.e,b['f'],b.w #error ...
I want to print 'eee fff {'e':'eee','f':'fff'}',how can i get it. (it is about __setattr__)
the next is my code: class a: w={} def __setattr__(self,name,value): self.w[name]=value def __getattr__(self,name): return self.w[name] b=a() b.e='eee' b['f']='fff' print b.e,b['f'],b.w #error what is the difference between b.e and b['f']. thanks
[ "__ set/getitem__() are used for indexing. Define them as well.\n", "class MyClass(object):\n def __init__(self):\n self.w = {}\n\n def __setitem__(self, k, v):\n self.w[k] = v\n\n def __getitem__(self, k):\n return self.w[k]\n\n\nmc = MyClass()\nmc['aa'] = 12\nprint mc['aa']\n\nseti...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001962919_python.txt
Q: Formatted Input in Python I have a peculiar problem. I need to read (from a txt file) using python only those substrings that are present at predefined range of offsets. Let's say 5-8 and 12-16. For example, if a line in the file is something like: abcdefghi akdhflskdhfhglskdjfhghsldk then I would like to read th...
Formatted Input in Python
I have a peculiar problem. I need to read (from a txt file) using python only those substrings that are present at predefined range of offsets. Let's say 5-8 and 12-16. For example, if a line in the file is something like: abcdefghi akdhflskdhfhglskdjfhghsldk then I would like to read the two words - "efgh" and "kdhfl...
[ "assuming its a file,\nfor line in open(\"file\"):\n print line[4:8] , line[11:16]\n\n", "To extract pieces from offsets simply read each line into a string and then access a substring with a slice ([from:to]). \nIt's unclear what you're saying about the inconsistent whitespace. If whitespace adds to the offse...
[ 5, 1 ]
[ "What's to stop you from using a regular expression? Besides the whitespace do the offsets vary?\n/.{4}(.{4}).{4}(.{4})/\n\n" ]
[ -1 ]
[ "file_io", "python", "textinput" ]
stackoverflow_0001963546_file_io_python_textinput.txt
Q: Render and scroll through multiline paragraphs using pyglet and ScrollableTextLayout How can one display and scroll through a multi-line strings (contain "\n") via pyglet using the features of ScrollableTextLayout? STL crops what is display, and seems to be the most efficient way to implement scrolling. However I ...
Render and scroll through multiline paragraphs using pyglet and ScrollableTextLayout
How can one display and scroll through a multi-line strings (contain "\n") via pyglet using the features of ScrollableTextLayout? STL crops what is display, and seems to be the most efficient way to implement scrolling. However I have no idea as to how to use it. The docs do not elucidate much to me. SomeText: string =...
[ "You create one like this:\nscroll_area = pyglet.text.layout.ScrollableTextLayout(my_text, width, height, multiline=True) \n\nAnd you choose your scroll position with the view_x and view_y values.\nscroll_area.view_y = 30 # start 30 pixels down\n\nSet different values of view_y to scroll vertically.\n" ]
[ 0 ]
[]
[]
[ "multiline", "pyglet", "python", "scroll" ]
stackoverflow_0001963171_multiline_pyglet_python_scroll.txt
Q: Regular Expression search/replace help needed, Python One rule that I need is that if the last vowel (aeiou) of a string is before a character from the set ('t','k','s','tk'), then a : needs to be added right after the vowel. So, in Python if I have the string "orchestras" I need a rule that will turn it into "orc...
Regular Expression search/replace help needed, Python
One rule that I need is that if the last vowel (aeiou) of a string is before a character from the set ('t','k','s','tk'), then a : needs to be added right after the vowel. So, in Python if I have the string "orchestras" I need a rule that will turn it into "orchestra:s" edit: The (t, k, s, tk) would be the final charac...
[ "re.sub(r\"([aeiou])(t|k|s|tk)([^aeiou]*)$\", r\"\\1:\\2\\3\", \"orchestras\")\nre.sub(r\"([aeiou])(t|k|s|tk)$\", r\"\\1:\\2\", \"orchestras\")\n\nYou don't say if there can be other consonants after the t/k/s/tk. The first regex allows for this as long as there aren't any more vowels, so it'll change ...
[ 6, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001862782_python_regex.txt
Q: What problems will one see in using Python multiprocessing naively? We're considering re-factoring a large application with a complex GUI which is isolated in a decoupled fashion from the back-end, to use the new (Python 2.6) multiprocessing module. The GUI/backend interface uses Queues with Message objects excha...
What problems will one see in using Python multiprocessing naively?
We're considering re-factoring a large application with a complex GUI which is isolated in a decoupled fashion from the back-end, to use the new (Python 2.6) multiprocessing module. The GUI/backend interface uses Queues with Message objects exchanged in both directions. One thing I've just concluded (tentatively, but ...
[ "I have not used multiprocessing itself, but the problems presented are similar to experience I've had in two other domains: distributed systems, and object databases. Python object identity can be a blessing and a curse!\nAs for general gotchas, it helps if the application you are refactoring can acknowledge that...
[ 2, 1, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001925718_multiprocessing_python.txt
Q: What exception to raise if wrong number of arguments passed in to **kwargs? Suppose in python you have a routine that accepts three named parameters (as **kwargs), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would yo...
What exception to raise if wrong number of arguments passed in to **kwargs?
Suppose in python you have a routine that accepts three named parameters (as **kwargs), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise? RuntimeError, a specifically created exception, or other?
[ "Remember that you can subclass Python's built-in exception classes (and TypeError would surely be the right built-in exception class to raise here -- that's what Python raises if the number of arguments does not match the signature, in normal cases without *a or **k forms in the signature). I like having every pa...
[ 17, 15, 4, 3, 0, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001964126_exception_python.txt
Q: short Unicode \N{} names for Latin-1 characters in Python? Are there short Unicode u"\N{...}" names for Latin1 characters in Python ? \N{A umlaut} etc. would be nice, \N{LATIN SMALL LETTER A WITH DIAERESIS} etc. is just too long to type every time. (Added:) I use an English keyboard, but occasionally need German l...
short Unicode \N{} names for Latin-1 characters in Python?
Are there short Unicode u"\N{...}" names for Latin1 characters in Python ? \N{A umlaut} etc. would be nice, \N{LATIN SMALL LETTER A WITH DIAERESIS} etc. is just too long to type every time. (Added:) I use an English keyboard, but occasionally need German letters, as in "Löwenbräu Weißbier". Yes one can cut-paste them s...
[ "Sorry, no, there's no such thing. In string literals, anyway... you could perhaps piggyback on another encoding scheme, such as HTML:\n>>> import HTMLParser\n>>> HTMLParser.HTMLParser().unescape(u'a &auml; b c')\nu'a \\xe4 b'\n\nBut I don't think this'd be worth it.\nHardly anyone even uses the \\N notation in any...
[ 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0001963353_encoding_python_unicode_utf_8.txt
Q: Time complexity of accessing a Python dict I am writing a simple Python program. My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic. I use a dictionary to memoize values. That seems to be a bottleneck. The values I'm hashing a...
Time complexity of accessing a Python dict
I am writing a simple Python program. My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic. I use a dictionary to memoize values. That seems to be a bottleneck. The values I'm hashing are tuples of points. Each point is: (x,y), 0 <= ...
[ "See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely ...
[ 100, 10, 9, 6, 2, 2 ]
[]
[]
[ "complexity_theory", "dictionary", "hash", "python" ]
stackoverflow_0001963507_complexity_theory_dictionary_hash_python.txt
Q: How to append '\\?\' to the front of a file path in Python I'm trying to work with some long file paths (Windows) in Python and have come across some problems. After reading the question here, it looks as though I need to append '\\?\' to the front of my long file paths in order to use them with os.stat(filepath)...
How to append '\\?\' to the front of a file path in Python
I'm trying to work with some long file paths (Windows) in Python and have come across some problems. After reading the question here, it looks as though I need to append '\\?\' to the front of my long file paths in order to use them with os.stat(filepath). The problem I'm having is that I can't create a string in Pyt...
[ "\"\\\\\\\\?\\\\\" should give you exactly the string you want.\nLonger answer: of course you can end a string in Python with a backslash. You just can't do so when it's a \"raw\" string (one prefixed with an 'r'). Which you usually use for strings that contains (lots of) backslashes (to avoid the infamous \"lean...
[ 3, 0 ]
[]
[]
[ "backslash", "filepath", "python" ]
stackoverflow_0001963302_backslash_filepath_python.txt
Q: edit in place using xpath Is it possible to do in place edit of XML document using xpath ? I'd prefer any python solution but Java would be fine too. A: XPath is not intended to edit document in place, as far as I know. It is intended to only select nodes of the document. XSLT relies on XPath and can transform d...
edit in place using xpath
Is it possible to do in place edit of XML document using xpath ? I'd prefer any python solution but Java would be fine too.
[ "XPath is not intended to edit document in place, as far as I know. It is intended to only select nodes of the document. XSLT relies on XPath and can transform documents.\nRegarding Python, see answer to this question: how to use xpath in python. It mentions also libraries which can do XSLT transformations.\n", "...
[ 3, 1 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0001964583_python_xpath.txt
Q: what is the next code mean, the 'lambda request' and the '**kwargs: {}',i have never see this def validate(request, *args, **kwargs): form_class = kwargs.pop('form_class') extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {}) thanks a={'a':'aaa','b':'bbb'} b=a.pop('a',lambda x,y:x...
what is the next code mean, the 'lambda request' and the '**kwargs: {}',i have never see this
def validate(request, *args, **kwargs): form_class = kwargs.pop('form_class') extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {}) thanks a={'a':'aaa','b':'bbb'} b=a.pop('a',lambda x,y:x) print a i know dict.pop('a'),but i don't know dict.pop('a',func) what is the use of 'func‘ in he...
[ "The expression:\nlambda request, *args, **kwargs: {}\n\nbuilds an anonymous function which must be called with at least one argument (which, if named, must be named request) and can be called with any number of positional and named arguments: when called, it ignores all the arguments and returns a new empty dictio...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001964750_python.txt
Q: Creating a PyBuffer from a C struct EDIT: Upon re-reading my original question I realized very quickly that it was very poorly worded, ambiguous, and too confusing to ever get a decent answer. That's what I get for rushing out a question at the end of my lunch break. Hopefully this will be clearer: I am trying to ...
Creating a PyBuffer from a C struct
EDIT: Upon re-reading my original question I realized very quickly that it was very poorly worded, ambiguous, and too confusing to ever get a decent answer. That's what I get for rushing out a question at the end of my lunch break. Hopefully this will be clearer: I am trying to expose a simple C structure to Python (3....
[ "The set of methods to implement so that your extension type supports the buffer protocol is described here: http://docs.python.org/3.1/c-api/typeobj.html#buffer-object-structures\nI recognize that the documentation is pretty rough, so the best advice I can give is to start from an existing implementation of the bu...
[ 1 ]
[]
[]
[ "pybuffer", "python", "python_3.x" ]
stackoverflow_0001710820_pybuffer_python_python_3.x.txt
Q: Python C-API Object Initialisation What is the correct way to initialise a python object into already existing memory (like the inplace new in c++) I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set.. //PyVarObject *mem; -previously allocated me...
Python C-API Object Initialisation
What is the correct way to initialise a python object into already existing memory (like the inplace new in c++) I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set.. //PyVarObject *mem; -previously allocated memory Py_INCREF(type); //couldnt get PyO...
[ "What are doing is pretty horrible. Unless this code path is really performance critical I'd advise you to allocate your objects on the heap as is normally done.\n", "Taking your question at face value, you have a few options. The quick and dirty method is to put an extra Py_INCREF into your initialisation code....
[ 1, 0, 0 ]
[]
[]
[ "c", "python", "python_3.x", "python_c_api" ]
stackoverflow_0000581281_c_python_python_3.x_python_c_api.txt
Q: Unicode handling in ReportLab I am trying to use ReportLab with Unicode characters, but it is not working. I tried tracing through the code until I reached the following line: class TTFont: # ... def splitString(self, text, doc, encoding='utf-8'): # ... cur.append(n & 0xFF) # <-- here is th...
Unicode handling in ReportLab
I am trying to use ReportLab with Unicode characters, but it is not working. I tried tracing through the code until I reached the following line: class TTFont: # ... def splitString(self, text, doc, encoding='utf-8'): # ... cur.append(n & 0xFF) # <-- here is the problem! # ... (This cod...
[ "What do you mean, \"not working\"? You have misquoted the reportlab source code. What it is actually doing is that the lower and upper byte of each 16-bit unicode character are coded separately (the upper byte is only written out when it changes, which I assume is a PDF-specific optimization to make documents smal...
[ 1, 0 ]
[]
[]
[ "python", "reportlab", "unicode" ]
stackoverflow_0001594470_python_reportlab_unicode.txt
Q: Random selection ideas I am thinking of giving one or more set of introductory lectures to introduce people in my department with Python and related scientific tools as I did once in the last summer py4science @ UND. To make the meetings more interesting and catch more attention I had given two Python learning ma...
Random selection ideas
I am thinking of giving one or more set of introductory lectures to introduce people in my department with Python and related scientific tools as I did once in the last summer py4science @ UND. To make the meetings more interesting and catch more attention I had given two Python learning materials to one of the lucky ...
[ "Cards are also a source of popular (and familiar!) games of chance.\nPerhaps you could show how easy it is to generate, shuffle and sample cards:\n#!/usr/bin/env python\nimport random\nimport itertools\n\nnumname={1:'Ace',11:'Jack',12:'Queen',13:'King'}\nsuits=['Clubs','Diamonds','Hearts','Spades']\nnumbers=range(...
[ 3, 1, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001964366_python_random.txt
Q: Error when compiling simple python program This script won't compile. I wanted to made a simple 21-style game for practice but I get an error: X@X:~/Desktop$ python 21.py File "21.py", line 18 int(ptotal) = ptotal + newcard SyntaxError: can't assign to function call Here's the code. Can anyone please help me?...
Error when compiling simple python program
This script won't compile. I wanted to made a simple 21-style game for practice but I get an error: X@X:~/Desktop$ python 21.py File "21.py", line 18 int(ptotal) = ptotal + newcard SyntaxError: can't assign to function call Here's the code. Can anyone please help me? I'm obviously a beginner and the code is pretty...
[ "Not sure where you got this syntax:\nint(cone) == random.randrange(1, 11)\n\nI think you mean this:\ncone = random.randrange(1, 11)\n\nThis is also an (interesting) invention:\nwhile hit is not \"No\" or \"no\" or \"n\":\n\nYou'll need:\nwhile hit not in [\"No\", \"no\", \"n\"]:\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001965031_python.txt
Q: Python epoll.register threadsafe? Does anyone know if I can call epoll.register from another thread safely? Here is what I am imagining: Thread 1: epoll.poll() Thread 2: adding some fd to the same epoll object with epoll.register http://docs.python.org/library/select.html A: I changed my answer after you chang...
Python epoll.register threadsafe?
Does anyone know if I can call epoll.register from another thread safely? Here is what I am imagining: Thread 1: epoll.poll() Thread 2: adding some fd to the same epoll object with epoll.register http://docs.python.org/library/select.html
[ "I changed my answer after you changed the question.\nThis will not be \"thread safe\" in that each thread will impact the same epoll object. Registering a new fd to the epoll object will still do it to that object. \nThere's no reason for that particular object to have different states across separate threads, bec...
[ 1 ]
[]
[]
[ "epoll", "multithreading", "python" ]
stackoverflow_0001965092_epoll_multithreading_python.txt
Q: why my code run wrong ,it is about '@property' I used python 2.5, I want to know how can change the next code when the Platform is python2.5 or python2.6 class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @...
why my code run wrong ,it is about '@property'
I used python 2.5, I want to know how can change the next code when the Platform is python2.5 or python2.6 class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = v...
[ "Python 2.5 does not support the .setter and .deleter sub-decorators of property; they were introduced in Python 2.6.\nTo work on both releases, you can, instead, code something like:\nclass C(object):\n def __init__(self):\n self._x = None\n\n def _get_x(self):\n \"\"\"I'm the 'x' property.\"\"...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001965117_python.txt
Q: Python TypeError when using json.dumps When I do json.dumps with a dictionary that maps strings to a list of unicodes, python raises a type error. Why does that not work? A: Works fine for me in Python 2.6 (and identically in 3.1, without the u prefix on the value): >>> import json >>> d={'a': u'fél'} >>> json.d...
Python TypeError when using json.dumps
When I do json.dumps with a dictionary that maps strings to a list of unicodes, python raises a type error. Why does that not work?
[ "Works fine for me in Python 2.6 (and identically in 3.1, without the u prefix on the value):\n>>> import json\n>>> d={'a': u'fél'}\n>>> json.dumps(d)\n'{\"a\": \"f\\\\u00e9l\"}'\n\nCan you please reproduce and post (by editing your answer, so you can format it properly) the tiniest bit of code that gives you the p...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0001965021_json_python.txt
Q: encode Netbios name python I would like to encode "ITSATEST" to it's netbios name value in python; The occurence table and explication are here: http://support.microsoft.com/kb/194203 I dont know how this could be done easily in python, someone can give me a hand ? Thanks ! A: You can map each nibble of the orig...
encode Netbios name python
I would like to encode "ITSATEST" to it's netbios name value in python; The occurence table and explication are here: http://support.microsoft.com/kb/194203 I dont know how this could be done easily in python, someone can give me a hand ? Thanks !
[ "You can map each nibble of the original string, taking its numerical value and offsetting from 'A':\nencoded_name = ''.join([chr((ord(c)>>4) + ord('A'))\n + chr((ord(c)&0xF) + ord('A')) for c in original_name])\n\n", "Take a look at RFC 1001, which defines the encoding. In section 14.1 \"...
[ 2, 1 ]
[]
[]
[ "netbios", "python" ]
stackoverflow_0001965065_netbios_python.txt
Q: Why is getattr() not working like I think it should? I think this code should print 'sss' the next is my code: class foo: def __init__(self): self.a = "a" def __getattr__(self,x,defalut): if x in self: return x else:return defalut a=foo() print getattr(a,'b','sss') i k...
Why is getattr() not working like I think it should? I think this code should print 'sss'
the next is my code: class foo: def __init__(self): self.a = "a" def __getattr__(self,x,defalut): if x in self: return x else:return defalut a=foo() print getattr(a,'b','sss') i know the __getattr__ must be 2 argument,but i want to get a default attribute if the attribute ...
[ "Your problem number one: you're defining an old-style class (we know you're on Python 2.something, even though you don't tell us, because you're using print as a keyword;-). In Python 2:\nclass foo:\n\nmeans you're defining an old-style, aka legacy, class, whose behavior can be rather quirky at times. Never do t...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001964980_python.txt
Q: Calculate time between time-1 to time-2? enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 How can it be done in Python. I'm a beginner so I really have no clue where to start. Edited to add: I don't want a timer. Both time-1 and...
Calculate time between time-1 to time-2?
enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 How can it be done in Python. I'm a beginner so I really have no clue where to start. Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually. Than...
[ "The datetime and timedelta class from the built-in datetime module is what you need.\nfrom datetime import datetime\n\n# Parse the time strings\nt1 = datetime.strptime('01:12','%H:%M')\nt2 = datetime.strptime('18:59','%H:%M')\n\n# Do the math, the result is a timedelta object\ndelta = (t2 - t1) / 12\nprint(delta.s...
[ 17, 6, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001965201_python.txt
Q: File downloading using python with threads I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file. How do I manage it so that the order i...
File downloading using python with threads
I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file. How do I manage it so that the order in which the threads where generated will append ...
[ "You could coordinate the works with locks &c, but I recommend instead using Queue -- usually the best way to coordinate multi-threading (and multi-processing) in Python.\nI would have the main thread spawn as many worker threads as you think appropriate (you may want to calibrate between performance, and load on t...
[ 9, 1, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001965213_multithreading_python.txt
Q: Split a large string into multiple substrings containing 'n' number of words via python Source text: United States Declaration of Independence How can one split the above source text into a number of sub-strings, containing an 'n' number of words? I use split(' ') to extract each word, however I do not know how to...
Split a large string into multiple substrings containing 'n' number of words via python
Source text: United States Declaration of Independence How can one split the above source text into a number of sub-strings, containing an 'n' number of words? I use split(' ') to extract each word, however I do not know how to do this with multiple words in one operation. I could run through the list of words that I ...
[ "text = \"\"\"\nWhen in the course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature?s God entitle them, a decent Respect t...
[ 7, 3, 3 ]
[]
[]
[ "python", "split", "string", "substring", "words" ]
stackoverflow_0001964999_python_split_string_substring_words.txt
Q: Pygtk graphics contexts and allocating colors I've searched on this, but nothing has what I'm looking for. http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html -- Nobody answered him. This is exactly what I'm experiencing. When I set the foreground on a graphics context, it doesn't seem to actually change. ...
Pygtk graphics contexts and allocating colors
I've searched on this, but nothing has what I'm looking for. http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html -- Nobody answered him. This is exactly what I'm experiencing. When I set the foreground on a graphics context, it doesn't seem to actually change. I've been through the tutorial and FAQ, but neither...
[ "I've had some trouble with Drawable and GC in the past. This answer got me started on the way to a solution. Here's a quick example that uses a custom colour gc to draw some squares:\nimport gtk\n\nsquare_sz = 20\npixmap = None\ncolour = \"#FF0000\"\ngc = None\n\ndef configure_event( widget, event):\n global pi...
[ 2, 1 ]
[]
[]
[ "drawing2d", "pygtk", "python" ]
stackoverflow_0000938921_drawing2d_pygtk_python.txt
Q: how to make a python array of particular objects in java, the following code defines an array of the predefined class (myCls): myCls arr[] = new myCls how can I do that in python? I want to have an array of type (myCls)? thanks in advance A: Python is dynamically typed. You do not need to (and in fact CAN'T) c...
how to make a python array of particular objects
in java, the following code defines an array of the predefined class (myCls): myCls arr[] = new myCls how can I do that in python? I want to have an array of type (myCls)? thanks in advance
[ "Python is dynamically typed. You do not need to (and in fact CAN'T) create a list that only contains a single type:\narr = list()\narr = []\n\nIf you require it to only contain a single type then you'll have to create your own list-alike, reimplementing the list methods and __setitem__() yourself.\n", "You can o...
[ 7, 5 ]
[]
[]
[ "arrays", "python", "types" ]
stackoverflow_0001965725_arrays_python_types.txt
Q: 2to3 not working I'm converting a single module using 2to3. test_lib2to3.py is in /Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/test/test_lib2to3.py File to be converted is in /Users/Nimbuz/Documents/python31/Excercise 1/time3.py Terminal Session: localhost:test Nimbuz$ 2to3 /Users/Nimbuz/Documen...
2to3 not working
I'm converting a single module using 2to3. test_lib2to3.py is in /Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/test/test_lib2to3.py File to be converted is in /Users/Nimbuz/Documents/python31/Excercise 1/time3.py Terminal Session: localhost:test Nimbuz$ 2to3 /Users/Nimbuz/Documents/python31/Excercise\...
[ "Maybe there's something wrong with path.\nTry\n2to3 \"/Users/Nimbuz/Documents/python31/Excercise 1/time3.py\"\n\nInstead of\n2to3 /Users/Nimbuz/Documents/python31/Excercise\\ 1/time3.py\n\nor just cd to that folder and \n2to3 time3.py\n\nReady diff: http://pastebay.com/78746\n" ]
[ 0 ]
[]
[]
[ "path", "python", "python_2to3" ]
stackoverflow_0001965387_path_python_python_2to3.txt