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: Django: Easily add extra manager for child class, still use default manager from AbstractBase This question is about the last example on Custom managers and model inheritance. I want to be able to do something similar to the following: class ExtraManagerModel(models.Model): # OtherManager class supplied by argumen...
Django: Easily add extra manager for child class, still use default manager from AbstractBase
This question is about the last example on Custom managers and model inheritance. I want to be able to do something similar to the following: class ExtraManagerModel(models.Model): # OtherManager class supplied by argument shall be set as manager here class Meta: abstract = True class ChildC(AbstractBase,...
[ "I am absolutely not sure that I understand your question. Your code snippet seems to be contradicting the comment underneath it.\nYour code snippet looks like you want to be able to have different ExtraManagerModel classes. If that is the case, you can use an abstract class that is implemented by those ExtraManage...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001188899_django_django_models_python.txt
Q: What are the Python thread + Unix signals semantics? What are the rules surrounding Python threads and how Unix signals are handled? Is KeyboardInterrupt, which is triggered by SIGINT but handled internally by the Python runtime, handled differently? A: First, when setting up signal handlers using the signal mod...
What are the Python thread + Unix signals semantics?
What are the rules surrounding Python threads and how Unix signals are handled? Is KeyboardInterrupt, which is triggered by SIGINT but handled internally by the Python runtime, handled differently?
[ "First, when setting up signal handlers using the signal module, you must create them in the main thread. You will receive an exception if you try to create them in a separate thread.\nSignal handlers registered via the signal.signal() function will always be called in the main thread. On architectures which supp...
[ 9, 4 ]
[]
[]
[ "multithreading", "posix", "python", "signals", "unix" ]
stackoverflow_0001189072_multithreading_posix_python_signals_unix.txt
Q: Reason for unintuitive UnboundLocalError behaviour Note: There is a very similar question here. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case." I just stumbled over this: a = 5 def x() print a a = 6 x() throws an Un...
Reason for unintuitive UnboundLocalError behaviour
Note: There is a very similar question here. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case." I just stumbled over this: a = 5 def x() print a a = 6 x() throws an UnboundLocalException. Now, I do know why that happens (la...
[ "Having the same, identical name refer to completely different variables within the same flow of linear code is such a mind-boggling complexity that it staggers the mind. Consider:\ndef aaaargh(alist):\n for x in alist:\n print a\n a = 23\n\nwhat is THIS code supposed to do in your desired variant on Python?...
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001188944_python.txt
Q: Good or bad practice in Python: import in the middle of a file Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should imports only be in the first part of the module. Example: import string...
Good or bad practice in Python: import in the middle of a file
Suppose I have a relatively long module, but need an external module or method only once. Is it considered OK to import that method or module in the middle of the module? Or should imports only be in the first part of the module. Example: import string, pythis, pythat ... ... ... ... def func(): blah blah ...
[ "PEP 8 authoritatively states:\n\nImports are always put at the top of\n the file, just after any module\n comments and docstrings, and before module globals and constants.\n\nPEP 8 should be the basis of any \"in-house\" style guide, since it summarizes what the core Python team has found to be the most ef...
[ 65, 31, 20, 12, 8, 7, 6, 3, 2 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001188640_python_python_import.txt
Q: wxPython RichTextCtrl much slower than tkInter Text? I've made a small tool that parses a chunk of text, does some simple processing (retrieves values from a dictionary, a few regex, etc.) and then spits the results. In order to make easier to read the results, I made two graphic ports, one with tkInter and other ...
wxPython RichTextCtrl much slower than tkInter Text?
I've made a small tool that parses a chunk of text, does some simple processing (retrieves values from a dictionary, a few regex, etc.) and then spits the results. In order to make easier to read the results, I made two graphic ports, one with tkInter and other with wxPython, so the output is nicely displayed in a Text...
[ "I'm copying here the comment that solved the problem:\n\nHave you tried using Freeze() and\n Thaw() to only update the display\n after you are done appending the\n coloured text? – mghie Jun 30 at 7:20\n\n", "It kind of avoids the question slightly, but could you use wxStyledTextCtrl instead?\n" ]
[ 1, 0 ]
[]
[]
[ "performance", "python", "richtextediting", "tkinter", "wxpython" ]
stackoverflow_0001059214_performance_python_richtextediting_tkinter_wxpython.txt
Q: Why python compile the source to bytecode before interpreting? Why python compile the source to bytecode before interpreting? Why not interpret from the source directly? A: Nearly no interpreter really interprets code directly, line by line – it's simply too inefficient. Almost all interpreters use some intermed...
Why python compile the source to bytecode before interpreting?
Why python compile the source to bytecode before interpreting? Why not interpret from the source directly?
[ "Nearly no interpreter really interprets code directly, line by line – it's simply too inefficient. Almost all interpreters use some intermediate representation which can be executed easily. Also, small optimizations can be performed on this intermediate code.\nPython furthermore stores this code which has a huge a...
[ 39, 8, 7, 6, 3, 0 ]
[]
[]
[ "bytecode", "compiler_construction", "interpreter", "python" ]
stackoverflow_0000888100_bytecode_compiler_construction_interpreter_python.txt
Q: Bizzare eclipse-pydev console behavior Stumbled upon some seemingly random character mangling in eclipse-pydev console: specific characters are read from stdout as '\xd0?' (first byte correct, second "?") Is there some solution to this? (PyDEV 1.4.6, Python 2.6, console encoding - inherited UTF-8, Eclipse 3.5, Win...
Bizzare eclipse-pydev console behavior
Stumbled upon some seemingly random character mangling in eclipse-pydev console: specific characters are read from stdout as '\xd0?' (first byte correct, second "?") Is there some solution to this? (PyDEV 1.4.6, Python 2.6, console encoding - inherited UTF-8, Eclipse 3.5, WinXP with UK locale) Code: import sys if __nam...
[ "Well, I don't know how to fix it, but I have deduced the pattern in what goes wrong.\nThe bytes that get replaced with \"?\" are precisely those bytes that are not defined in windows-1252 - that is, bytes 0x81, 0x8d, 0x8f, 0x90, and 0x9d.\nWhat this looks like to me is that somehow you're getting this series of tr...
[ 2, 0 ]
[]
[]
[ "pydev", "python", "utf_8" ]
stackoverflow_0001188103_pydev_python_utf_8.txt
Q: Does YouTube's API allow uploading and setting of thumbnails? I haven't found anything in their documentation or on the web that says yes or no. Using the Python library. A: Apparently thumbnails can't be updated, per the docs -- media:thumbnail is not listed among the tags you can set on update. On uploading t...
Does YouTube's API allow uploading and setting of thumbnails?
I haven't found anything in their documentation or on the web that says yes or no. Using the Python library.
[ "Apparently thumbnails can't be updated, per the docs -- media:thumbnail is not listed among the tags you can set on update. On uploading the video, yes, you can have media:thumbnail tags as part of your media:group tag which gives the video's metadata.\n" ]
[ 2 ]
[]
[]
[ "api", "python", "youtube" ]
stackoverflow_0001189365_api_python_youtube.txt
Q: How can I launch a background process in Pylons? I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so n...
How can I launch a background process in Pylons?
I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so nothing needs to be stored long-term. I have two questi...
[ "I've handled this problem in the past (long-running process invoked over HTTP) by having my invoked 2nd process daemonize. Your Pylons controller makes a system call to your 2nd process (passing whatever data is needed) and the 2nd process immediately becomes a daemon. This ends the system call and your controll...
[ 6, 1 ]
[]
[]
[ "background", "pylons", "python" ]
stackoverflow_0001182587_background_pylons_python.txt
Q: Event Handling in Chaco When hovering over a data point in Chaco, I would like a small text box to appear, with the text I desire. Also, when I click on a data point (or close enough), I would like my program to take a certain action. I have seen relevant parts of the Chaco documentation, but implementing them ha...
Event Handling in Chaco
When hovering over a data point in Chaco, I would like a small text box to appear, with the text I desire. Also, when I click on a data point (or close enough), I would like my program to take a certain action. I have seen relevant parts of the Chaco documentation, but implementing them has proved to be difficult. Any...
[ "Focusing first on the first (hover->textbox) issue, can you better explain what you've tried so far and how it's not working? E.g.,\nfrom enthought.enable.tools import hover_tool\n\ntool = hover_tool.HoverTool(theplot, callback=showtext)\n\netc? There's a more complex example of hover-tool use here (shows a Plot...
[ 0 ]
[]
[]
[ "chaco", "python" ]
stackoverflow_0001189864_chaco_python.txt
Q: Empty XML element handling in Python I'm puzzled by minidom parser handling of empty element, as shown in following code section. import xml.dom.minidom doc = xml.dom.minidom.parseString('<value></value>') print doc.firstChild.nodeValue.__repr__() # Out: None print doc.firstChild.toxml() # Out: <value/> doc = xm...
Empty XML element handling in Python
I'm puzzled by minidom parser handling of empty element, as shown in following code section. import xml.dom.minidom doc = xml.dom.minidom.parseString('<value></value>') print doc.firstChild.nodeValue.__repr__() # Out: None print doc.firstChild.toxml() # Out: <value/> doc = xml.dom.minidom.Document() v = doc.appendChi...
[ "Cracking open xml.dom.minidom and searching for \"/>\", we find this:\n# Method of the Element(Node) class.\ndef writexml(self, writer, indent=\"\", addindent=\"\", newl=\"\"):\n # [snip]\n if self.childNodes:\n writer.write(\">%s\"%(newl))\n for node in self.childNodes:\n node.write...
[ 4, 1, 1 ]
[]
[]
[ "python", "string", "xml" ]
stackoverflow_0001187718_python_string_xml.txt
Q: How can I get nose to find class attributes defined on a base test class? I'm getting some integration tests running against the database, and I'd like to have a structure that looks something like this: class OracleMixin(object): oracle = True # ... set up the oracle connection class SqlServerMixin(objec...
How can I get nose to find class attributes defined on a base test class?
I'm getting some integration tests running against the database, and I'd like to have a structure that looks something like this: class OracleMixin(object): oracle = True # ... set up the oracle connection class SqlServerMixin(object): sql_server = True # ... set up the sql server connection class Som...
[ "I do not think you can without making your own plugin. The the code in the attrib plugin only looks at the classes __dict__. Here is the code \ndef wantClass(self, cls):\n \"\"\"Accept the class if the class or any method is wanted.\n \"\"\"\n cls_attr = cls.__dict__\n if self.validateAttrib(cls_attr)...
[ 4, 0 ]
[]
[]
[ "integration_testing", "mixins", "multiple_inheritance", "nose", "python" ]
stackoverflow_0001188922_integration_testing_mixins_multiple_inheritance_nose_python.txt
Q: In Python, what's the correct way to instantiate a class from a variable? Suppose that I have class C. I can write o = C() to create an instance of C and assign it to o. However, what if I want to assign the class itself into a variable and then instantiate it? For example, suppose that I have two classes, such as...
In Python, what's the correct way to instantiate a class from a variable?
Suppose that I have class C. I can write o = C() to create an instance of C and assign it to o. However, what if I want to assign the class itself into a variable and then instantiate it? For example, suppose that I have two classes, such as C1 and C2, and I want to do something like: if (something): classToUse = C1...
[ "o = C2()\n\nThis will accomplish what you want. Or, in case you meant to use classToUse, simply use:\no = classToUse()\n\nHope this helps.\n", "You're almost there. Instead of calling an instantiate() method, just call the variable directly. It's assigned to the class, and classes are callable:\nif (something)...
[ 18, 12, 2, 0 ]
[]
[]
[ "instantiation", "python" ]
stackoverflow_0001189649_instantiation_python.txt
Q: Executing current Python script in Emacs on Windows I've just started learning Emacs, and decided to start writing Python in it. I tried using C-c C-c to execute the current buffer, but I get the message Searching for program: no such file or directory, python. I've looked on google, but I'm none the wiser as to h...
Executing current Python script in Emacs on Windows
I've just started learning Emacs, and decided to start writing Python in it. I tried using C-c C-c to execute the current buffer, but I get the message Searching for program: no such file or directory, python. I've looked on google, but I'm none the wiser as to how to sort this out (bear in mind I know next to nothing ...
[ "I managed to work it out, following the instructions here. I used python-mode.el, when before I had been using Emacs' built-in python.el, but according to emacswiki, \"The version in Emacs 22 has a bunch of problems\". Hope someone else running Emacs 22 on Windows XP finds this useful one day!\n", "Try adding C:...
[ 3, 2 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0001190595_emacs_python.txt
Q: jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and...
jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET"
The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, ...
[ "I think you have a cross-subdomain issue, sub.domain.tld and domain.ltd are not the same.\nI recommend you to install Firebug and check if your code is throwing an Permission denied Exception when the request starts, if it's the case, go for JSONP...\n", "change your url to something like:\n\"https://celeryserv...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "jquery", "json", "python" ]
stackoverflow_0001186827_django_jquery_json_python.txt
Q: Hello World from cython wiki not working I'm trying to follow this tutorial from Cython: http://docs.cython.org/docs/tutorial.html#the-basics-of-cython and I'm having a problem. The files are very simple. I have a helloworld.pyx: print "Hello World" and a setup.py: from distutils.core import setup from distutils...
Hello World from cython wiki not working
I'm trying to follow this tutorial from Cython: http://docs.cython.org/docs/tutorial.html#the-basics-of-cython and I'm having a problem. The files are very simple. I have a helloworld.pyx: print "Hello World" and a setup.py: from distutils.core import setup from distutils.extension import Extension from Cython.Distut...
[ "Looks like you're missing some package like python_dev or the like -- Debian and derivatives (including Ubuntu) have long preferred to isolate everything that could possibly be of \"developer\"'s use from the parts of a package that are for \"everybody\"... a philosophical stance I could debate against (and have d...
[ 4, 1 ]
[]
[]
[ "c++", "cython", "python" ]
stackoverflow_0001191600_c++_cython_python.txt
Q: Threading in Python What are the modules used to write multi-threaded applications in Python? I'm aware of the basic concurrency mechanisms provided by the language and also of Stackless Python, but what are their respective strengths and weaknesses? A: In order of increasing complexity: Use the threading module...
Threading in Python
What are the modules used to write multi-threaded applications in Python? I'm aware of the basic concurrency mechanisms provided by the language and also of Stackless Python, but what are their respective strengths and weaknesses?
[ "In order of increasing complexity:\nUse the threading module\nPros:\n\nIt's really easy to run any function (any callable in fact) in its\nown thread.\nSharing data is if not easy (locks are never easy :), at\nleast simple.\n\nCons:\n\nAs mentioned by Juergen Python threads cannot actually concurrently access stat...
[ 120, 104, 22, 13, 6, 4, 3 ]
[]
[]
[ "multithreading", "python", "python_stackless" ]
stackoverflow_0001190206_multithreading_python_python_stackless.txt
Q: Python classes for simple GTD app I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however. Here are the classes I have so far: class Project: def __init__(self, name, actio...
Python classes for simple GTD app
I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however. Here are the classes I have so far: class Project: def __init__(self, name, actions=[]): self.name = name ...
[ "You could create a subprojects member, similar to your actions list, and assign projects to it in a similar way. No subclassing of Project is necessary.\nclass Project:\n def __init__(self, name, actions=[], subprojects=[]):\n self.name = name\n self.actions = actions\n self.subprojects = s...
[ 3, 0, 0 ]
[]
[]
[ "gtd", "python", "recursion" ]
stackoverflow_0001175110_gtd_python_recursion.txt
Q: What's a good way to replace international characters with their base Latin counterparts using Python? Say I have the string "blöt träbåt" which has a few a and o with umlaut and ring above. I want it to become "blot trabat" as simply as possibly. I've done some digging and found the following method: import unico...
What's a good way to replace international characters with their base Latin counterparts using Python?
Say I have the string "blöt träbåt" which has a few a and o with umlaut and ring above. I want it to become "blot trabat" as simply as possibly. I've done some digging and found the following method: import unicodedata unicode_string = unicodedata.normalize('NFKD', unicode(string)) This will give me the string in unic...
[ "It would be better if you created an explicit table, and then used the unicode.translate method. The advantage would be that transliteration is more precise, e.g. transliterating \"ö\" to \"oe\" and \"ß\" to \"ss\", as should be done in German.\nThere are several transliteration packages on PyPI: translitcodec, Un...
[ 7 ]
[]
[]
[ "internationalization", "python", "string" ]
stackoverflow_0001192367_internationalization_python_string.txt
Q: To set up environmental variables for a Python web application I need to set up the following env variables such that I can a database program which use PostgreSQL export PGDATA="/home/masi/postgres/var" export PGPORT="12428" I know that the problem may be solved by adding the files to .zshrc. However, I am not s...
To set up environmental variables for a Python web application
I need to set up the following env variables such that I can a database program which use PostgreSQL export PGDATA="/home/masi/postgres/var" export PGPORT="12428" I know that the problem may be solved by adding the files to .zshrc. However, I am not sure whether it is the right way to go. How can you add env variables...
[ "You only need to set the PGDATA variable in the script that starts the server. The client only cares about the port.\nYou do have to set the port value if you must run it on a non-standard port. I assume you have a good reason to not just run it on the default port? If you do run it on the default port (5432), it ...
[ 4, 3 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0001187716_postgresql_python.txt
Q: Unicode to UTF8 for CSV Files - Python via xlrd I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8. I imaging that this has nothing to do with the xlrd mo...
Unicode to UTF8 for CSV Files - Python via xlrd
I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8. I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or ot...
[ "I expect the cell_value return value is the unicode string that's giving you problems (please print its type() to confirm that), in which case you should be able to solve it by changing this one line:\nthis_row.append(s.cell_value(row,col))\n\nto:\nthis_row.append(s.cell_value(row,col).encode('utf8'))\n\nIf cell_v...
[ 26, 9, 0, 0 ]
[]
[]
[ "csv", "encoding", "python", "unicode", "xlrd" ]
stackoverflow_0001189111_csv_encoding_python_unicode_xlrd.txt
Q: User in Form-Class I have a form like this: class MyForm(forms.Form): [...] which is rendered in my view: if request.method == 'GET': form = MyForm(request.GET) Now, i want to add a form field which contains a set of values in a select-field, and the queryset must be filtered by the currently logged in user....
User in Form-Class
I have a form like this: class MyForm(forms.Form): [...] which is rendered in my view: if request.method == 'GET': form = MyForm(request.GET) Now, i want to add a form field which contains a set of values in a select-field, and the queryset must be filtered by the currently logged in user. So I changed the method...
[ "Replace your last line of code with this:\nself.fields['myfield'].choices = [('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)]\n\n", "I think here's what you're after:\nclass MyForm(forms.Form):\n def __init__(self, user, *args, **kwargs):\n super(MyForm, self).__init__(*arg...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001193084_django_python.txt
Q: Python's unittest and dynamic creation of test cases Possible Duplicate: How do you generate dynamic (parameterized) unit tests in Python? Is there a way to dynamically create unittest test cases? I have tried the following... class test_filenames(unittest.TestCase): def setUp(self): for category, t...
Python's unittest and dynamic creation of test cases
Possible Duplicate: How do you generate dynamic (parameterized) unit tests in Python? Is there a way to dynamically create unittest test cases? I have tried the following... class test_filenames(unittest.TestCase): def setUp(self): for category, testcases in files.items(): for testindex, cur...
[ "In the following solution, the class Tests contains the helper method check and no test cases statically defined. Then, to dynamically add a test cases, I use setattr to define functions in the class. In the following example, I generate test cases test_<i>_<j> with i and j spanning [1,3] and [2,5] respectively, w...
[ 25, 12 ]
[]
[]
[ "dynamic", "python", "unit_testing" ]
stackoverflow_0001193909_dynamic_python_unit_testing.txt
Q: Nested Set Model and SQLAlchemy -- Adding New Nodes How should new nodes be added with SQLAlchemy to a tree implemented using the Nested Set Model? class Category(Base): __tablename__ = 'categories' id = Column(Integer, primary_key=True) name = Column(String(128), nullable=False) lft = Column(Inte...
Nested Set Model and SQLAlchemy -- Adding New Nodes
How should new nodes be added with SQLAlchemy to a tree implemented using the Nested Set Model? class Category(Base): __tablename__ = 'categories' id = Column(Integer, primary_key=True) name = Column(String(128), nullable=False) lft = Column(Integer, nullable=False, unique=True) rgt = Column(Intege...
[ "You might want to look at the nested sets example in the examples directory of SQLAlchemy. This implements the model at the Python level.\nDoing it at the database level with triggers would need some way to communicate the desired parent, either as an extra column or as a stored procedure.\n" ]
[ 6 ]
[]
[]
[ "nested_sets", "python", "sql", "sqlalchemy", "tree" ]
stackoverflow_0001186086_nested_sets_python_sql_sqlalchemy_tree.txt
Q: SQLAlchemy: Operating on results I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown. This is what I attempted ( after the initial connection of course ): metadata = MetaData(engine) users_table = Table('fu...
SQLAlchemy: Operating on results
I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown. This is what I attempted ( after the initial connection of course ): metadata = MetaData(engine) users_table = Table('fusion_users', metadata, autoload=True) ...
[ "A SQLAlchemy RowProxy object has dict-like methods -- .items() to get all name/value pairs, .keys() to get just the names (e.g. to display them as a header line, then use .values() for the corresponding values or use each key to index into the RowProxy object, etc, etc -- so it being a \"smart object\" rather than...
[ 16, 15 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0001192269_python_sql_sqlalchemy.txt
Q: What's wrong with this bit of python code using lambda? Some python code that keeps throwing up an invalid syntax error: stat.sort(lambda x1, y1: 1 if x1.created_at < y1.created_at else -1) A: This is a better solution: stat.sort(key=lambda x: x.created_at, reverse=True) Or, to avoid the lambda altogether: from...
What's wrong with this bit of python code using lambda?
Some python code that keeps throwing up an invalid syntax error: stat.sort(lambda x1, y1: 1 if x1.created_at < y1.created_at else -1)
[ "This is a better solution:\nstat.sort(key=lambda x: x.created_at, reverse=True)\n\nOr, to avoid the lambda altogether:\nfrom operator import attrgetter\nstat.sort(key=attrgetter('created_at'), reverse=True)\n\n", "Try the and-or trick:\nlambda x1, y1: x1.created_at < y1.created_at and 1 or -1\n\n" ]
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001194543_python.txt
Q: Forward declaration - no admin page in django? This is probably a db design issue, but I couldn't figure out any better. Among several others, I have these models: class User(models.Model): name = models.CharField( max_length=40 ) # some fields omitted bands = models.ManyToManyField( Band ) and class Band(m...
Forward declaration - no admin page in django?
This is probably a db design issue, but I couldn't figure out any better. Among several others, I have these models: class User(models.Model): name = models.CharField( max_length=40 ) # some fields omitted bands = models.ManyToManyField( Band ) and class Band(models.Model): creator = models.ForeignKey( User ) ...
[ "See: http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey, which says:\n\nIf you need to create a relationship on a model that has not \n yet been defined, you can use the name of the model, rather \n than the model object itself:\n\n class Car(models.Model):\n manufacturer = models.ForeignKey...
[ 12 ]
[]
[]
[ "circular_dependency", "database_design", "django", "forward_declaration", "python" ]
stackoverflow_0001194723_circular_dependency_database_design_django_forward_declaration_python.txt
Q: Python scoping problem I have a trivial example: def func1(): local_var = None def func(args): print args, print "local_var:", local_var local_var = "local" func("first") func("second") func1() I expect the output to be: first local_var: None second local_var: local ...
Python scoping problem
I have a trivial example: def func1(): local_var = None def func(args): print args, print "local_var:", local_var local_var = "local" func("first") func("second") func1() I expect the output to be: first local_var: None second local_var: local However, my actual output is...
[ "The assignment to local_var in func makes it local to func -- so the print statement references that \"very very local\" variable before it's ever assigned to, as the exception says. As jtb says, in Python 3 you can solve this with nonlocal, but it's clear from your code, using print statements, that you're workin...
[ 9, 1, 1, 1 ]
[]
[]
[ "python", "scoping" ]
stackoverflow_0001195577_python_scoping.txt
Q: Load non-uniform data from a txt file into a msql database I have text files with a lot of uniform rows that I'd like to load into a mysql database, but the files are not completely uniform. There are several rows at the beginning for some miscellaneous information, and there are timestamps about every 6 lines. "L...
Load non-uniform data from a txt file into a msql database
I have text files with a lot of uniform rows that I'd like to load into a mysql database, but the files are not completely uniform. There are several rows at the beginning for some miscellaneous information, and there are timestamps about every 6 lines. "LOAD DATA INFILE" doesn't seem like the answer here because of my...
[ "LOAD DATA INFILE has an IGNORE LINES option which you can use to skip the header. According to the docs, it also has a \" LINES STARTING BY 'prefix_string'\" option which you could use since all of your data lines seem to start with two blanks, while your timestamps start at the beginning of the line.\n", "Anoth...
[ 2, 2 ]
[]
[]
[ "file_io", "load_data_infile", "mysql", "python", "sqlalchemy" ]
stackoverflow_0001195753_file_io_load_data_infile_mysql_python_sqlalchemy.txt
Q: django auth User truncating email field I have an issue with the django.contrib.auth User model where the email max_length is 75. I am receiving email addresses that are longer than 75 characters from the facebook api, and I need to (would really like to) store them in the user for continuity among users that are ...
django auth User truncating email field
I have an issue with the django.contrib.auth User model where the email max_length is 75. I am receiving email addresses that are longer than 75 characters from the facebook api, and I need to (would really like to) store them in the user for continuity among users that are from facebook connect and others. I am able t...
[ "EmailField 75 chars length is hardcoded in django. You can fix this like that:\nfrom django.db.models.fields import EmailField\ndef email_field_init(self, *args, **kwargs):\n kwargs['max_length'] = kwargs.get('max_length', 200)\n CharField.__init__(self, *args, **kwargs)\nEmailField.__init__ = email_field_init\n...
[ 12, 2 ]
[]
[]
[ "authentication", "django", "mysql", "python" ]
stackoverflow_0000915910_authentication_django_mysql_python.txt
Q: How to manage many to one relationship in Django I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py: from django.db import models class Office(models.Model): name = models.CharField(max_length=30) class Province(model...
How to manage many to one relationship in Django
I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py: from django.db import models class Office(models.Model): name = models.CharField(max_length=30) class Province(models.Model): numberPlate = models.IntegerField(prima...
[ "It seams that you have your models setup backwards. If you want province to have many offices, then province should be a foreign key in the Office model.\nfrom django.db import models\n\nclass Province(models.Model):\n numberPlate = models.IntegerField(primary_key=True)\n name = models.CharField(max_length=2...
[ 6, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0001195911_django_django_admin_django_models_python.txt
Q: Python memory footprint vs. heap size I'm having some memory issues while using a python script to issue a large solr query. I'm using the solrpy library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed t...
Python memory footprint vs. heap size
I'm having some memory issues while using a python script to issue a large solr query. I'm using the solrpy library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed through top balloons to ~190MB. PID USER ...
[ "Python allocates Unicode objects from the C heap. So when you allocate many of them (along with other malloc blocks), then release most of them except for the very last one, C malloc will not return any memory to the operating system, as the C heap will only shrink on the end (not in the middle). Releasing the las...
[ 6, 2, 1, 0 ]
[]
[]
[ "memory_leaks", "python", "solr" ]
stackoverflow_0001194416_memory_leaks_python_solr.txt
Q: Using Eval in Python to create class variables I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the ...
Using Eval in Python to create class variables
I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables ...
[ "You can use the setattr function, which takes three arguments: the object, the name of the attribute, and it's value. For example,\nsetattr(self, 'wavelength', wavelength_val)\n\nis equivalent to:\nself.wavelength = wavelength_val\n\nSo you could do something like this:\nfor variable in self.variable_list:\n ...
[ 18, 1, 0, 0 ]
[]
[]
[ "python", "scientific_computing", "wxpython" ]
stackoverflow_0001144702_python_scientific_computing_wxpython.txt
Q: Running programs w/ a GUI over a remote connection I'm trying to start perfmon and another program that have GUI's through a python script that uses a PKA ssh connection. Is it possible to do this? If so could anyone point me in the right direction? A: I've found a program called psexec that will open a program ...
Running programs w/ a GUI over a remote connection
I'm trying to start perfmon and another program that have GUI's through a python script that uses a PKA ssh connection. Is it possible to do this? If so could anyone point me in the right direction?
[ "I've found a program called psexec that will open a program remotely on another windows machine. http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx\nThere are options or flags that you can use with this command line program to open a program with a GUI and view it on a remote machine.\n", "If you mean...
[ 6, 2 ]
[]
[]
[ "perfmon", "python", "ssh", "user_interface" ]
stackoverflow_0001125894_perfmon_python_ssh_user_interface.txt
Q: Python Hangs When Importing Swig Generated Wrapper Python is 'hanging' when I try to import a c++ shared library into the windows version of python 2.5 and I have no clue why. On Linux, everything works fine. We can compile all of our C++ code, generate swig wrapper classes. They compile and can be imported and ...
Python Hangs When Importing Swig Generated Wrapper
Python is 'hanging' when I try to import a c++ shared library into the windows version of python 2.5 and I have no clue why. On Linux, everything works fine. We can compile all of our C++ code, generate swig wrapper classes. They compile and can be imported and used in either python 2.5 or 2.6. Now, we are trying to...
[ "A technique I've used is to insert a \"hard\" breakpoint (__asm int 3) in the module init function. Then either run it through a debugger or just run it and let the windows debugger pop when the interrupt is called.\nYou can download a nice windows debugger from Microsoft here.\n" ]
[ 1 ]
[]
[]
[ "cygwin", "python", "swig" ]
stackoverflow_0001162461_cygwin_python_swig.txt
Q: How to open python source files using the IDLE shell? If I import a module in IDLE using: import <module_name> print <module_name>.__file__ how can I open it without going through the Menu->File->Open multiple-step procedure? It would be nice to open it via a command that takes the path and outputs a separate ed...
How to open python source files using the IDLE shell?
If I import a module in IDLE using: import <module_name> print <module_name>.__file__ how can I open it without going through the Menu->File->Open multiple-step procedure? It would be nice to open it via a command that takes the path and outputs a separate editor like IDLE.
[ "\nYou can use ALT-M and write the name of the module in the popup box\nYou can use CTRL-O to open a file\n\n", "I don't think IDLE will do it for you, but if you use Wing, you can mouse over the name of the module, and do a <Ctrl>-<Left Click>, or open the right click context menu on the module name, and select ...
[ 2, 0 ]
[]
[]
[ "file", "ide", "python" ]
stackoverflow_0001186884_file_ide_python.txt
Q: How do I change the directory of InMemoryUploadedFile? It seems that if I do not create a ModelForm from a model, and create a new object and save it, it will not respect the field's upload directory. How do I change the directory of a InMemoryUploadedFile so I can manually implement the upload dir? Because the In...
How do I change the directory of InMemoryUploadedFile?
It seems that if I do not create a ModelForm from a model, and create a new object and save it, it will not respect the field's upload directory. How do I change the directory of a InMemoryUploadedFile so I can manually implement the upload dir? Because the InMemoryUploadedFile obj is just the filename, and I would lik...
[ "How did you define the attribute of image in your ProductImages model? Did you have upload_to argument in your FileField? \nclass ProductImages(models.Model):\n image = models.FileField(upload_to=\"images/\")\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001194963_django_python.txt
Q: FormEncode, pylons, and mako example I'm working in pylons with mako, and I'd like to create forms and validations with FormEncode for several parts of my application. I can't seem to find any good examples of the whole process. My question is twofold: Technical FancyValidators and Schemas - Their relationship a...
FormEncode, pylons, and mako example
I'm working in pylons with mako, and I'd like to create forms and validations with FormEncode for several parts of my application. I can't seem to find any good examples of the whole process. My question is twofold: Technical FancyValidators and Schemas - Their relationship and syntax Pylons controllers and mako tem...
[ "I don't know if you've gone through the pylons book, but I found chapter 6 to be very thorough in regards to forms. \nAs far as best practices go, I'm not exactly sure what you are looking for. A controller method maps to a url and needs to return a string-like object. How you arrive at that is largely application...
[ 1 ]
[]
[]
[ "formencode", "mako", "pylons", "python", "validation" ]
stackoverflow_0001191265_formencode_mako_pylons_python_validation.txt
Q: Passing a Django model attribute name to a function I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like...
Passing a Django model attribute name to a function
I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like this: class Comment(models.Model): name = models.Cha...
[ "def do_something(attribute, objects):\n results = []\n for object in objects:\n if hasattr(object, attribute):\n results.append(getattr(object, attribute))\n return results\n\nOr, more succinctly,\ndef do_something(attribute, objects):\n return [getattr(o, attribute) for o in objects ...
[ 4, 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001197042_django_python.txt
Q: Is it possible to overload ++ operators in Python? Is it possible to overload ++ operators in Python? A: There is no ++ operator in Python (nor '--'). Incrementing is usually done with the += operator instead. A: Nope, it is not possible to overload the unary ++ operator, because it is not an operator at all i...
Is it possible to overload ++ operators in Python?
Is it possible to overload ++ operators in Python?
[ "There is no ++ operator in Python (nor '--'). Incrementing is usually done with the += operator instead.\n", "Nope, it is not possible to overload the unary ++ operator, because it is not an operator at all in Python.\nOnly (a subset of) the operators that are allowed by the Python syntax (those operators that a...
[ 20, 18, 7, 5, 5 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0000774784_operator_overloading_python.txt
Q: Installing Django with mod_wsgi I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app. The server I use is WAMP2.0. I've been a PHP programmer for years now and I've been using W...
Installing Django with mod_wsgi
I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app. The server I use is WAMP2.0. I've been a PHP programmer for years now and I've been using WAMPServer since long ago. I installed...
[ "You have:\nWSGIScriptAlias / /C:/Users/Marcos/Documents/mysite/apache/django.wsgi\n\nThat is wrong as RHS is not a valid Windows pathname. Use:\nWSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi\n\nThat is, no leading slash before the Windows drive specifier.\nOther than that, follow the mod_ws...
[ 7, 6, 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0001195260_apache_django_mod_wsgi_python.txt
Q: Processing chunked encoded HTTP POST requests in python (or generic CGI under apache) I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CG...
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too. I'd like to kno...
[ "I had the exact same problem a year ago with a J2ME client talking to a Python/Ruby backend. The only solution I found which doesn't require application or infrastructure level changes was to use a relatively unknown feature of mod_proxy.\nMod_proxy has the ability to buffer incoming (chunked) requests, and then r...
[ 6, 2, 2, 2, 1 ]
[]
[]
[ "http", "java_me", "midlet", "post", "python" ]
stackoverflow_0000284741_http_java_me_midlet_post_python.txt
Q: CopyBlock tag for Django How can I write a tag "copyblock" for Django templates? For such a function: <title> {% block title %} some title... {% endblock %} </title> <h1>{% copyblock title %}</h1> A: Take a look at the solutions mentioned in this question: How to repeat a "block" in a django template A: Djang...
CopyBlock tag for Django
How can I write a tag "copyblock" for Django templates? For such a function: <title> {% block title %} some title... {% endblock %} </title> <h1>{% copyblock title %}</h1>
[ "Take a look at the solutions mentioned in this question:\n\nHow to repeat a \"block\" in a django template\n\n", "Django's template parser doesn't expose blocks by name. Instead, they are organized into a tree structure in the Django Template's nodelist, with rendering pushing and popping on the stack of templat...
[ 1, 1 ]
[]
[]
[ "django", "django_templates", "python", "templates" ]
stackoverflow_0001197650_django_django_templates_python_templates.txt
Q: Web Services with Google App Engine I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml? Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not ...
Web Services with Google App Engine
I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml? Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not supported)? Any links o samples or articl...
[ "Google App Engine allows you to write web services that return any type of HTTP response content. This includes xml, json, text, etc.\nFor instance, take a look at the guestbook sample project offered by Google which shows the HTTP response coming back as text/plain:\n public class GuestbookServlet extends Htt...
[ 9, 3, 2 ]
[]
[]
[ "google_app_engine", "java", "python", "web_services" ]
stackoverflow_0001195893_google_app_engine_java_python_web_services.txt
Q: Python Printing StdOut As It Received I'm trying to run wrap a simple (windows) command line tool up in a PyQt GUI app that I am writing. The problem I have is that the command line tool throws it's progress out to stdout (it's a server reset command so you get "Attempting to stop" and "Restarting" type output. W...
Python Printing StdOut As It Received
I'm trying to run wrap a simple (windows) command line tool up in a PyQt GUI app that I am writing. The problem I have is that the command line tool throws it's progress out to stdout (it's a server reset command so you get "Attempting to stop" and "Restarting" type output. What I am trying to do is capture the output...
[ "Interactive communication through stdin/stdout is a common problem.\nYou're in luck though, with PyQt you can use QProcess, as described here:\nhttp://diotavelli.net/PyQtWiki/Capturing_Output_from_a_Process\n", "Do I understand the question?\nI believe you're running something like \"echo first; sleep 60; echo s...
[ 1, 0 ]
[]
[]
[ "python", "stdout" ]
stackoverflow_0001152160_python_stdout.txt
Q: Python: How to get rid of circular dependency involving decorator? I had got a following case of circular import (here severly simplified): array2image.py conversion module: import tuti @tuti.log_exec_time # can't do that, evaluated at definition time def convert(arr): '''Convert array to image.''' return...
Python: How to get rid of circular dependency involving decorator?
I had got a following case of circular import (here severly simplified): array2image.py conversion module: import tuti @tuti.log_exec_time # can't do that, evaluated at definition time def convert(arr): '''Convert array to image.''' return image.fromarray(arr) tuti.py test utils module: import array2image de...
[ "The answer you came up with is a valid solution. \nHowever, if you were that worried about circular dependencies, I would say that log_exec_time would belong in its own file since its not dependent on anything else in tuti.py.\n" ]
[ 4 ]
[]
[]
[ "circular_dependency", "decorator", "python" ]
stackoverflow_0001198188_circular_dependency_decorator_python.txt
Q: Tkinter locks Python when an icon is loaded and tk.mainloop is in a thread Here's the test case... import Tkinter as tk import thread from time import sleep if __name__ == '__main__': t = tk.Tk() thread.start_new_thread(t.mainloop, ()) # t.iconbitmap('icon.ico') b = tk.Button(text='test', command...
Tkinter locks Python when an icon is loaded and tk.mainloop is in a thread
Here's the test case... import Tkinter as tk import thread from time import sleep if __name__ == '__main__': t = tk.Tk() thread.start_new_thread(t.mainloop, ()) # t.iconbitmap('icon.ico') b = tk.Button(text='test', command=exit) b.grid(row=0) while 1: sleep(1) This code works. Uncomm...
[ "I believe you should not execute the main loop on a different thread. AFAIK, the main loop should be executed on the same thread that created the widget. \nThe GUI toolkits that I am familiar with (Tkinter, .NET Windows Forms) are that way: You can manipulate the GUI from one thread only.\nOn Linux, your code rais...
[ 22 ]
[]
[]
[ "green_threads", "python", "tkinter", "winapi" ]
stackoverflow_0001198262_green_threads_python_tkinter_winapi.txt
Q: django one to many issue at the admin panel Greetings, I have these 2 models: from django.db import models class Office(models.Model): name = models.CharField(max_length=30) person = models.CharField(max_length=30) phone = models.CharField(max_length=20) fax = models.CharField(max_length=20) a...
django one to many issue at the admin panel
Greetings, I have these 2 models: from django.db import models class Office(models.Model): name = models.CharField(max_length=30) person = models.CharField(max_length=30) phone = models.CharField(max_length=20) fax = models.CharField(max_length=20) address = models.CharField(max_length=100) def...
[ "I'm not sure if I'm misunderstanding you, but your models currently say \"an office can be associated with many provinces, but each province may only have one office\". This contradicts what you want. Use a ManyToMany field instead:\nclass Province(models.Model):\n numberPlate = models.IntegerField(primary_key=...
[ 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0001198589_django_django_admin_django_models_python.txt
Q: Provide discount to preferred customer with Satchmo? I am new to Satchmo -- picked it up because I needed payment processing for site subscriptions and physical product. My site will have two classes of users: paid subscribers and free users. Both can order a physical product. Paid subscribers get an automatic di...
Provide discount to preferred customer with Satchmo?
I am new to Satchmo -- picked it up because I needed payment processing for site subscriptions and physical product. My site will have two classes of users: paid subscribers and free users. Both can order a physical product. Paid subscribers get an automatic discount on all orders. I don't see a configuration for this...
[ "Checkout the tiered pricing module\n" ]
[ 2 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0000647257_django_python_satchmo.txt
Q: How to set the encoding for the tables' char columns in django? I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run manage.py syncdb all respective columns are created with cp1252 character set (where did it get that -- I have no ...
How to set the encoding for the tables' char columns in django?
I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run manage.py syncdb all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column... Is there a way to...
[ "Django does not specify charset and collation in CREATE TABLE statements. Everything is determined by database charset. Doing ALTER DATABASE ... CHARACTER SET utf8 COLLATE utf8_general_ci before running syncdb should help.\nFor connection, Django issues SET NAMES utf8 automatically, so you don't need to worry abou...
[ 20, 4, 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0001198486_django_mysql_python.txt
Q: What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? The code below is outdated in Python 3.0 by being replaced by subprocess.getstatusoutput(). import commands (ret, out) = commands.getstatusoutput('some command') print ret print out The real questio...
What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python?
The code below is outdated in Python 3.0 by being replaced by subprocess.getstatusoutput(). import commands (ret, out) = commands.getstatusoutput('some command') print ret print out The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly under Window...
[ "I wouldn't really consider this multiplatform, but you can use subprocess.Popen:\nimport subprocess\npipe = subprocess.Popen('dir', stdout=subprocess.PIPE, shell=True, universal_newlines=True)\noutput = pipe.stdout.readlines()\nsts = pipe.wait()\nprint sts\nprint output\n\n\nHere's a drop-in replacement for getsta...
[ 8, 8, 1 ]
[]
[]
[ "process", "python", "redirect" ]
stackoverflow_0001193583_process_python_redirect.txt
Q: installed module on python editor how can i import modules/packages at python3.0 editor IDLE. and can we see all the modules contain/included by it. A: >>> import idle >>> dir(idle)
installed module on python editor
how can i import modules/packages at python3.0 editor IDLE. and can we see all the modules contain/included by it.
[ ">>> import idle\n>>> dir(idle)\n\n" ]
[ 1 ]
[]
[]
[ "editor", "python" ]
stackoverflow_0001199249_editor_python.txt
Q: Structuring model layout with regards to parents? How does one go about structuring his db.Models effectively? For instance, lets say I have a model for Countries, with properties like "name, northern_hemisphere(boolean), population, states (list of states), capital(boolean). And another model called State or coun...
Structuring model layout with regards to parents?
How does one go about structuring his db.Models effectively? For instance, lets say I have a model for Countries, with properties like "name, northern_hemisphere(boolean), population, states (list of states), capital(boolean). And another model called State or county or something with properties "name, population, citi...
[ "If you want to store relational data in the datastore of Google App Engine, this is a great article to start out with: Modeling Entity Relationships.\nYou use ReferenceProperty to specify a relationship between two models:\nclass Country(db.Model):\n name = db.StringProperty(required=True)\n\nclass State(db.Mod...
[ 4 ]
[]
[]
[ "django_models", "google_app_engine", "python" ]
stackoverflow_0001199713_django_models_google_app_engine_python.txt
Q: How do I use Python serverside with shared hosting? I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PH...
How do I use Python serverside with shared hosting?
I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.
[ "When I used shared hosting I found that if I renamed the file to .py and prefixed it with a shebang line then it would be executed as Python.\n#!/usr/bin/python\n\nWas probably pretty bad practice, but it did work. Don't expect to be able to spit out any extensive web apps with it though.\n", "There are many way...
[ 3, 2, 2, 1 ]
[]
[]
[ "python", "server_side" ]
stackoverflow_0001199703_python_server_side.txt
Q: Python: Mapping from intervals to values I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way). The code that is now handling the work is: if p <= 100: re...
Python: Mapping from intervals to values
I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way). The code that is now handling the work is: if p <= 100: return 0 elif p > 100 and p <= 300: return 1...
[ "import bisect\nbisect.bisect_left([100,300,500,800,1000], p)\n\nhere the docs: bisect\n", "You could try a take on this:\ndef check_mapping(p):\n mapping = [(100, 0), (300, 1), (500, 2)] # Add all your values and returns here\n\n for check, value in mapping:\n if p <= check:\n return valu...
[ 53, 3, 3, 0, 0, 0 ]
[]
[]
[ "intervals", "python", "range" ]
stackoverflow_0001199053_intervals_python_range.txt
Q: Django (?) really slow with large datasets after doing some python profiling I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one. ...
Django (?) really slow with large datasets after doing some python profiling
I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one. First, some context: I have a page that spits out reports of sales data. The data ...
[ "There is a lot of things to assume about your problem as you don't have any type of code sample.\nHere are my assumptions: You are using Django's built-in ORM tools and models (i.e. sales-data = modelobj.objects().all() ) and on the PHP side you are dealing with direct SQL queries and working with a query_set.\nDj...
[ 7, 2, 2, 1 ]
[]
[]
[ "django", "optimization", "python" ]
stackoverflow_0001173798_django_optimization_python.txt
Q: How to import python module in a shared folder? I have some python modules in a shared folder on a Windows machine. The file is \mtl12366150\test\mymodule.py os.path.exists tells me this path is valid. I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid). When I try...
How to import python module in a shared folder?
I have some python modules in a shared folder on a Windows machine. The file is \mtl12366150\test\mymodule.py os.path.exists tells me this path is valid. I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid). When I try to import mymodule I get an error saying the module ...
[ "Did you forget to use a raw string, or escape the backslashes, in your additional sys.path component? Remember that \"\\t\" is a tab, whereas r\"\\t\" or \"\\t\" are a backslash followed by a tab.\nIn most applications you are actually better off using forward slashes rather than backslashes even for Windows paths...
[ 1, 1, 0, 0, 0 ]
[ "\"I appended to sys.path ...\"\nPlease don't.\nSet the PYTHONPATH environment variable from outside your application.\n" ]
[ -2 ]
[ "directory", "import", "python", "shared" ]
stackoverflow_0001196708_directory_import_python_shared.txt
Q: Using Storm: ImportError: No module named local As stated in the Storm documentation, I am doing the following to import the necessary symbols for using Storm: from storm.locals import * I'm using it alongside with Pylons, and storm is indeed installed as an egg in the virtual Python environment which Pylon setup...
Using Storm: ImportError: No module named local
As stated in the Storm documentation, I am doing the following to import the necessary symbols for using Storm: from storm.locals import * I'm using it alongside with Pylons, and storm is indeed installed as an egg in the virtual Python environment which Pylon setup for me, and it also searches the correct paths. Howe...
[ "Here's the code that's failing.\nFile '/home/andy/projects/evecharacters/evecharacters/controllers/characters.py', line 9 in <module>\n from storm.local import *\nImportError: No module named local\n\nYou claim your snippet is\nfrom storm.locals import *\n\nBut the error traceback says\nfrom storm.local import *\...
[ 1 ]
[]
[]
[ "python", "storm_orm" ]
stackoverflow_0001199415_python_storm_orm.txt
Q: pygame is screwing up ctypes import mymodule, ctypes #import pygame foo = ctypes.cdll.MyDll.foo print 'success' if i uncomment the import pygame this fails with WindowsError: [Errno 182] The operating system cannot load %1. the stack frame is in ctypes python code, trying to load MyDll. win32 error code 182 i...
pygame is screwing up ctypes
import mymodule, ctypes #import pygame foo = ctypes.cdll.MyDll.foo print 'success' if i uncomment the import pygame this fails with WindowsError: [Errno 182] The operating system cannot load %1. the stack frame is in ctypes python code, trying to load MyDll. win32 error code 182 is ERROR_INVALID_ORDINAL. if the p...
[ "This sounds like a dll conflict. It seems that import pygame loads some dll that is not compatible with a dll that MyDll needs.\nYou should try to debug this with sysinternals ProcessExplorer, it can show which dlls a process has loaded; look for different dlls in both cases.\nAnother usefull tool to debug dll pr...
[ 2, 2 ]
[]
[]
[ "ctypes", "pygame", "python", "winapi" ]
stackoverflow_0000686798_ctypes_pygame_python_winapi.txt
Q: Whats the best way of putting tabular data into python? I have a CSV file which I am processing and putting the processed data into a text file. The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goe...
Whats the best way of putting tabular data into python?
I have a CSV file which I am processing and putting the processed data into a text file. The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file? For eg. Assume there is a column called '...
[ "Go with a list of lists. That is:\n[[col1, col2, col3, col4], # Row 1\n [col1, col2, col3, col4], # Row 2\n [col1, col2, col3, col4], # Row 3\n [col1, col2, col3, col4]] # Row 4\n\nTo modify a specific column, you can transform this into a list of columns with a single statement:\n>>> cols = zip(*rows)\n>>> cols\n...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "csv", "file", "python" ]
stackoverflow_0001199350_csv_file_python.txt
Q: Python interpolation I have a set of data that looks like: Table-1 X1 | Y1 ------+-------- 0.1 | 0.52147 0.02 | 0.8879 0.08 | 0.901 0.11 | 1.55 0.15 | 1.82 0.152 | 1.95 Table-2 X2 | Y2 -----+------ 0.2 | 0.11 0.21 | 0.112 0.34 | 0.120 0.33 |...
Python interpolation
I have a set of data that looks like: Table-1 X1 | Y1 ------+-------- 0.1 | 0.52147 0.02 | 0.8879 0.08 | 0.901 0.11 | 1.55 0.15 | 1.82 0.152 | 1.95 Table-2 X2 | Y2 -----+------ 0.2 | 0.11 0.21 | 0.112 0.34 | 0.120 0.33 | 1.121 I have to i...
[ "numpy.interp seems to be the function you want: pass your X1 as the first argument x, your X2 as the second argument xp, your Y2 as the third argument fp, and you'll get the Y values corresponding to the X1 coordinates.\nY2_at_X1 = np.interp(X1, X2, Y2)\n\nI'm assuming you want to completely ignore the existing Y1...
[ 31 ]
[]
[]
[ "interpolation", "numpy", "python" ]
stackoverflow_0001200644_interpolation_numpy_python.txt
Q: Which events can be bound to a Tkinter Frame? I am making a small application with Tkinter. I would like to clean few things in a function called when my window is closed. I am trying to bind the close event of my window with that function. I don't know if it is possible and what is the corresponding sequence. The...
Which events can be bound to a Tkinter Frame?
I am making a small application with Tkinter. I would like to clean few things in a function called when my window is closed. I am trying to bind the close event of my window with that function. I don't know if it is possible and what is the corresponding sequence. The Python documentation says: See the bind man page a...
[ "I believe this is the bind man page you may have been looking for; I believe the event you're trying to bind is Destroy. __del__ is not to be relied on (just too hard to know when a circular reference loop, e.g. parent to child widget and back, will stop it from triggering!), using event binding is definitely pref...
[ 3, 3 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0001200592_python_python_3.x_tkinter.txt
Q: pylint false positive for superclass __init__ If I derive a class from ctypes.BigEndianStructure, pylint warns if I don't call BigEndianStructure.__init__(). Great, but if I fix my code, pylint still warns: import ctypes class Foo(ctypes.BigEndianStructure): def __init__(self): ctypes.BigEndianStructu...
pylint false positive for superclass __init__
If I derive a class from ctypes.BigEndianStructure, pylint warns if I don't call BigEndianStructure.__init__(). Great, but if I fix my code, pylint still warns: import ctypes class Foo(ctypes.BigEndianStructure): def __init__(self): ctypes.BigEndianStructure.__init__(self) $ pylint mymodule.py C: 1: Miss...
[ "Try using the new-style super calls:\nclass Foo(ctypes.BigEndianStructure):\n def __init__(self):\n super(Foo, self).__init__()\n\n" ]
[ 6 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0001201094_pylint_python.txt
Q: Importing files in Python from __init__.py Suppose I have the following structure: app/ __init__.py foo/ a.py b.py c.py __init__.py a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py file so I d...
Importing files in Python from __init__.py
Suppose I have the following structure: app/ __init__.py foo/ a.py b.py c.py __init__.py a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py file so I don't have to import them in every one of the fil...
[ "You can do this using a common file such as include.py, but it goes against recommended practices because it involves a wildcard import. Consider the following files:\napp/\n __init__.py\nfoo/\n a.py\n b.py\n c.py\n include.py <- put the includes here.\n __init__.py\n\nNow, in a.py, etc., do:\nfr...
[ 14, 11, 6 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0001201115_import_module_python.txt
Q: Cannot insert data into an sqlite3 database using Python I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. However, I cannot insert data into the database. This is the code that I am trying to use to insert the data into the databas...
Cannot insert data into an sqlite3 database using Python
I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. However, I cannot insert data into the database. This is the code that I am trying to use to insert the data into the database: #! /usr/bin/env python import sqlite3 companies = ('GOOG'...
[ "Try to add\ndb.commit()\n\nafter the inserting.\n", "To insert the data you don't need a cursor\njust use the db\ndb.execute() instead of c.execute() and get rid of the c = db.cursor() line\nCursors aren't used to insert data, but usually to read data, or update data in place.\n" ]
[ 21, 4 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001201522_python_sqlite.txt
Q: Django and File Permissions: Best Practices? I am integrating "legacy" code with Django, and have problems when the process executing Django must write to legacy code directories where it lacks write permissions. (The legacy code is a Python backend to a Tkinter GUI, which I'm repurposing to a browser-based UI.) ...
Django and File Permissions: Best Practices?
I am integrating "legacy" code with Django, and have problems when the process executing Django must write to legacy code directories where it lacks write permissions. (The legacy code is a Python backend to a Tkinter GUI, which I'm repurposing to a browser-based UI.) I could: Make the legacy directory writeable to a...
[ "I'd go with option number 2. I don't think your django user is any more likely to get compromised than your Tkinter user. If there's something else under apache that you're worried about, run it under a separate apache with the right user.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001201785_django_python.txt
Q: How to identify the currently available wireless networks with Python in Windows? Is there a way to get a list of wireless networks (SSID's) that are currently available? And seeing what is the current connected network? Doesn't need to be exactly the SSID, I just need to identify the current wireless network. A...
How to identify the currently available wireless networks with Python in Windows?
Is there a way to get a list of wireless networks (SSID's) that are currently available? And seeing what is the current connected network? Doesn't need to be exactly the SSID, I just need to identify the current wireless network.
[ "You can use the netsh command. I don't remember the exact syntax used to invoke cli commands from within python, but I'm sure it should be fairly easy to locate.\nThe article below has more information about how to use netsh itself:\nhttp://technet.microsoft.com/en-us/library/cc755301%28WS.10%29.aspx#bkmk_wlanShow...
[ 2 ]
[]
[]
[ "python", "ssid", "windows", "windows_xp", "wireless" ]
stackoverflow_0001201749_python_ssid_windows_windows_xp_wireless.txt
Q: Check if an element exists I'm trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn't find any elegant way in the Making queries section of the Django documentation. The problem I have is that I've thousands of screenshots in a directory and need to check if...
Check if an element exists
I'm trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn't find any elegant way in the Making queries section of the Django documentation. The problem I have is that I've thousands of screenshots in a directory and need to check if they are in the database that i...
[ "If your Screenshot model has a lot of attributes, then the code you showed is doing unnecessary work for your specific need. For example, you can do something like this:\nfiles_in_db = Screenshot.objects.values_list('filename', flat=True).distinct()\n\nwhich will give you a list of all filenames in the database, a...
[ 2, 1, 1 ]
[]
[]
[ "django", "performance", "python" ]
stackoverflow_0001201381_django_performance_python.txt
Q: Windows build for PyLucene+JCC on python 2.6 Where can I download a PyLucene+JCC Windows build compiled for python 2.6? Jose A: I ended up using solr and interfacing it using XML/JSON. A: Not tested but there appears to be an egg here: http://code.google.com/p/pylucene-win32-binary/ A: you might want to see ...
Windows build for PyLucene+JCC on python 2.6
Where can I download a PyLucene+JCC Windows build compiled for python 2.6? Jose
[ "I ended up using solr and interfacing it using XML/JSON.\n", "Not tested but there appears to be an egg here:\nhttp://code.google.com/p/pylucene-win32-binary/\n", "you might want to see this recent mailing list post and the related thread. There's also a pylucene-dev thread that seems apropos. Unfortunately, ...
[ 3, 2, 1 ]
[]
[]
[ "jcc", "pylucene", "python", "windows" ]
stackoverflow_0000338008_jcc_pylucene_python_windows.txt
Q: OpenSocial Win32 compatibility I am planning to develop an application in Python on the Win32 platform. Does the OpenSocial API work upon the Win32 platform as well? To make things more clear, I need to use information from the OpenSocial API to conduct certain things in the application. A: Yes the general idea ...
OpenSocial Win32 compatibility
I am planning to develop an application in Python on the Win32 platform. Does the OpenSocial API work upon the Win32 platform as well? To make things more clear, I need to use information from the OpenSocial API to conduct certain things in the application.
[ "Yes the general idea of an API is it uses a standard language like XML or JSON or whatever. You can easily find libraries that read/write those formats in most languages, no matter the platform. If you're lucky someone will have written a library for the specific API you need.\nWhich in this case, they have :)\nht...
[ 1 ]
[]
[]
[ "opensocial", "python" ]
stackoverflow_0001202086_opensocial_python.txt
Q: random.sample return only characters instead of strings This is a kind of newbie question, but I couldn't find a solution. I read a list of strings from a file, and try to get a random, 5 element sample with random.sample, but the resultung list only contains characters. Why is that? How can I get a random sample ...
random.sample return only characters instead of strings
This is a kind of newbie question, but I couldn't find a solution. I read a list of strings from a file, and try to get a random, 5 element sample with random.sample, but the resultung list only contains characters. Why is that? How can I get a random sample list of strings? This is what I do: names = random.sample...
[ "If the names are all on seperate lines, ry the following:\nnames = random.sample(open('names.txt').readlines(), count)\nprint names\n\nEssentially you are going wrong because you need to pass an interable to random.sample(). When you pass a string it treats it like a list. If you're names are all on one line, yo...
[ 3 ]
[]
[]
[ "character", "python", "random", "string" ]
stackoverflow_0001202251_character_python_random_string.txt
Q: raw_input without leaving a history in readline Is there a way of using raw_input without leaving a sign in the readline history, so that it don't show when tab-completing? A: You could make a function something like import readline def raw_input_no_history(): input = raw_input() readline.remove_history...
raw_input without leaving a history in readline
Is there a way of using raw_input without leaving a sign in the readline history, so that it don't show when tab-completing?
[ "You could make a function something like\nimport readline\n\ndef raw_input_no_history():\n input = raw_input()\n readline.remove_history_item(readline.get_current_history_length()-1)\n return input\n\nand call that function instead of raw_input. You may not need the minus 1 dependent on where you call it ...
[ 7 ]
[]
[]
[ "history", "python", "readline", "tab_completion" ]
stackoverflow_0001202127_history_python_readline_tab_completion.txt
Q: How do I do cross-project refactorings with ropemacs? I have a file structure that looks something like this: project1_root/ tests/ ... src/ .ropeproject/ project1/ ... (project1 source code) project2_root/ tests/ ... src/ .ropeproject/ p...
How do I do cross-project refactorings with ropemacs?
I have a file structure that looks something like this: project1_root/ tests/ ... src/ .ropeproject/ project1/ ... (project1 source code) project2_root/ tests/ ... src/ .ropeproject/ project2/ ... (project2 source) I'm frequently ...
[ "The documention on ropemacs and ropemode seems to be very sparse (the homepage http://rope.sourceforge.net/ropemacs.html only point to the mercurial repos, which I checked out and read through the code), but it seems you can give a specific .ropeproject to use, and it may be guess it (ropemode/interfaces.py:_guess...
[ 3 ]
[]
[]
[ "elisp", "emacs", "python", "rope", "ropemacs" ]
stackoverflow_0001160057_elisp_emacs_python_rope_ropemacs.txt
Q: Sorting a list of dictionaries of objects by dictionary values This is related to the various other questions about sorting values of dictionaries that I have read here, but I have not found the answer. I'm a newbie and maybe I just didn't see the answer as it concerns my problem. I have this function, which I'm u...
Sorting a list of dictionaries of objects by dictionary values
This is related to the various other questions about sorting values of dictionaries that I have read here, but I have not found the answer. I'm a newbie and maybe I just didn't see the answer as it concerns my problem. I have this function, which I'm using as a Django custom filter to sort results from a list of dictio...
[ "You gain access to the keys using itemgetter and to the value attributes using attrgetter.\nSo, once you've extracted the key, value names you're interested in, you can construct your key function:\nfrom operator import attrgetter, itemgetter\nitmget = itemgetter('TOT_PTS_Misc')\nattget_v = attrgetter('value')\nat...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001202088_django_python.txt
Q: Python - tempfile.TemporaryFile cannot be read; why? The official documentation for TemporaryFile reads: The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Yet, the below code does not work as expected: import tempfile def play_with_fd(): with tem...
Python - tempfile.TemporaryFile cannot be read; why?
The official documentation for TemporaryFile reads: The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Yet, the below code does not work as expected: import tempfile def play_with_fd(): with tempfile.TemporaryFile() as f: f.write('test data\n')...
[ "You must put \nf.seek(0)\n\nbefore trying to read the file (this will send you to the beginning of the file), and\nf.seek(0, 2)\n\nto return to the end so you can assure you won't overwrite it.\n", "read() does not return anything because you are at the end of the file. You need to call seek() first before read(...
[ 39, 7 ]
[]
[]
[ "file", "io", "python", "temporary_files" ]
stackoverflow_0001202848_file_io_python_temporary_files.txt
Q: Constructor specialization in python Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent. So, in Python, we end up with something like this: class Parent(object): def __init__(self, a, b, c, ka=None, kb=None, kc=None): # do something with a, ...
Constructor specialization in python
Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent. So, in Python, we end up with something like this: class Parent(object): def __init__(self, a, b, c, ka=None, kb=None, kc=None): # do something with a, b, c, ka, kb, kc class Child(Parent): ...
[ "\"dozen child classes and lots of parameters\" sounds like a problem irrespective of parameter naming.\nI suspect that a little refactoring can peel out some Strategy objects that would simplify this hierarchy and make the super-complex constructors go away.\n", "Well, the only solution I could see is using a mi...
[ 8, 3, 1 ]
[]
[]
[ "anti_patterns", "class", "design_patterns", "oop", "python" ]
stackoverflow_0001202711_anti_patterns_class_design_patterns_oop_python.txt
Q: Good python library for designing a mmo? Actor based design i m trying to design a mmo game using python... I have evaluated stackless and since it is not the general python and it is a fork, i dont want to use it I am trying to chose between pysage candygram dramatis and parley any one try any of these libraries?...
Good python library for designing a mmo? Actor based design
i m trying to design a mmo game using python... I have evaluated stackless and since it is not the general python and it is a fork, i dont want to use it I am trying to chose between pysage candygram dramatis and parley any one try any of these libraries? Thanks a lot for your responses
[ "I would go for pysage.\nIt has the highest level of abstraction and a lightweight messaging API which will give you lots of flexibility. I would imagine when designing an MMO you will want as much flexibility as possible.\nIt also takes a page from Erlang's Actor model which is really solid.\nThat's great you ar...
[ 7, 1, 0 ]
[]
[]
[ "mmo", "python", "python_stackless", "stackless" ]
stackoverflow_0000312096_mmo_python_python_stackless_stackless.txt
Q: Sources of PyS60's standard functions (particularly appuifw.query) I need to give user ability to enter a time in form hh:mm:ss (with appropriate validation of course). And standard function appuifw.query(u'Label', 'time') works almost fine except that it allows to enter only hours and minutes (hh:mm). So I want t...
Sources of PyS60's standard functions (particularly appuifw.query)
I need to give user ability to enter a time in form hh:mm:ss (with appropriate validation of course). And standard function appuifw.query(u'Label', 'time') works almost fine except that it allows to enter only hours and minutes (hh:mm). So I want to look though its source and write my own that enhances it in the stated...
[ "Are the *_src.zip files on garage.maemo.org any useful? (I don't currently have the tools to verify what's in there.)\n" ]
[ 1 ]
[]
[]
[ "mobile", "pys60", "python" ]
stackoverflow_0001196050_mobile_pys60_python.txt
Q: Using Enthought I need to calculate the inverse of the complementary error function (erfc^(1)) for a problem. I was looking into Python tools for it, and many threads said Enthought has most of the math tools needed, so I downloaded and installed it in my local user account. But I am not very sure about how to use...
Using Enthought
I need to calculate the inverse of the complementary error function (erfc^(1)) for a problem. I was looking into Python tools for it, and many threads said Enthought has most of the math tools needed, so I downloaded and installed it in my local user account. But I am not very sure about how to use it? Any ideas?
[ "SciPy, which is included in the Enthought Python distribution, contains that special function.\nIn [1]: from scipy.special import erfcinv\nIn [2]: from numpy import linspace\nIn [3]: x = linspace(0, 1, 10)\nIn [4]: y = erfcinv(x)\nIn [5]: y\nOut[5]: \narray([ 1.27116101e+308, 1.12657583e+000, 8.63123068e-001,...
[ 8, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0001202967_python_scipy.txt
Q: Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that ...
Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value
Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20. One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the ...
[ "I suggest that you spend a little bit of time writing up a Monte Carlo simulation and let it run while you work out the math by hand. Hopefully the Monte Carlo simulation will converge before you're finished with the math and you'll be able to check your solution.\nA slightly faster option might involve creating ...
[ 5, 3, 2, 2, 1, 1, 1 ]
[]
[]
[ "combinatorics", "dice", "discrete_mathematics", "puzzle", "python" ]
stackoverflow_0001202343_combinatorics_dice_discrete_mathematics_puzzle_python.txt
Q: Java Wrapper to Perl/Python code I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in...
Java Wrapper to Perl/Python code
I have to deploy some Web Services on a server that only supports the Java ones, but some of them will be done using perl or python. I want to know if is possible to develop a Java wrapper to call a specific code written in perl or python. So, I want to have all the Web Services in Java, but some of them will call some...
[ "This depends heavily upon your needs. If Jython is an option for the Python code (it isn't always 100% compatible), then it is probably the best option there. Otherwise, you will need to use Java's Process Builder to call the interpretters directly and return the results on their output stream. This will not be...
[ 4, 3, 3, 1, 0 ]
[]
[]
[ "java", "perl", "python", "web_services", "wrapper" ]
stackoverflow_0001201628_java_perl_python_web_services_wrapper.txt
Q: wxPython: Handling events in a widget that is inside a notebook I have a wxPython notebook, in this case a wx.aui.AuiNotebook. (but this problem has happened with other kinds of notebooks as well.) In my notebook I have a widget, in this case a subclass of ScrolledPanel, for which I am trying to do some custom eve...
wxPython: Handling events in a widget that is inside a notebook
I have a wxPython notebook, in this case a wx.aui.AuiNotebook. (but this problem has happened with other kinds of notebooks as well.) In my notebook I have a widget, in this case a subclass of ScrolledPanel, for which I am trying to do some custom event handling (for wx.EVT_KEY_DOWN). However, the events are not being ...
[ "I tried reproducing your problem but it worked fine for me. The only thing I can think of is that there is one of your classes that also binds to wx.EVT_KEY_DOWN and doesn't call wx.Event.Skip() in its callback. That would prevent further handling of the event. If your scrolled panel happens to be downstream of su...
[ 2 ]
[]
[]
[ "event_handling", "python", "user_interface", "wxpython" ]
stackoverflow_0001201979_event_handling_python_user_interface_wxpython.txt
Q: Python: \number Backreference in re.sub I'm trying to use python's re.sub function to replace some text. >>> import re >>> text = "<hi type=\"italic\"> the></hi>" >>> pat_error = re.compile(">(\s*\w*)*>") >>> pat_error.search(text) <_sre.SRE_Match object at 0xb7a3fea0> >>> re.sub(pat_error, ">\1", text) '<hi type=...
Python: \number Backreference in re.sub
I'm trying to use python's re.sub function to replace some text. >>> import re >>> text = "<hi type=\"italic\"> the></hi>" >>> pat_error = re.compile(">(\s*\w*)*>") >>> pat_error.search(text) <_sre.SRE_Match object at 0xb7a3fea0> >>> re.sub(pat_error, ">\1", text) '<hi type="italic">\x01</hi>' Afterwards the value of ...
[ "Two bugs in your code. First, you're not matching (and specifically, capturing) what you think you're matching and capturing -- insert after your call to .search:\n>>> _.groups()\n('',)\n\nThe unconstrained repetition of repetitions (star after a capturing group with nothing but stars) matches once too many -- wit...
[ 10, 0 ]
[]
[]
[ "backreference", "python", "regex" ]
stackoverflow_0001204223_backreference_python_regex.txt
Q: Split a list into parts based on a set of indexes in Python What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below indexes = [5, 12, 17] list = range(20) return something like this part1 = list[:5] part2 = list[5:12] part3 = list[12:17] part4 = list[17:]...
Split a list into parts based on a set of indexes in Python
What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below indexes = [5, 12, 17] list = range(20) return something like this part1 = list[:5] part2 = list[5:12] part3 = list[12:17] part4 = list[17:] If there are no indexes it should return the entire list.
[ "This is the simplest and most pythonic solution I can think of:\ndef partition(alist, indices):\n return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]\n\nif the inputs are very large, then the iterators solution should be more convenient:\nfrom itertools import izip, chain\ndef partition(alist, indi...
[ 57, 13, 8, 6, 3, 0, 0, 0 ]
[ "The plural of index is indices. Going for simplicity/readability.\nindices = [5, 12, 17]\ninput = range(20)\noutput = []\n\nfor i in reversed(indices):\n output.append(input[i:])\n input[i:] = []\noutput.append(input)\n\nwhile len(output):\n print output.pop()\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0001198512_list_python.txt
Q: \r\n vs \n in python eval function Why eval function doesn't work with \r\n but with \n. for example eval("for i in range(5):\r\n print 'hello'") doesn't work eval("for i in range(5):\n print 'hello'") works I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happen...
\r\n vs \n in python eval function
Why eval function doesn't work with \r\n but with \n. for example eval("for i in range(5):\r\n print 'hello'") doesn't work eval("for i in range(5):\n print 'hello'") works I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happens? --Edit-- Oh! sorry , exactly, I meant...
[ "You have a strange definition of \"work\":\n>>> eval(\"for i in range(5):\\n print 'hello'\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<string>\", line 1\n for i in range(5):\n ^\nSyntaxError: invalid syntax\n>>> \n\nI'm not sure why you're using eval -- I susp...
[ 6, 1 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0001204376_eval_python.txt
Q: Why is wxGridSizer much slower to initialize on a wxDialog then on a wxFrame? It seems that this is specific to windows, here is an example that reproduces the effect: import wx def makegrid(window): grid = wx.GridSizer(24, 10, 1, 1) window.SetSizer(grid) for i in xrange(240): cell = wx.Panel(...
Why is wxGridSizer much slower to initialize on a wxDialog then on a wxFrame?
It seems that this is specific to windows, here is an example that reproduces the effect: import wx def makegrid(window): grid = wx.GridSizer(24, 10, 1, 1) window.SetSizer(grid) for i in xrange(240): cell = wx.Panel(window) cell.SetBackgroundColour(wx.Color(i, i, i)) grid.Add(cell,...
[ "I got a reply on the wxPython-users mailing list, the problem can be fixed by calling Layout explicitly before the dialog is shown.\n\nThis is really weird...\nMy guess is that this is due to\n Windows and wxWidgets not dealing very\n well with overlapping siblings, and so\n when the sizer is doing the initial\...
[ 2 ]
[]
[]
[ "python", "windows", "wxpython" ]
stackoverflow_0001198067_python_windows_wxpython.txt
Q: TypeError: can't multiply sequence by non-int of type 'str' >>> Enter muzzle velocity (m/2): 60 Enter angle (degrees): 45 Traceback (most recent call last): File "F:/Python31/Lib/idlelib/test", line 9, in <module> range() File "F:/Python31/Lib/idlelib/test", line 7, in range Distance = float(decimal((...
TypeError: can't multiply sequence by non-int of type 'str'
>>> Enter muzzle velocity (m/2): 60 Enter angle (degrees): 45 Traceback (most recent call last): File "F:/Python31/Lib/idlelib/test", line 9, in <module> range() File "F:/Python31/Lib/idlelib/test", line 7, in range Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2) Typ...
[ "You should convert the data you get from console to integers:\nx = int(x)\ny = int(y)\nDistance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)\n\n", ">>> '60' * '60'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: can't multiply sequence by...
[ 10, 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001204744_python.txt
Q: importing modules with submodules from deep in a library here at office we have a library named after the company name and inside of it sublibraries, per project more or less, and in each sublibrary there might be more modules or libraries. we are using Django and this makes our hierarchy a couple of steps deeper...
importing modules with submodules from deep in a library
here at office we have a library named after the company name and inside of it sublibraries, per project more or less, and in each sublibrary there might be more modules or libraries. we are using Django and this makes our hierarchy a couple of steps deeper... I am a bit perplex about the differences among the followi...
[ "The three examples above are all equivalent in practice. All of them are weird, though. There is no reason to do \nfrom company.productline import specific\n\nand\nimport company.productline.specific.models\n\nYou can (most of the time) just access models by specific.models after the first import.\nIt seems reason...
[ 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001199743_coding_style_python.txt
Q: Scheduling issues in python I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled a...
Scheduling issues in python
I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the a...
[ "Your vendor would be right if yours was pure python code; however, C extensions may release the GIL, and therefore allows for actual multithreading.\nIn particular, time.sleep does release the GIL (you can check it directly from the source code, here - look at floatsleep implementation); so your code should not ha...
[ 3, 2, 0 ]
[]
[]
[ "multithreading", "python", "scheduling" ]
stackoverflow_0001205328_multithreading_python_scheduling.txt
Q: Django - Repeating a form field n times in one form I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possible at all)? e.g. instead of :- Class PaymentsForm(forms.form): invoice = forms.Char...
Django - Repeating a form field n times in one form
I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possible at all)? e.g. instead of :- Class PaymentsForm(forms.form): invoice = forms.CharField(widget=ValueHiddenInput()) total = forms.CharFi...
[ "You can create the repeated fields in the __init__ method of your form:\nclass PaymentsForm(forms.Form):\n invoice = forms.CharField(widget=forms.HiddenInput())\n total = forms.CharField(widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs):\n super(PaymentsForm, self).__init__(*args,...
[ 10, 4 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001205626_django_django_forms_python.txt
Q: How to use Python's Easygui module to pick files and insert filenames into code I'm trying to use Python's easygui module to select a file and then insert it's name into a program I wrote (see code below). So I want to insert filename 1 and 2 where it says insert filename1, etc.. Any help would be greatly appreci...
How to use Python's Easygui module to pick files and insert filenames into code
I'm trying to use Python's easygui module to select a file and then insert it's name into a program I wrote (see code below). So I want to insert filename 1 and 2 where it says insert filename1, etc.. Any help would be greatly appreciated. Thanks! import easygui import csv msg='none' title='select a 90m distance cs...
[ "I'm going to assume you're new to programming. If I misunderstood your question, I apologize.\nIn your code, after the lines:\nfilename1 = easygui.fileopenbox()\nfilename2 = easygui.fileopenbox()\n\nThe selected file names are stored in the variables filename1 and filename2. You can use those variables to open fil...
[ 2 ]
[]
[]
[ "easygui", "file", "python" ]
stackoverflow_0001202902_easygui_file_python.txt
Q: removing extensions in subdirectories I need to remove the extension ".tex": ./1-aoeeu/1.tex ./2-thst/2.tex ./3-oeu/3.tex ./4-uoueou/4.tex ./5-aaa/5.tex ./6-oeua/6.tex ./7-oue/7.tex Please, do it with some tools below: Sed and find Ruby Python My Poor Try: $find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex...
removing extensions in subdirectories
I need to remove the extension ".tex": ./1-aoeeu/1.tex ./2-thst/2.tex ./3-oeu/3.tex ./4-uoueou/4.tex ./5-aaa/5.tex ./6-oeua/6.tex ./7-oue/7.tex Please, do it with some tools below: Sed and find Ruby Python My Poor Try: $find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
[ "A Python script to do the same:\nimport os.path, shutil\n\ndef remove_ext(arg, dirname, fnames):\n argfiles = (os.path.join(dirname, f) for f in fnames if f.endswith(arg))\n for f in argfiles:\n shutil.move(f, f[:-len(arg)])\n\nos.path.walk('/some/path', remove_ext, '.tex')\n\n", "One way, not neces...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "find", "python", "ruby", "sed" ]
stackoverflow_0001204617_find_python_ruby_sed.txt
Q: Is there a Python shortcut for variable checking and assignment? I'm finding myself typing the following a lot (developing for Django, if that's relevant): if testVariable then: myVariable = testVariable else: # something else Alternatively, and more commonly (i.e. building up a parameters list) if 'query' ...
Is there a Python shortcut for variable checking and assignment?
I'm finding myself typing the following a lot (developing for Django, if that's relevant): if testVariable then: myVariable = testVariable else: # something else Alternatively, and more commonly (i.e. building up a parameters list) if 'query' in request.POST.keys() then: myVariable = request.POST['query'] els...
[ "Assuming you want to leave myVariable untouched to its previous value in the \"not exist\" case,\nmyVariable = testVariable or myVariable\n\ndeals with the first case, and\nmyVariable = request.POST.get('query', myVariable)\n\ndeals with the second one. Neither has much to do with \"exist\", though (which is hardl...
[ 25, 7 ]
[]
[]
[ "django", "idioms", "python" ]
stackoverflow_0001207333_django_idioms_python.txt
Q: How do I limit the border size on a matplotlib graph? I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows. Here are the guts of my graphing code: import matplotlib from ...
How do I limit the border size on a matplotlib graph?
I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows. Here are the guts of my graphing code: import matplotlib from pylab import figure fig = figure() ax = fi...
[ "Since it looks like you're just using a single subplot, you may want to skip add_subplot and go straight to add_axes. This will allow you to give the size of the axes (in figure-relative coordinates), so you can make it as large as you want within the figure. In your case, this would mean your code would look so...
[ 7, 5 ]
[]
[]
[ "graph", "matplotlib", "plot", "python" ]
stackoverflow_0001203639_graph_matplotlib_plot_python.txt
Q: Adding a field to a structured numpy array What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done e...
Adding a field to a structured numpy array
What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently?
[ "If you're using numpy 1.3, there's also numpy.lib.recfunctions.append_fields(). \nFor many installations, you'll need to import numpy.lib.recfunctions to access this. import numpy will not allow one to see the numpy.lib.recfunctions\n", "import numpy\n\ndef add_field(a, descr):\n \"\"\"Return a new array that...
[ 20, 8 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001201817_numpy_python.txt
Q: How to change a GtkTreeView style in Python? I have an app written in python that presents some of its data in a tree view. By default, the tree view is a floaty white affair with little floaty triangles to expand the nodes. Is it possible to change this style to be more like a Windows explorer tree view? Specific...
How to change a GtkTreeView style in Python?
I have an app written in python that presents some of its data in a tree view. By default, the tree view is a floaty white affair with little floaty triangles to expand the nodes. Is it possible to change this style to be more like a Windows explorer tree view? Specifically, I'd like to have vertical lines indicating p...
[ "For lines linking the arrows there is a method in gtk.TreeView for that, see http://library.gnome.org/devel/pygtk/stable/class-gtktreeview.html#method-gtktreeview--set-enable-tree-lines\n", "you need to create a custom CellRenderers for this. the below links might help.\nhttp://www.pygtk.org/pygtk2tutorial/ch-Tr...
[ 3, 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0001207250_gtk_gtktreeview_pygtk_python.txt
Q: "Interfaces" in Python: Yea or Nay? So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects....
"Interfaces" in Python: Yea or Nay?
So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to th...
[ "I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class?\nclass Something(object):\n def some_method(self):\n raise NotImplementedError()\n def some_other_method(s...
[ 30, 12, 11, 10, 7, 5, 4, 3, 1, 1, 1 ]
[]
[]
[ "coding_style", "documentation", "interface", "python" ]
stackoverflow_0000552058_coding_style_documentation_interface_python.txt
Q: Can pydoc generate subdirectories? Is there any way to get pydoc's writedocs() function to create subdirectories for packages? For instance, let's say I have the following modules to document: foo.py dir/bar.py dir/__init__.py When I run pydoc.writedocs(), I get the following files: foo.html dir.bar.html I would...
Can pydoc generate subdirectories?
Is there any way to get pydoc's writedocs() function to create subdirectories for packages? For instance, let's say I have the following modules to document: foo.py dir/bar.py dir/__init__.py When I run pydoc.writedocs(), I get the following files: foo.html dir.bar.html I would like to get: foo.html dir/bar.html Is...
[ "pydoc.writedocs just loops calling writedoc, which is documented (and implemented) to \"write a file in the current directory\". The only way out that I can see is by making a modified version and forcing it (i.e., sigh, monkeypatching it) into the module, or monkeypatching some key aspect of it, namely where 'ope...
[ 1 ]
[]
[]
[ "pydoc", "python" ]
stackoverflow_0001208990_pydoc_python.txt
Q: Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr? Today I ran against the fact, that sys.exit() called from a child-thread does not kill the main process. I did not know this before, and this is okay, but I needed long time to realize this. It would have saved much much time, if sys....
Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr?
Today I ran against the fact, that sys.exit() called from a child-thread does not kill the main process. I did not know this before, and this is okay, but I needed long time to realize this. It would have saved much much time, if sys.exit(msg) would have printed msg to stderr. But it did not. It turned out that it wasn...
[ "I agree that the Python docs are incorrect, or maybe more precisely incomplete, regarding sys.exit and SystemExit when called/raised by threads other than the main one; please open a doc issue on the Python online tracker so this can be addressed in a future iteration of the docs (probably a near-future one -- doc...
[ 7, 0 ]
[]
[]
[ "exit", "multithreading", "python", "sys" ]
stackoverflow_0001209155_exit_multithreading_python_sys.txt
Q: Creating dynamic images with WSGI, no files involved I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved". I would like to send the image directly to the us...
Creating dynamic images with WSGI, no files involved
I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved". I would like to send the image directly to the user, without saving it on the file system first. With PHP t...
[ "It is not related to WSGI or php or any other specific web technology. consider\n<img src=\"someScript.php?param1=xyz\">\n\nin general for url someScript.php?param1=xyz server should return data of image type and it would work\nConsider this example:\nfrom wsgiref.simple_server import make_server\n\ndef serveImage...
[ 9, 2, 0, 0 ]
[]
[]
[ "image_processing", "python", "wsgi" ]
stackoverflow_0001001068_image_processing_python_wsgi.txt