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: Code to utilize memory more than 70% Please tell me C++/Java code which utilize memory more than 70% . For Example we have 3 Virtual machine and in memory resources we want to test the memory utilization as per memory resources allocated by user. A: Which memory? On a 64 bit platform, a 64 bit process can use fa...
Code to utilize memory more than 70%
Please tell me C++/Java code which utilize memory more than 70% . For Example we have 3 Virtual machine and in memory resources we want to test the memory utilization as per memory resources allocated by user.
[ "Which memory? On a 64 bit platform, a 64 bit process can use far more than 4GB. You'd be filling swap for hours before you hit those limits.\nIf you want to test \"70% of physical RAM\", you might discover that you cannot allocate 70% of the 32 bits address space. A significant amount is already claimed by the OS....
[ 4, 3, 0 ]
[]
[]
[ "c", "c++", "java", "python" ]
stackoverflow_0000456926_c_c++_java_python.txt
Q: Simulating a 'local static' variable in python Consider the following code: def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } This is the easiest way I can...
Simulating a 'local static' variable in python
Consider the following code: def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } This is the easiest way I can think of for simulating a 'local static' variable i...
[ "Turn it into a callable object (since that's what it really is.)\nclass CalcSomething(object):\n def __init__(self):\n self._cache = {}\n def __call__(self, a):\n if a not in self._cache: \n self._cache[a] = self.reallyCalc(a)\n return self._cache[a]\n def reallyCalc(self, ...
[ 56, 17, 11, 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000460586_python.txt
Q: Python with Netbeans 6.5 Can you give me some links or explain how to configure an existing python project onto Netbeans? I'm trying it these days and it continues to crash also code navigation doesn't work well and I've problems with debugging. Surely these problems are related to my low eperience about python a...
Python with Netbeans 6.5
Can you give me some links or explain how to configure an existing python project onto Netbeans? I'm trying it these days and it continues to crash also code navigation doesn't work well and I've problems with debugging. Surely these problems are related to my low eperience about python and I need support also in triv...
[ "Python support is in beta, and as someone who works with NB for a past 2 years, I can say that even a release versions are buggy and sometimes crashes. Early Ruby support was also very shaky.\n" ]
[ 1 ]
[]
[]
[ "netbeans", "project", "python" ]
stackoverflow_0000462068_netbeans_project_python.txt
Q: Perl or Python script to remove user from group I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existin...
Perl or Python script to remove user from group
I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that ...
[ "I found This for you. It should do what you need. As far as I can tell Perl does not have any built in functions for removing users from a group. It has several for seeing the group id of a user or process.\n", "Web Link: http://www.ibm.com/developerworks/linux/library/l-roadmap4/\nTo add members to the group, ...
[ 2, 2, 1, 1 ]
[]
[]
[ "centos", "perl", "python", "redhat", "sysadmin" ]
stackoverflow_0000128933_centos_perl_python_redhat_sysadmin.txt
Q: UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2 With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in rang...
UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2
With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in range(128) Below is the code I am currently running: import urllib2 from...
[ "Here is another idea. Your terminal is not capable of displaying an unicode string from Python. The interpreter tries to convert it to ASCII first. You should encode it explicitly before printing. I don't know the exact semantics of soup.findAll(). But it is probably something like:\nfor t in soup.findAll(\"table...
[ 11 ]
[]
[]
[ "beautifulsoup", "encoding", "python", "screen_scraping" ]
stackoverflow_0000463215_beautifulsoup_encoding_python_screen_scraping.txt
Q: Distributing a stand-alone Python web-based application to non-technical users I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if the...
Distributing a stand-alone Python web-based application to non-technical users
I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if they want more performance or they simply won't have an Internet connection available i...
[ "Using NSIS is great (i use it too) but i would suggest using a \"packager\" like pyinstaller (my personal fav, alternatives bb_freeze, py2exe) to create an exe before the using NSIS\nThe primary benefit you get by doing this is;\nYour download is smaller as you're not bundling the whole Python Standard Lib and ext...
[ 4, 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0000210461_installation_python.txt
Q: Algorithm to generate spanning set Given this input: [1,2,3,4] I'd like to generate the set of spanning sets: [1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] Every set ...
Algorithm to generate spanning set
Given this input: [1,2,3,4] I'd like to generate the set of spanning sets: [1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] Every set has all the elements of the original set...
[ "This should work, though I haven't tested it enough.\ndef spanningsets(items):\n if not items: return\n if len(items) == 1:\n yield [[items[-1]]]\n else:\n for cc in spanningsets(items[:-1]):\n yield cc + [[items[-1]]]\n for i in range(len(cc)):\n yield c...
[ 11, 6, 0, 0 ]
[ "The result sets together with the empty set {} looks like the results of the powerset (or power set), but it is not the same thing.\nI started a post about a similar problem which has a few implementations (although in C#) and geared more for speed than clarity in some cases. The first example should be easy to t...
[ -1 ]
[ "algorithm", "python" ]
stackoverflow_0000460479_algorithm_python.txt
Q: Python Psycopg error and connection handling (v MySQLdb) Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2: results = {'felicitas': 3, 'volumes': 8,...
Python Psycopg error and connection handling (v MySQLdb)
Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2: results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative...
[ "I think your code looks like this at the moment:\nl = \"a very long ... text\".split()\nfor e in l:\n cursor.execute(\"INSERT INTO yourtable (yourcol) VALUES ('\" + e + \"')\")\n\nSo try to change it into something like this:\nl = \"a very long ... text\".split()\nfor e in l:\n cursor.execute(\"INSERT INTO y...
[ 2, 2 ]
[]
[]
[ "mysql", "psycopg2", "python" ]
stackoverflow_0000070681_mysql_psycopg2_python.txt
Q: Python - Doing absolute imports from a subfolder Basically I'm asking the same question as this guy: How to do relative imports in Python? But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does no...
Python - Doing absolute imports from a subfolder
Basically I'm asking the same question as this guy: How to do relative imports in Python? But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their...
[ "main.py\nsetup.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n module_a.py\n package_b/ ->\n __init__.py\n module_b.py\n\n\nYou run python main.py.\nmain.py does: import app.package_a.module_a\nmodule_a.py does import app.package_b.module_b\n\nAlternatively 2 or 3 could u...
[ 12, 2, 0 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0000463643_python_python_import.txt
Q: Django missing translation of some strings. Any idea why? I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should. I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file whe...
Django missing translation of some strings. Any idea why?
I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should. I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file when I run make_messages, with the correct file locations marked w...
[ "Ugh. Django, you're killing me.\nHere's what was happening:\nhttp://blog.e-shell.org/124\nFor some reason only Django knows, it decided to decorate some of my translations with the comment '# fuzzy'. It seems to have chosen which ones to mark randomly.\nAnyway, #fuzzy means this: \"don't translate this, even tho...
[ 11, 11 ]
[]
[]
[ "django", "internationalization", "python", "translation" ]
stackoverflow_0000463714_django_internationalization_python_translation.txt
Q: Python - Hits per minute implementation? This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that? I was thinking of may...
Python - Hits per minute implementation?
This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that? I was thinking of maybe summing a dictionary that uses the current ...
[ "A common pattern for solving this in other languages is to let the thing being measured simply increment an integer. Then you leave it to the listening client to determine intervals and frequencies.\nSo you basically do not let the socket server know about stuff like \"minutes\", because that's a feature the obser...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000464314_python.txt
Q: Python regular expressions - how to capture multiple groups from a wildcard expression? I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example: re.search("(\w)*", "abcdefg").groups() this...
Python regular expressions - how to capture multiple groups from a wildcard expression?
I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example: re.search("(\w)*", "abcdefg").groups() this returns the list ('g',) I need it to return ('a','b','c','d','e','f','g',) Is that possible?...
[ "re.findall(r\"\\w\",\"abcdefg\")\n\n", "In addition to Douglas Leeder's solution, here is the explanation:\nIn regular expressions the group count is fixed. Placing a quantifier behind a group does not increase group count (imagine all other group indexes increment because an eralier group matched more than once...
[ 41, 33 ]
[]
[]
[ "lexical_analysis", "python", "regex" ]
stackoverflow_0000464736_lexical_analysis_python_regex.txt
Q: Parsing Functions I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else bloc...
Parsing Functions
I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block.... EDIT This is for ...
[ "Once you get the name of the function, use a dispatch dict to run the function:\ndef mysum(...): ...\ndef myotherstuff(...): ...\n\n# create dispatch dict:\nmyfunctions = {'sum': mysum, 'stuff': myotherstuff}\n\n# run your parser:\nfunction_name, parameters = parse_result(line)\n\n# run the function:\nmyfunctions[...
[ 3, 2, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000464970_parsing_python.txt
Q: How do I take the output of one program and use it as the input of another? I've looked at this and it wasn't much help. I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about...
How do I take the output of one program and use it as the input of another?
I've looked at this and it wasn't much help. I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this? Thanks for your help. EDIT Thanks to the guys that mentioned piping...
[ "p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE, \n stdout=subprocess.PIPE)\nruby_question = p.stdout.readline()\nanswer = calculate_answer(ruby_question)\np.stdin.write(answer)\nprint p.communicate()[0] # prints further info ruby may show.\n\nThe l...
[ 10, 4, 3, 3, 1 ]
[]
[]
[ "io", "python", "ruby" ]
stackoverflow_0000465421_io_python_ruby.txt
Q: Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background) I need to batch create images with text. Requirements: arbitrary size of bitmap PNG format transparent background black text anti-aliased against transparency adjustable character spacing adjustable text position (x and...
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
I need to batch create images with text. Requirements: arbitrary size of bitmap PNG format transparent background black text anti-aliased against transparency adjustable character spacing adjustable text position (x and y coordinates where text begins) TrueType and/or Type1 support Unix command line tool or Python lib...
[ "(5) indeed looks tricky, short of inserting dummy narrow-spaces into the string (which will break kerning) or using something much higher-level like the SVG or HTML/CSS renderer.\nHowever, if you don't mind getting your hands dirty, it looks quite easy to hack PIL's freetype renderer into adding horizontal space. ...
[ 4, 3, 2 ]
[]
[]
[ "bitmap", "fonts", "python", "spacing", "unix" ]
stackoverflow_0000465144_bitmap_fonts_python_spacing_unix.txt
Q: Writing unit tests in Django / Python I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how. I'm writing a Django application, and so far...
Writing unit tests in Django / Python
I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how. I'm writing a Django application, and so far have only created the models (and customis...
[ "Is a function to test each model within the ModelTests class a good way of writing tests?\nNo.\nWhat exactly should I be testing for?\n\nThat creating a model with all of the fields completed works? \nThat a half complete model fails? \nThat any special cases are tested (like a null and is_required=False)? \nI've ...
[ 37, 10, 4 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0000465065_django_python_unit_testing.txt
Q: Delphi-like GUI designer for Python Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc. A: I recommend PyQt (now from Nokia), which uses Qt Designer. Qt designer produces XML files (.ui) which you can either convert to P...
Delphi-like GUI designer for Python
Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc.
[ "I recommend PyQt (now from Nokia), which uses Qt Designer. Qt designer produces XML files (.ui) which you can either convert to Python modules using a utility called pyuic, or load dynamically from your Python program.\nYou do have to write your Python code in a different editor, i.e. Designer is only the GUI desi...
[ 7, 2, 2 ]
[]
[]
[ "form_designer", "python", "user_interface" ]
stackoverflow_0000465814_form_designer_python_user_interface.txt
Q: Possible to integrate Google AppEngine and Google Code for continuous integration? Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code? I have a simple Google AppEngine project's source hosted on Google Code and would lov...
Possible to integrate Google AppEngine and Google Code for continuous integration?
Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code? I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit...
[ "Made By Sofa had a blog post about their workflow with Google App Engine. In the second last paragraph they have attached a subversion hook that when when someone commits code it will automatically deploy to Google App Engine. It would take a little bit of tweaking (because it works on the server side not the clie...
[ 5, 5, 2, 1, 1 ]
[]
[]
[ "continuous_integration", "google_app_engine", "google_code", "python", "svn" ]
stackoverflow_0000241007_continuous_integration_google_app_engine_google_code_python_svn.txt
Q: How can I hide the console window in a PyQt app running on Windows? Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently. [Edit] Thanks PEZ for the answer - more details including use of th...
How can I hide the console window in a PyQt app running on Windows?
Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently. [Edit] Thanks PEZ for the answer - more details including use of the .pyw extension in Python Programming on Win32 chapter 20
[ "I think you should be able to run your app with pythonw.exe.\n", "An easy way to do this is to give your script a .pyw extension instead of the usual .py.\nThis has the same effect as PEZ's answer (runs the script using pythonw.exe).\n" ]
[ 26, 17 ]
[]
[]
[ "command_line", "pyqt", "python", "windows" ]
stackoverflow_0000466203_command_line_pyqt_python_windows.txt
Q: How can I set it up so that threads communicate they're complete with their task? Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in Python: from threading import Thread for i in range(0,3): t = Thread(target=myfunction) t.start() # wait until...
How can I set it up so that threads communicate they're complete with their task?
Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in Python: from threading import Thread for i in range(0,3): t = Thread(target=myfunction) t.start() # wait until threads have finished executing print 'complete!'
[ "add the threads to a list and join() them.\nfrom threading import Thread\ntlist = []\nfor i in range(3):\n t = Thread(target=some_function)\n t.start()\n tlist.append(t)\n\n# wait until threads have finished executing\nfor t in tlist:\n t.join()\n\nprint 'complete!'\n\n" ]
[ 6 ]
[ "I have never used python, but I think the concept you are looking for is a \"semaphore\".\nGoogle turned up this:\nhttp://www.python.org/doc/2.5.2/lib/semaphore-objects.html\n" ]
[ -4 ]
[ "multithreading", "python" ]
stackoverflow_0000466525_multithreading_python.txt
Q: How to prevent overwriting an object someone else has modified I would like to find a generic way of preventing to save an object if it is saved after I checked it out. We can assume the object has a timestamp field that contains last modification time. If I had checked out (visited a view using a ModelForm for in...
How to prevent overwriting an object someone else has modified
I would like to find a generic way of preventing to save an object if it is saved after I checked it out. We can assume the object has a timestamp field that contains last modification time. If I had checked out (visited a view using a ModelForm for instance) at t1 and the object is saved again at t2, given t2 > t1 I s...
[ "Overwrite the save method that would first check the last timestamp:\ndef save(self):\n if(self.id):\n foo = Foo.objects.get(pk=self.id)\n if(foo.timestamp > self.timestamp):\n raise Exception, \"trying to save outdated Foo\" \n super(Foo, self).save()\n\n" ]
[ 3 ]
[]
[]
[ "blocking", "django", "django_models", "locking", "python" ]
stackoverflow_0000467134_blocking_django_django_models_locking_python.txt
Q: python: list comprehension tactics I'm looking to take a string and create a list of strings that build up the original string. e.g.: "asdf" => ["a", "as", "asd", "asdf"] I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done? A: One possibility: >>> st...
python: list comprehension tactics
I'm looking to take a string and create a list of strings that build up the original string. e.g.: "asdf" => ["a", "as", "asd", "asdf"] I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?
[ "One possibility:\n>>> st = 'asdf'\n>>> [st[:n+1] for n in range(len(st))]\n['a', 'as', 'asd', 'asdf']\n\n", "If you're going to be looping over the elements of your \"list\", you may be better off using a generator rather than list comprehension:\n>>> text = \"I'm a little teapot.\"\n>>> textgen = (text[:i + 1] ...
[ 19, 17 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0000467094_list_comprehension_python.txt
Q: WX Python and Raw Input on Windows (WM_INPUT) Does anyone know how to use the Raw Input facility on Windows from a WX Python application? What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too. A: Have you tried using cty...
WX Python and Raw Input on Windows (WM_INPUT)
Does anyone know how to use the Raw Input facility on Windows from a WX Python application? What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.
[ "Have you tried using ctypes?\n>>> import ctypes\n>>> ctypes.windll.user32.RegisterRawInputDevices\n<_FuncPtr object at 0x01FCFDC8>\n\nIt would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.\n",...
[ 4, 3 ]
[]
[]
[ "python", "raw_input", "windows", "wxpython" ]
stackoverflow_0000285869_python_raw_input_windows_wxpython.txt
Q: Multiple mouse pointers? Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow. Is this someth...
Multiple mouse pointers?
Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow. Is this something I should try to farm out t...
[ "You could try the Microsoft Windows MultiPoint Software Development Kit 1.1\nor the new\nMicrosoft Windows MultiPoint Software Development Kit 1.5\nand the main Microsoft Multipoint site\n", "Yes. I know of at least one program that does this, KidPad. I think it's written in Java and was developed by Juan Pabl...
[ 8, 5, 2, 1, 1, 1 ]
[]
[]
[ "mouse", "multi_user", "python", "user_interface" ]
stackoverflow_0000237155_mouse_multi_user_python_user_interface.txt
Q: How to integrate the StringTemplate engine into the CherryPy web server I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated. Who has done it? How? EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a t...
How to integrate the StringTemplate engine into the CherryPy web server
I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated. Who has done it? How? EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in M...
[ "Based on the tutorials for both, it looks pretty straightforward:\n\nimport stringtemplate\nimport cherrypy\n\nclass HelloWorld(object):\n def index(self):\n hello = stringtemplate.StringTemplate(\"Hello, $name$\")\n hello[\"name\"] = \"World\"\n return str(hello)\n index.exposed = True\...
[ 4, 0 ]
[]
[]
[ "cherrypy", "python", "stringtemplate" ]
stackoverflow_0000379338_cherrypy_python_stringtemplate.txt
Q: Python piping on Windows: Why does this not work? I'm trying something like this Output.py print "Hello" Input.py greeting = raw_input("Give me the greeting. ") print "The greeting is:", greeting At the cmd line Output.py | Input.py But it returns an EOFError. Can someone tell me what I am doing wrong? Thanks ...
Python piping on Windows: Why does this not work?
I'm trying something like this Output.py print "Hello" Input.py greeting = raw_input("Give me the greeting. ") print "The greeting is:", greeting At the cmd line Output.py | Input.py But it returns an EOFError. Can someone tell me what I am doing wrong? Thanks for your help. EDIT Patrick Harrington solution works ...
[ "I tested this on my Windows machine and it works if you specify the Python exe: \nC:\\>C:\\Python25\\python.exe output.py | C:\\Python25\\python.exe input.py\nGive me the greeting. The greeting is: hello\n\nBut I get an EOFError also if running the commands directly as: \noutput.py | input.py \n\nI'm not sure exac...
[ 23, 4, 0 ]
[]
[]
[ "piping", "python", "windows" ]
stackoverflow_0000466801_piping_python_windows.txt
Q: Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? In Python compiled regex patterns have a findall method that does the following: Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are retu...
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?
In Python compiled regex patterns have a findall method that does the following: Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list o...
[ "Use the /g modifier in your match. From the perlop manual:\n\nThe \"/g\" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in t...
[ 13, 8, 2 ]
[]
[]
[ "iterator", "perl", "python", "regex" ]
stackoverflow_0000467800_iterator_perl_python_regex.txt
Q: Permutations in python, with a twist I have a list of objects (for the sake of example, let's say 5). I want a list of some of the possible permutations. Specifically, given that some pairs are not together, and some triples don't make sandwiches, how can I generate all other permutations? I realize that I gene...
Permutations in python, with a twist
I have a list of objects (for the sake of example, let's say 5). I want a list of some of the possible permutations. Specifically, given that some pairs are not together, and some triples don't make sandwiches, how can I generate all other permutations? I realize that I generate all of them first and check that they...
[ "You would have to find an algorithm that cuts off more than one unwanted permutation after a single check, in order to gain anything. The obvious strategy is to build the permutations sequentially, for example, in a tree. Each cut then eliminates a whole branch.\nedit:\nExample: in the set (A B C D), let's say t...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000467878_python.txt
Q: Sample a running Python app I'm used to sampling C-based apps, which every few milliseconds sees what function stack is being called at that moment. This allows me to see where most of the time is spent in an app so I can optimize it. When using python, however, sample isn't so helpful, since it's sampling the C f...
Sample a running Python app
I'm used to sampling C-based apps, which every few milliseconds sees what function stack is being called at that moment. This allows me to see where most of the time is spent in an app so I can optimize it. When using python, however, sample isn't so helpful, since it's sampling the C functions of the python interprete...
[ "Python includes a built-in set of profiling tools. In particular, you can run cProfile on an arbitrary python script from the command-line:\n$ python -m cProfile myscript.py\n\nMuch more elaborate usage is available by calling the API directly. Note that the cProfile module was added in Python 2.5. In earlier vers...
[ 4 ]
[]
[]
[ "performance", "python", "sample" ]
stackoverflow_0000467925_performance_python_sample.txt
Q: Python: convert alphabetically spelled out numbers to numerics? I'm looking for a library, service, or code suggestions to turn spelled out numbers and amounts (eg. "thirty five dollars and fifteen cents", "one point five") into numerics ($35.15, 1.5) . Suggestions? A: I wrote some code to do this for integers a...
Python: convert alphabetically spelled out numbers to numerics?
I'm looking for a library, service, or code suggestions to turn spelled out numbers and amounts (eg. "thirty five dollars and fifteen cents", "one point five") into numerics ($35.15, 1.5) . Suggestions?
[ "I wrote some code to do this for integers a while ago: http://github.com/ghewgill/text2num\nFeel free to fork and hack.\n" ]
[ 5 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000468241_parsing_python.txt
Q: Python code for sorting files into folders Python 2.5.1 http://www.cgsecurity.org/wiki/After_Using_PhotoRec I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks : [EDIT2: Two points: This question was vo...
Python code for sorting files into folders
Python 2.5.1 http://www.cgsecurity.org/wiki/After_Using_PhotoRec I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks : [EDIT2: Two points: This question was voted down because it was a 'usage' of code, someh...
[ "It simply means that the program is expecting two command line arguments: source and destination. If you wish to use the same code in another function, replace sys.argv[1] and [2] with your own variables.\n", "Or you can modify the original script and add\nif len(sys.argv) != 3:\n print \"Require 2 arguments:...
[ 2, 2, 0 ]
[]
[]
[ "python", "recovery", "scripting" ]
stackoverflow_0000468383_python_recovery_scripting.txt
Q: Tracking file load progress in Python A lot of modules I use import entire files into memory or trickle a file's contents in while they process it. I'm wondering if there's any way to track this sort of loading progress? Possibly a wrapper class that takes a callback? A: I would do by this by determining the s...
Tracking file load progress in Python
A lot of modules I use import entire files into memory or trickle a file's contents in while they process it. I'm wondering if there's any way to track this sort of loading progress? Possibly a wrapper class that takes a callback?
[ "I would do by this by determining the size of the file, and then simply dividing the total by the number of bytes read. Like this:\nimport os\n\ndef show_progress(file_name, chunk_size=1024):\n fh = open(file_name, \"r\")\n total_size = os.path.getsize(file_name)\n total_read = 0\n while True:\n ...
[ 7, 3 ]
[]
[]
[ "file", "load", "progress", "python" ]
stackoverflow_0000468238_file_load_progress_python.txt
Q: What is the best approach to implement configuration app with Django? I need to program kind of configuration registry for Django-based application. Requirements: Most likely param_name : param_value structure Editable via admin interface Has to work with syncdb. How to deal with a situation in which other apps ...
What is the best approach to implement configuration app with Django?
I need to program kind of configuration registry for Django-based application. Requirements: Most likely param_name : param_value structure Editable via admin interface Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized...
[ "I have found djblets.siteconfig very useful. Works great with the Admin app, and very easy to use. Highly recommended.\n", "Once a while (year ago) I used dbsettings to have some sort of business configuration accessible via admin interface, but I cann't say how it fits today.\n", "I think you'll have trouble ...
[ 5, 1, 0 ]
[]
[]
[ "configuration", "django", "django_admin", "django_models", "python" ]
stackoverflow_0000442355_configuration_django_django_admin_django_models_python.txt
Q: Templates within templates. How to avoid rendering twice? I've got a CMS that takes some dynamic content and renders it using a standard template. However I am now using template tags in the dynamic content itself so I have to do a render_to_string and then pass the results of that as a context variable to render_...
Templates within templates. How to avoid rendering twice?
I've got a CMS that takes some dynamic content and renders it using a standard template. However I am now using template tags in the dynamic content itself so I have to do a render_to_string and then pass the results of that as a context variable to render_to_response. This seems wasteful. What's a better way to do thi...
[ "\"This seems wasteful\" Why does it seem that way?\nEvery template is a mix of tags and text. In your case some block of text has already been visited by a template engine. So what? Once it's been transformed it's just text and passes through the next template engine very, very quickly.\nDo you have specific p...
[ 2, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000468736_django_django_templates_python.txt
Q: problem using an instance in a with_statement I've recently started to learn python , and I reached the with statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code : from __future__ import with_statement import pdb class Geo: def __init__(self,text): ...
problem using an instance in a with_statement
I've recently started to learn python , and I reached the with statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code : from __future__ import with_statement import pdb class Geo: def __init__(self,text): self.text = text def __enter__(self): pr...
[ "Your __enter__ method needs to return the object that should be used for the \"as g\" part of the with statement. See the documentation, where it states:\n\nIf a target was included in the with statement, the return value from __enter__() is assigned to it.\n\nCurrently, it has no return statement, so g gets boun...
[ 12 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0000469950_python_with_statement.txt
Q: Why does 1+++2 = 3? How does Python evaluate the expression 1+++2? How many ever + I put in between, it is printing 3 as the answer. Please can anyone explain this behavior And for 1--2 it is printing 3 and for 1---2 it is printing -1 A: Your expression is the same as: 1+(+(+2)) Any numeric expression can be pr...
Why does 1+++2 = 3?
How does Python evaluate the expression 1+++2? How many ever + I put in between, it is printing 3 as the answer. Please can anyone explain this behavior And for 1--2 it is printing 3 and for 1---2 it is printing -1
[ "Your expression is the same as:\n1+(+(+2))\n\nAny numeric expression can be preceded by - to make it negative, or + to do nothing (the option is present for symmetry). With negative signs:\n1-(-(2)) = 1-(-2)\n = 1+2\n = 3\n\nand\n1-(-(-2)) = 1-(2)\n = -1\n\nI see you clarified your questio...
[ 63, 15, 4, 4, 1, 1 ]
[]
[]
[ "evaluation", "operator_precedence", "python" ]
stackoverflow_0000470139_evaluation_operator_precedence_python.txt
Q: In Django how do i return the total number of items that are related to a model? In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question. This is ea...
In Django how do i return the total number of items that are related to a model?
In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question. This is easy if i get the questionid, i can return all answers related to that question but whe...
[ "QuerySet.count()\nSee also an example how to build QuerySets of related models.\n", "If you're willing to use trunk, you can take advantage of the brand new annotate() QuerySet method added just a week or so ago, which solves this exact problem:\nhttp://docs.djangoproject.com/en/dev/topics/db/aggregation/\nIf yo...
[ 5, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000469110_django_python.txt
Q: How do I get PIL to work when built on mingw/cygwin? I'm trying to build PIL 1.1.6 against cygwin or mingw whilst running against a windows install of python. When I do either the build works but I get the following failure when trying to save files. $ python25 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MS...
How do I get PIL to work when built on mingw/cygwin?
I'm trying to build PIL 1.1.6 against cygwin or mingw whilst running against a windows install of python. When I do either the build works but I get the following failure when trying to save files. $ python25 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright"...
[ "As far as I can tell from some cursory Google searching, you need to rebase the DLLs after building PIL in order for it to work properly on Cygwin.\nReferences: \n\nhttp://jetfar.com/cygwin-install-python-imaging-library/\nhttp://www.cygwin.com/ml/cygwin/2003-06/msg01121.html\n\n" ]
[ 1 ]
[]
[]
[ "cygwin", "python", "python_imaging_library", "windows" ]
stackoverflow_0000380731_cygwin_python_python_imaging_library_windows.txt
Q: Pros and cons of IronPython and IronPython Studio We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we ...
Pros and cons of IronPython and IronPython Studio
We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it...
[ "My company, Resolver Systems, develops what is probably the biggest application written in IronPython yet. (It's called Resolver One, and it's a Pythonic spreadsheet). We are also hosting the Ironclad project (to run CPython extensions under IronPython) and that is going well (we plan to release a beta of Resolver...
[ 18, 9, 7 ]
[]
[]
[ "ironpython", "ironpython_studio", "python" ]
stackoverflow_0000471712_ironpython_ironpython_studio_python.txt
Q: Incorrect answer in dll import in Python In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if succ...
Incorrect answer in dll import in Python
In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success message....
[ "Python strings are immutable. There is no way the string can be changed inside the function.\nSo what you really want is to pass a char buffer of some sort. You can create those in python using the ctypes module. \nPlease edit the question and paste a minimal snippet of the code so we can test and give more inform...
[ 3, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0000472170_import_python.txt
Q: TypeError: 'tuple' object is not callable I was doing the tutorial from the book teach yourself django in 24 hours and in part1 hour 4 i got stuck on this error. Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 278, in run self.result = applicat...
TypeError: 'tuple' object is not callable
I was doing the tutorial from the book teach yourself django in 24 hours and in part1 hour 4 i got stuck on this error. Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 278, in run self.result = application(self.environ, self.start_response) File ...
[ "You somehow set some function to a tuple. Please edit the question and paste your urls.py code, so we can point you to the error.\nI can try a wild guess:\nFile \"c:\\projects\\iFriends\\..\\iFriends\\urls.py\", line 17, in <module>\n (r'^admin/', include('django.contribute.admin.urls'))\n\nThis somehow tells me...
[ 21 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000472503_django_python.txt
Q: Customizing an Admin form in Django while also using autodiscover I want to modify a few tiny details of Django's built-in django.contrib.auth module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify auth any more than necessa...
Customizing an Admin form in Django while also using autodiscover
I want to modify a few tiny details of Django's built-in django.contrib.auth module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify auth any more than necessary -- a simple form change seems to be all that's needed.) When I use a...
[ "None of the above. Just use admin.site.unregister(). Here's how I recently added filtering Users on is_active in the admin (n.b. is_active filtering is now on the User model by default in Django core; still works here as an example), all DRY as can be:\nfrom django.contrib import admin\nfrom django.contrib.auth....
[ 53, 2 ]
[]
[]
[ "customization", "django", "django_admin", "forms", "python" ]
stackoverflow_0000471550_customization_django_django_admin_forms_python.txt
Q: How to specify uniqueness for a tuple of field in a Django model Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field? Or do I need to check this constraint in the clean() method? A: There is...
How to specify uniqueness for a tuple of field in a Django model
Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field? Or do I need to check this constraint in the clean() method?
[ "There is a META option called unique_together. For example:\nclass MyModel(models.Model):\n field1 = models.BlahField()\n field2 = models.FooField()\n field3 = models.BazField()\n\n class Meta:\n unique_together = (\"field1\", \"field2\")\n\nMore info on the Django documentation page.\n" ]
[ 42 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000472392_django_django_models_python.txt
Q: reading/writing xmp metadatas on pdf files through pypdf I can read xmp metadatas through pyPdf with this code: a = pyPdf.PdfFileReader(open(self.fileName)) b = a.getXmpMetadata() c = b.pdf_keywords but: is this the best way? And if I don't use the pdf_keywords property? And is there any w...
reading/writing xmp metadatas on pdf files through pypdf
I can read xmp metadatas through pyPdf with this code: a = pyPdf.PdfFileReader(open(self.fileName)) b = a.getXmpMetadata() c = b.pdf_keywords but: is this the best way? And if I don't use the pdf_keywords property? And is there any way to set these metadatas with pyPdf?
[ "As far as I can see, this is the best way to do so - and there is no way to change the metadata with pyPDF.\n" ]
[ 3 ]
[]
[]
[ "metadata", "pdf", "pypdf", "python", "xmp" ]
stackoverflow_0000466692_metadata_pdf_pypdf_python_xmp.txt
Q: Subtract from an input appended list with a running balance output Noob I am trying to write a script that gives a running balance. I am messing up on the elementary declared functions of python. I need it too: accept a balance via input append a list of transactions take those out one by one in the order they ...
Subtract from an input appended list with a running balance output
Noob I am trying to write a script that gives a running balance. I am messing up on the elementary declared functions of python. I need it too: accept a balance via input append a list of transactions take those out one by one in the order they were input print a running total use pyhtmltable to make the output i...
[ "Something like that?\n# transaction posting on available balance\nimport PyHtmlTable \n\nposting_trans = [] #creating a list of posting debits here\n\n#getting the starting balance\nprint 'What is the balance available to pay transactions? '\navail_bal = float(raw_input('Value: ')) \n\nwhile True: #building up th...
[ 2 ]
[]
[]
[ "loops", "python", "running_balance" ]
stackoverflow_0000472839_loops_python_running_balance.txt
Q: file upload status information Im making a small python script to upload files on the net. The script is working correctly, and now I want to add a simple progress bar that indicates the amount of uploading left. my question is -how do I get the upload status information from the server where im uploading the fil...
file upload status information
Im making a small python script to upload files on the net. The script is working correctly, and now I want to add a simple progress bar that indicates the amount of uploading left. my question is -how do I get the upload status information from the server where im uploading the file, assuming it is possible...I am us...
[ "Check out the documentation here: http://pycurl.sourceforge.net/doc/callbacks.html for callbacks. Best of luck!\n" ]
[ 2 ]
[]
[]
[ "curl", "python", "upload" ]
stackoverflow_0000473937_curl_python_upload.txt
Q: Best way to create a "runner" script in Python? I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of ...
Best way to create a "runner" script in Python?
I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them. I don't know how many modules are there, but I ...
[ "You could use __import__() to load each module, use dir() to find all objects in each module, find all objects which are classes, instantiate them, and run the go() method:\nimport types\nfor module_name in list_of_modules_to_load:\n module = __import__(module_name)\n for name in dir(module):\n object...
[ 4, 3, 1, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0000473961_metaprogramming_python.txt
Q: Getting attributes of a Python package that I don't have the name of, until runtime In a Python package, I have a string containing (presumably) the name of a subpackage. From that subpackage, I want to retrieve a tuple of constants...I'm really not even sure how to proceed in doing this, though. #!/usr/bin/pytho...
Getting attributes of a Python package that I don't have the name of, until runtime
In a Python package, I have a string containing (presumably) the name of a subpackage. From that subpackage, I want to retrieve a tuple of constants...I'm really not even sure how to proceed in doing this, though. #!/usr/bin/python "" The Alpha Package Implements functionality of a base package under the 'alpha' names...
[ "If I correctly understand what you want, I think something roughly like this should work:\ndef get_params(packagename):\n module = __import__('alpha.%s' % packagename)\n return module.__dict__['REQUIRED_PARAMS']\n\n" ]
[ 5 ]
[]
[]
[ "package", "python" ]
stackoverflow_0000474331_package_python.txt
Q: Python: Use the codecs module or use string function decode? I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided u...
Python: Use the codecs module or use string function decode?
I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided up as a csv, so could the csv module also be a valid solution? Than...
[ "Do you mean that your file is encoded in UTF-8? (\"Unicode\" is not an encoding... Required reading: http://www.joelonsoftware.com/articles/Unicode.html) I'm not 100% sure but I think you should be able to read a UTF-8 encoded file with the csv module, and you can convert the strings which contain special characte...
[ 5 ]
[]
[]
[ "codec", "csv", "decode", "python", "unicode" ]
stackoverflow_0000474373_codec_csv_decode_python_unicode.txt
Q: Non-ascii string in verbose_name argument when declaring DB field in Django I declare this: #This file is using encoding:utf-8 ... class Buddy(models.Model): name=models.CharField('ФИО',max_length=200) ... ... in models.py. manage.py syncdb works smoothly. However when I go to admin interface and try to a...
Non-ascii string in verbose_name argument when declaring DB field in Django
I declare this: #This file is using encoding:utf-8 ... class Buddy(models.Model): name=models.CharField('ФИО',max_length=200) ... ... in models.py. manage.py syncdb works smoothly. However when I go to admin interface and try to add a new Buddy I catch a DjangoUnicodeDecodeError, which says: "'utf8' codec can'...
[ "First, I would explicitly define your description as a Unicode string:\nclass Buddy(models.Model):\n name=models.CharField(u'ФИО',max_len)\n\nNote the 'u' in u'ФИО'.\nSecondly, do you have a __unicode__() function defined on your model? If so, make sure that it returns a Unicode string. It's very likely you'r...
[ 5 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0000475073_django_python_unicode.txt
Q: How do I construct the packets for this UDP protocol? Valve Software's Steam Server Query protocol as documented here allows you to query their game servers for various data. This is a little out of my depth and I'm looking for a little guidance as to what I need to learn. I'm assuming I'll need socket and struct...
How do I construct the packets for this UDP protocol?
Valve Software's Steam Server Query protocol as documented here allows you to query their game servers for various data. This is a little out of my depth and I'm looking for a little guidance as to what I need to learn. I'm assuming I'll need socket and struct, correct? I'm comfortable with basic UDP tasks like these,...
[ "I found an answer to my own question. Yay.\nSRCDS.py has this implemented already and I figured it out by looking it over.\n" ]
[ 1 ]
[]
[]
[ "network_programming", "network_protocols", "python" ]
stackoverflow_0000474934_network_programming_network_protocols_python.txt
Q: A QuerySet by aggregate field value Let's say I have the following model: class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest...
A QuerySet by aggregate field value
Let's say I have the following model: class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( User ) ...
[ "Oh, of course I forget about new aggregation support in Django and its annotate functionality.\nSo query may look like this:\nContest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )\n\n", "You can write your own sort in Python very simply.\ndef getScore( anObject ):\n retur...
[ 47, 9, 2 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0000476017_database_django_python.txt
Q: python IPC (Inter Process Communication) for Vista UAC (User Access Control) I am writing a Filemanager in (wx)python - a lot already works. When copying files there is already a progress dialog, overwrite handling etc. Now in Vista when the user wants to copy a file to certain directories (eg %Program Files%) the...
python IPC (Inter Process Communication) for Vista UAC (User Access Control)
I am writing a Filemanager in (wx)python - a lot already works. When copying files there is already a progress dialog, overwrite handling etc. Now in Vista when the user wants to copy a file to certain directories (eg %Program Files%) the application/script needs elevation, which cannot be asked for at runtime. So i ha...
[ "How about just communicating with the second process using stdin/stdout?\nThere are some caveats due to input and output buffering, but take a look at this Python Cookbook recipe, and also Pexpect, for ideas on how to do this. \n" ]
[ 2 ]
[]
[]
[ "ipc", "python", "vista_security", "windows_vista", "wxpython" ]
stackoverflow_0000475928_ipc_python_vista_security_windows_vista_wxpython.txt
Q: PostgreSQL procedural languages: to choose? I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done pr...
PostgreSQL procedural languages: to choose?
I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manually...
[ "Since you already known python, PL/Python should be something to look at. And you sound like you write SQL for your database queries, so PL/SQL is a natural extension of that.\nPL/SQL feels like SQL, just with all the stuff that you would expect from SQL anyway, like variables for whole rows and the usual control ...
[ 6, 2, 1 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0000475302_postgresql_python.txt
Q: group by in django How can i create simple group by query in trunk version of django? I need something like SELECT name FROM mytable GROUP BY name actually what i want to do is simply get all entries with distinct names. A: If you need all the distinct names, just do this: Foo.objects.values('name').distinct()...
group by in django
How can i create simple group by query in trunk version of django? I need something like SELECT name FROM mytable GROUP BY name actually what i want to do is simply get all entries with distinct names.
[ "If you need all the distinct names, just do this:\nFoo.objects.values('name').distinct()\n\nAnd you'll get a list of dictionaries, each one with a name key. If you need other data, just add more attribute names as parameters to the .values() call. Of course, if you add in attributes that may vary between rows wi...
[ 12, 3, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000475552_django_django_models_python.txt
Q: Queryset API distinct() does not work? class Message(models.Model): subject = models.CharField(max_length=100) pub_date = models.DateTimeField(default=datetime.now()) class Topic(models.Model): title = models.CharField(max_length=100) message = models.ManyToManyField(Message, verbose_name='Discuss...
Queryset API distinct() does not work?
class Message(models.Model): subject = models.CharField(max_length=100) pub_date = models.DateTimeField(default=datetime.now()) class Topic(models.Model): title = models.CharField(max_length=100) message = models.ManyToManyField(Message, verbose_name='Discussion') I want to get order all the topics a...
[ "You don't need distinct() here, what you need is aggregation. This query will do what you want:\nfrom django.db.models import Max\nTopic.objects.annotate(Max('message__pub_date')).order_by('-message__pub_date__max')\n\nThough if this is production code, you'll probably want to follow akaihola's advice and denorma...
[ 7, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000453477_django_python.txt
Q: Trimming Mako output I really like the Mako templating system that's used in Pylons and a couple other Python frameworks, and my only complaint is how much WS leaks through even a simple inheritance scheme. Is there anyway to accomplish below, without creating such huge WS gaps... or packing my code in like I star...
Trimming Mako output
I really like the Mako templating system that's used in Pylons and a couple other Python frameworks, and my only complaint is how much WS leaks through even a simple inheritance scheme. Is there anyway to accomplish below, without creating such huge WS gaps... or packing my code in like I started to do with base.mako? ...
[ "Found my own answer\nhttp://docs.makotemplates.org/en/latest/filtering.html\nIt still required some trial and error, but using\nt = TemplateLookup(directories=['/tmp'], default_filters=['trim'])\n\ndramatically cut down on whitespace bleed. Additional savings can be found by checking the compiled template's and l...
[ 2 ]
[]
[]
[ "layout", "mako", "python", "template_engine" ]
stackoverflow_0000476324_layout_mako_python_template_engine.txt
Q: Python Regular Expression to add links to urls I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (http://example.com) and spoken about on coding horror at https://blog.codinghorror.com/the-problem-with-urls/ I'm currently using the follow...
Python Regular Expression to add links to urls
I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (http://example.com) and spoken about on coding horror at https://blog.codinghorror.com/the-problem-with-urls/ I'm currently using the following to create HTML A tags in python for links that s...
[ "Problem is, URLs could have parenthesis as part of them... (http://en.wikipedia.org/wiki/Tropical_Storm_Alberto_(2006)) . You can't treat that with regexp alone, since it doesn't have state. You need a parser. So your best chance would be to use a parser, and try to guess the correct close parenthesis. That is err...
[ 4 ]
[]
[]
[ "python", "regex", "url" ]
stackoverflow_0000476478_python_regex_url.txt
Q: Is there a way to install the scipy special module without the rest of scipy? I'm writing some Python numerical code and would like to use some functions from the special module. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on t...
Is there a way to install the scipy special module without the rest of scipy?
I'm writing some Python numerical code and would like to use some functions from the special module. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration. Is there a way to ge...
[ "The scipy subpackages can usually be installed individually. Try cd-ing to the \"special\" directory and running your normal \"python setup.py install\". The name space for importing should now be special and now scipy.special.\n", "I'm not familiar with scipy in particular, but in general, modules for softwar...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "package", "python", "scipy" ]
stackoverflow_0000476369_numpy_package_python_scipy.txt
Q: Generating and submitting a dynamic number of objects in a form with Django I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help. Model: class Customer(Model.models): name = ...
Generating and submitting a dynamic number of objects in a form with Django
I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help. Model: class Customer(Model.models): name = models.CharField(max_length=100) active = models.BooleanField() Form (I know...
[ "Formsets!\nAlso, the equivalent for forms generated directly models are model formsets.\n" ]
[ 8 ]
[]
[]
[ "django", "forms", "html", "python", "web_applications" ]
stackoverflow_0000477183_django_forms_html_python_web_applications.txt
Q: Most suitable language(s) for simulations in modeling? I will participate a modeling competition, which spends three days. I need a language which is fast and designed for modeling, such as to 2D/3D models. I have considered these languages: Python Sage Which languages would you use? A: You should use the lang...
Most suitable language(s) for simulations in modeling?
I will participate a modeling competition, which spends three days. I need a language which is fast and designed for modeling, such as to 2D/3D models. I have considered these languages: Python Sage Which languages would you use?
[ "You should use the language that you know best and that has good-enough tools for the task at hand. Depending on when the competition is you may have no time to learn a new language/environment.\n", "have a look at http://www.processing.org/ -- it is a programming language (similar to java) and IDE especially de...
[ 4, 2 ]
[ "I would use C++, since it spends three days I would have time to write C++ code, and it's a lot faster then python, which would be my choice if it were a one day competition. So I would probably use C++ with OpenGL and SDL for the models. The simulations would I first write in C++, and if I had time at the end I w...
[ -1 ]
[ "python", "sage" ]
stackoverflow_0000477335_python_sage.txt
Q: How to read Unicode input and compare Unicode strings in Python? I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input? Also, I would like to test Unicode strings for equality and it looks like a standard == does not work. A: raw_input() re...
How to read Unicode input and compare Unicode strings in Python?
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input? Also, I would like to test Unicode strings for equality and it looks like a standard == does not work.
[ "raw_input() returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following:\nimport sys, locale\ntext= raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))\n\nwhich should work correctly in most of the cases.\nWe need ...
[ 54, 16, 4, 1 ]
[]
[]
[ "python", "python_2.7", "unicode" ]
stackoverflow_0000477061_python_python_2.7_unicode.txt
Q: How to convert XML to JSON in Python Possible Duplicate: Converting XML to JSON using Python? I am importing an XML feed and trying to convert it to JSON for output. I'm getting this error: TypeError: <xml.dom.minidom.Document instance at 0x72787d8> is not JSON serializable Unfortunately I know next to nothing...
How to convert XML to JSON in Python
Possible Duplicate: Converting XML to JSON using Python? I am importing an XML feed and trying to convert it to JSON for output. I'm getting this error: TypeError: <xml.dom.minidom.Document instance at 0x72787d8> is not JSON serializable Unfortunately I know next to nothing about Python. I'm developing this on the...
[ "\nI'm quickly coming to the opinion that\n Python is potentially a great\n language, but that none of its users\n know how to actually document anything\n in a clear and concise way.\n\nThe attitude of the question isn't going to help with getting answers from these same Python users.\nAs is mentioned in the a...
[ 9 ]
[]
[]
[ "json", "python", "xml" ]
stackoverflow_0000477794_json_python_xml.txt
Q: How to list the files in a static directory? I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use. app.yaml - url: /data static_dir: data Python code to list the files myFiles = [] for root, dirs, files in os.walk(os.path.join(os.pat...
How to list the files in a static directory?
I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use. app.yaml - url: /data static_dir: data Python code to list the files myFiles = [] for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/') ): for name in f...
[ "https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers\nThey're not where you think they are, GAE puts static content into GoogleFS which is equivalent of a CDN. The idea is that static content is meant to be served directly to your users and not act as a file st...
[ 7, 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000477135_google_app_engine_python.txt
Q: Python and os.chroot I'm writing a web-server in Python as a hobby project. The code is targeted at *NIX machines. I'm new to developing on Linux and even newer to Python itself. I am worried about people breaking out of the folder that I'm using to serve up the web-site. The most obvious way to do this is to filt...
Python and os.chroot
I'm writing a web-server in Python as a hobby project. The code is targeted at *NIX machines. I'm new to developing on Linux and even newer to Python itself. I am worried about people breaking out of the folder that I'm using to serve up the web-site. The most obvious way to do this is to filter requests for documents ...
[ "Yes there are pitfalls. Security wise:\n\nIf you run as root, there are always ways to break out. So first chroot(), then PERMANENTLY drop privileges to an other user.\nPut nothing which isn't absolutely required into the chroot tree. Especially no suid/sgid files, named pipes, unix domain sockets and device nodes...
[ 7, 3 ]
[]
[]
[ "chroot", "linux", "python" ]
stackoverflow_0000478359_chroot_linux_python.txt
Q: How do I build and install P4Python for Mac OS X? I've been unable to build P4Python for an Intel Mac OS X 10.5.5. These are my steps: I downloaded p4python.tgz (from http://filehost.perforce.com/perforce/r07.3/tools/) and expanded it into "P4Python-2007.3". I downloaded p4api.tar (from http://filehost.perforce.c...
How do I build and install P4Python for Mac OS X?
I've been unable to build P4Python for an Intel Mac OS X 10.5.5. These are my steps: I downloaded p4python.tgz (from http://filehost.perforce.com/perforce/r07.3/tools/) and expanded it into "P4Python-2007.3". I downloaded p4api.tar (from http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/) and expanded it in...
[ "From http://bugs.mymediasystem.org/?do=details&task_id=676 suggests that Py_ssize_t was added in python 2.5, so it won't work (without some modifications) with python 2.4.\nEither install/compile your own copy of python 2.5/2.6, or work out how to change P4Python, or look for an alternative python-perforce library...
[ 1, 1, 0 ]
[]
[]
[ "macos", "p4python", "perforce", "python" ]
stackoverflow_0000168273_macos_p4python_perforce_python.txt
Q: Need to route instance calls inside a python class The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far. from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwar...
Need to route instance calls inside a python class
The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far. from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a re...
[ "When you do this\nr.doSomething(1)\n\nwhat happens is, in order:\n\nr.__getattr__ is called, and returns an object\nthis object is called with an argument \"1\" \n\nAt the time when __getattr__ is called, you have no way of knowing what arguments the object you return is going to get called with, or even if it's g...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "class", "instance", "python" ]
stackoverflow_0000478655_class_instance_python.txt
Q: is there a string method to capitalize acronyms in python? This is good: import string string.capwords("proper name") Out: 'Proper Name' This is not so good: string.capwords("I.R.S") Out: 'I.r.s' Is there no string method to do capwords so that it accomodates acronyms? A: This might work: import re def _cal...
is there a string method to capitalize acronyms in python?
This is good: import string string.capwords("proper name") Out: 'Proper Name' This is not so good: string.capwords("I.R.S") Out: 'I.r.s' Is there no string method to do capwords so that it accomodates acronyms?
[ "This might work:\nimport re\n\ndef _callback(match):\n \"\"\" This is a simple callback function for the regular expression which is \n in charge of doing the actual capitalization. It is designed to only \n capitalize words which aren't fully uppercased (like acronyms).\n \"\"\"\n word = ma...
[ 8, 2, 1 ]
[ "I just used a list comprehension: [ \".\".join( [ string.capwords(l) for l in entry.split(\".\") ] ) for entry in original_list ]\n" ]
[ -1 ]
[ "acronym", "capitalize", "python", "string" ]
stackoverflow_0000479043_acronym_capitalize_python_string.txt
Q: ISO encoded attachment names and python First of all i don't have the code example on this computer, but i have an example that is quite similar. (http://docs.python.org/library/email-examples.html) The 4th one. My issue lies within this bit of code counter = 1 for part in msg.walk(): # multipart/* are just co...
ISO encoded attachment names and python
First of all i don't have the code example on this computer, but i have an example that is quite similar. (http://docs.python.org/library/email-examples.html) The 4th one. My issue lies within this bit of code counter = 1 for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() =...
[ "I found the issue, it was with \nmimetypes.guess_extension(part.get_content_type())\n\nAnd images with \"image/pjpeg\" as the content type\n@S.Lott i have changed the code to resemble the above example, but i added this to fix the pjpeg issue.\nif not filename:\n ext = mimetypes.guess_extension(part.get_content...
[ 0 ]
[]
[]
[ "attachment", "email", "python" ]
stackoverflow_0000470567_attachment_email_python.txt
Q: All nodeValue fields are None when parsing XML I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line. >>> from xml.dom import minidom >>> import urllib2 >>> url ='http://www.digg.com/rss/index.xml' >>> xmldoc = m...
All nodeValue fields are None when parsing XML
I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line. >>> from xml.dom import minidom >>> import urllib2 >>> url ='http://www.digg.com/rss/index.xml' >>> xmldoc = minidom.parse(urllib2.urlopen(url)) >>> channelnode =...
[ "For RSS feeds you should try the Universal Feed Parser library. It simplifies the handling of RSS feeds immensly.\nimport feedparser\nd = feedparser.parse('http://www.digg.com/rss/index.xml')\ntitle = d.channel.title\n\n", "This is the syntax you are looking for:\n>>> print titlenode[0].firstChild.nodeValue\ndig...
[ 17, 10 ]
[]
[]
[ "minidom", "python", "rss", "xml" ]
stackoverflow_0000479751_minidom_python_rss_xml.txt
Q: The OLE way of doing drag&drop in wxPython I have wxPython app which is running on MS Windows and I'd like it to support drag&drop between its instances (so the user opens my app 3 times and drags data from one instance to another). The simple drag&drop in wxPython works that way: User initiates drag: The source ...
The OLE way of doing drag&drop in wxPython
I have wxPython app which is running on MS Windows and I'd like it to support drag&drop between its instances (so the user opens my app 3 times and drags data from one instance to another). The simple drag&drop in wxPython works that way: User initiates drag: The source window packs necessary data in wx.DataObject(), ...
[ "Since you can't use one of the standard data formats to store references to python objects I would recommend you use a text data format for storing the parameters you need for your method calls rather than making a new data format. And anyway, it would be no good to pass a reference to an object from one app to an...
[ 3, 0 ]
[]
[]
[ "drag_and_drop", "ole", "python", "windows", "wxpython" ]
stackoverflow_0000476142_drag_and_drop_ole_python_windows_wxpython.txt
Q: How can I build a recursive function in python? How can I build a recursive function in python? A: I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function: def factorial(n): if n == 0: return 1 else: return n * factor...
How can I build a recursive function in python?
How can I build a recursive function in python?
[ "I'm wondering whether you meant \"recursive\". Here is a simple example of a recursive function to compute the factorial function:\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nThe two key elements of a recursive algorithm are:\n\nThe termination condition:...
[ 81, 10, 5, 2 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0000479343_python_recursion.txt
Q: Python 2.2: How to get the lower 32 bits out of a 64 bit number? I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn'...
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. big_num = 0xFFFFFFFFFFFFFFFF some_field = (...
[ ">>> big_num = 0xFFFFFFFFFFFFFFFF\n>>> some_field = (big_num & 0x00FFFF0000000000) # works as expected\n>>> field_i_need = big_num & 0x00000000FFFFFFFF # doesn't work\n>>> big_num\n18446744073709551615L\n>>> field_i_need\n4294967295L\n\nIt seems to work, or I am missing the question. I'm using Python 2.6.1, anyway....
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000474949_python.txt
Q: Is there a way in python to apply a list of regex patterns that are stored in a list to a single string? i have a list of regex patterns (stored in a list type) that I would like to apply to a string. Does anyone know a good way to: Apply every regex pattern in the list to the string and Call a different functio...
Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?
i have a list of regex patterns (stored in a list type) that I would like to apply to a string. Does anyone know a good way to: Apply every regex pattern in the list to the string and Call a different function that is associated with that pattern in the list if it matches. I would like to do this in python if possib...
[ "import re\n\ndef func1(s):\n print s, \"is a nice string\"\n\ndef func2(s):\n print s, \"is a bad string\"\n\nfuncs = {\n r\".*pat1.*\": func1,\n r\".*pat2.*\": func2\n}\ns = \"Some string with both pat1 and pat2\"\n\nfor pat, func in funcs.items():\n if re.search(pat, s):\n func(s)\n\nThe ab...
[ 11 ]
[]
[]
[ "list", "python", "regex" ]
stackoverflow_0000481266_list_python_regex.txt
Q: Installing certain packages using virtualenv So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, an...
Installing certain packages using virtualenv
So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this? Well i...
[ "I know where you're coming from with the no-sites-option. I want to use pip freeze to generate requirements lists and don't want a lot of extra cruft in site-packages. I also need to use multiple versions of django as I have legacy projects I haven't upgraded (some old svn checkouts (pre1.0), some 1.0, and some ne...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "buildout", "python", "virtualenv" ]
stackoverflow_0000434407_buildout_python_virtualenv.txt
Q: What does the LDAP response tuple (97, []) mean? I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code: import ldap l = ldap.initialize('LDAP://example.com') m = l.simple_bind_s(username@example.com,password) I get the following back: print m (97, []...
What does the LDAP response tuple (97, []) mean?
I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code: import ldap l = ldap.initialize('LDAP://example.com') m = l.simple_bind_s(username@example.com,password) I get the following back: print m (97, []) What does the 97 and empty list signify coming from...
[ "The first item is a status code (97=success) followed by a list of messages from the server.\nSee here in the section Binding. \n", "According to the documentation, this is:\nLDAP_REFERRAL_LIMIT_EXCEEDED 0x61 The referral limit was exceeded.\n\nProbably\nldap.set_option(ldap.OPT_REFERRALS, 0)\n\ncould hel...
[ 6, 5, 0 ]
[]
[]
[ "active_directory", "ldap", "python" ]
stackoverflow_0000481995_active_directory_ldap_python.txt
Q: Python - what are all the built-in decorators? I know of @staticmethod, @classmethod, and @property, but only through scattered documentation. What are all the function decorators that are built into Python? Is that in the docs? Is there an up-to-date list maintained somewhere? A: I don't think so. Decorators do...
Python - what are all the built-in decorators?
I know of @staticmethod, @classmethod, and @property, but only through scattered documentation. What are all the function decorators that are built into Python? Is that in the docs? Is there an up-to-date list maintained somewhere?
[ "I don't think so. Decorators don't differ from ordinary functions, you only call them in a fancier way. \nFor finding all of them try searching Built-in functions list, because as you can see in Python glossary the decorator syntax is just a syntactic sugar, as the following two definitions create equal functions...
[ 44, 23, 1 ]
[ "There is no such thing as a list of all decorators. There's no list of all functions. There's no list of all classes.\nDecorators are a handy tool for defining a common aspect across functions, methods, or classes. There are the built-in decorators. Plus there are any number of cool and useless decorators. In the ...
[ -4 ]
[ "decorator", "python" ]
stackoverflow_0000480178_decorator_python.txt
Q: Replace Nested For Loops... or not I have a script that loops through a series of four (or less) characters strings. For example: aaaa aaab aaac aaad If have been able to implement it with nested for loops like so: chars = string.digits + string.uppercase + string.lowercase for a in chars: print '%s' % a ...
Replace Nested For Loops... or not
I have a script that loops through a series of four (or less) characters strings. For example: aaaa aaab aaac aaad If have been able to implement it with nested for loops like so: chars = string.digits + string.uppercase + string.lowercase for a in chars: print '%s' % a for b in chars: print '%s%s...
[ "import string\nimport itertools\n\nchars = string.digits + string.letters\nMAX_CHARS = 4\nfor nletters in range(MAX_CHARS):\n for word in itertools.product(chars, repeat=nletters + 1):\n print (''.join(word))\n\nThat'll print all 15018570 words you're looking for. If you want more/less words just change ...
[ 16, 6, 4, 3, 2, 1, 1 ]
[]
[]
[ "for_loop", "loops", "nested_loops", "python" ]
stackoverflow_0000482146_for_loop_loops_nested_loops_python.txt
Q: How to stop a Python script without error messages on the shell? I want to stop a Python script on seeing an error message. I dont want any error message on shell like exit(). How to do it ??? A: When you send CTRL+C to a Python script, it raises the KeyboardInterrupt exception, so you can do something like try:...
How to stop a Python script without error messages on the shell?
I want to stop a Python script on seeing an error message. I dont want any error message on shell like exit(). How to do it ???
[ "When you send CTRL+C to a Python script, it raises the KeyboardInterrupt exception, so you can do something like\ntry:\n ... Work goes here ...\nexcept KeyboardInterrupt:\n sys.exit(0)\n\n" ]
[ 9 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0000483208_error_handling_python.txt
Q: How come my class is behaving like a static class? i have a module (a single .py file, actually), with a class called HashedDir. when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different. Eg: h1 = HashedD...
How come my class is behaving like a static class?
i have a module (a single .py file, actually), with a class called HashedDir. when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different. Eg: h1 = HashedDir('/path/to/dir') print h1.getList()['files'] # /path/...
[ "There are two kinds of variables in a class:\n\nclass variables, defined at the class level, and common to all instances\ninstance variables, defined within a class method (usually __init__) and qualified by the instance (usually self.).\n\nExample\nclass SomeClass( object ):\n classVariable = 0\n def __init...
[ 10, 6, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000483072_python.txt
Q: Performance: Python 3.x vs Python 2.x On a question of just performance, how does Python 3 compare to Python 2.x? A: 3.0 is slower than 2.5 on official benchmarks. From "What’s New in Python 3.0": The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower tha...
Performance: Python 3.x vs Python 2.x
On a question of just performance, how does Python 3 compare to Python 2.x?
[ "3.0 is slower than 2.5 on official benchmarks. From \"What’s New in Python 3.0\":\n\nThe net result of the 3.0\n generalizations is that Python 3.0\n runs the pystone benchmark around 10%\n slower than Python 2.5. Most likely\n the biggest cause is the removal of\n special-casing for small integers.\n There’...
[ 29, 7, 5, 4, 3, 0 ]
[]
[]
[ "performance", "python", "python_2.x", "python_3.x" ]
stackoverflow_0000170426_performance_python_python_2.x_python_3.x.txt
Q: calling methods on an instance with getattr [ python ] I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this . Here is the code I used for the cla...
calling methods on an instance with getattr [ python ]
I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this . Here is the code I used for the class : class X: d...
[ "You need to do something like\nclass X: \n def __init__(self):\n self._value = 90 \n\n def _get(self): \n return self._value\n\n def _set(self, value):\n self._value = value \n\n value = property(_get, _set)\n\nNote that the \"internal\" variable has ...
[ 8, 2 ]
[]
[]
[ "attributes", "dynamic", "properties", "python" ]
stackoverflow_0000484220_attributes_dynamic_properties_python.txt
Q: Problem with encoding in Django templates I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the r...
Problem with encoding in Django templates
I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the rest of application in both the data, templates ...
[ "Sometimes there's nothing like describing a problem to someone else to help you solve it. :) I should have marked the Python strings as Unicode like this and everything works now:\ndef test(request):\n return render_to_response(\"test.html\", {\n \"s1\": u\"dados\",\n ...
[ 8 ]
[]
[]
[ "django", "django_templates", "internationalization", "python", "unicode" ]
stackoverflow_0000484338_django_django_templates_internationalization_python_unicode.txt
Q: Running unexported .dll functions with python This may seem like a weird question, but I would like to know how I can run a function in a .dll from a memory 'signature'. I don't understand much about how it actually works, but I needed it badly. Its a way of running unexported functions from within a .dll, if you ...
Running unexported .dll functions with python
This may seem like a weird question, but I would like to know how I can run a function in a .dll from a memory 'signature'. I don't understand much about how it actually works, but I needed it badly. Its a way of running unexported functions from within a .dll, if you know the memory signature and adress of it. For exa...
[ "If you can already run them using C++ then you can try using SWIG to generate python wrappers for the C++ code you've written making it callable from python.\nhttp://www.swig.org/\nSome caveats that I've found using SWIG:\nSwig looks up types based on a string value. For example\nan integer type in Python (int) w...
[ 2, 0 ]
[]
[]
[ "ctypes", "memory", "python" ]
stackoverflow_0000421223_ctypes_memory_python.txt
Q: Extracting info from large structured text files I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data. No.813829461 16/09/1987 270 Tit.SUZANO PAPEL E CELULOSE S.A. ...
Extracting info from large structured text files
I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data. No.813829461 16/09/1987 270 Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA) C.N.P.J./C.I.C./N INPI : 16404287000155 Pr...
[ "That is pretty good. Below some suggestions, let me know if you like'em:\nimport re\nimport pprint\nimport sys\n\nclass Despacho(object):\n \"\"\"\n Class to parse each line, applying the regexp and storing the results\n for future use\n \"\"\"\n #used a dict with the keys instead of functions.\n ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0000481862_python_text_processing.txt
Q: Parsing fixed-format data embedded in HTML in python I am using google's appengine api from google.appengine.api import urlfetch to fetch a webpage. The result of result = urlfetch.fetch("http://www.example.com/index.html") is a string of the html content (in result.content). The problem is the data that I wan...
Parsing fixed-format data embedded in HTML in python
I am using google's appengine api from google.appengine.api import urlfetch to fetch a webpage. The result of result = urlfetch.fetch("http://www.example.com/index.html") is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think us...
[ "Only suggestion I can think of is to parse it as if it has fixed width columns. Newlines are not taken into consideration for HTML. \nIf you have control of the source data, put it into a text file rather than HTML.\n", "I understand that the format of the document is the one you have posted. In that case, I a...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "html", "html_content_extraction", "parsing", "python" ]
stackoverflow_0000409769_google_app_engine_html_html_content_extraction_parsing_python.txt
Q: How would you determine where each property and method of a Python class is defined? Given an instance of some class in Python, it would be useful to be able to determine which line of source code defined each method and property (e.g. to implement 1). For example, given a module ab.py class A(object): z = 1 ...
How would you determine where each property and method of a Python class is defined?
Given an instance of some class in Python, it would be useful to be able to determine which line of source code defined each method and property (e.g. to implement 1). For example, given a module ab.py class A(object): z = 1 q = 2 def y(self): pass def x(self): pass class B(A): q = 4 def x(self...
[ "You are looking for the undocumented function inspect.classify_class_attrs(cls). Pass it a class and it will return a list of tuples ('name', 'kind' e.g. 'method' or 'data', defining class, property). If you need information on absolutely everything in a specific instance you'll have to do additional work.\nExampl...
[ 3, 2, 1 ]
[]
[]
[ "introspection", "plone", "python", "python_datamodel" ]
stackoverflow_0000484890_introspection_plone_python_python_datamodel.txt
Q: Why aren't all the names in dir(x) valid for attribute access? Why would a coder stuff things into __dict__ that can't be used for attribute access? For example, in my Plone instance, dir(portal) includes index_html, but portal.index_html raises AttributeError. This is also true for the __class__ attribute of Prod...
Why aren't all the names in dir(x) valid for attribute access?
Why would a coder stuff things into __dict__ that can't be used for attribute access? For example, in my Plone instance, dir(portal) includes index_html, but portal.index_html raises AttributeError. This is also true for the __class__ attribute of Products.ZCatalog.Catalog.mybrains. Is there a good reason why dir() can...
[ "I don't know about Plone, so the following is general.\nFrom the docs of dir:\n\nIf the object has a method named\n __dir__(), this method will be called and must return the list of\n attributes. This allows objects that\n implement a custom __getattr__() or\n __getattribute__() function to customize the way d...
[ 2 ]
[]
[]
[ "introspection", "python", "python_datamodel" ]
stackoverflow_0000485095_introspection_python_python_datamodel.txt
Q: Get foreign key without requesting the whole object I have a model Foo which have a ForeignKey to the User model. Later, I need to grab all the User's id and put then on a list foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] But when I do that, django grabs the whole User instance from the DB inst...
Get foreign key without requesting the whole object
I have a model Foo which have a ForeignKey to the User model. Later, I need to grab all the User's id and put then on a list foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist ...
[ "Use queryset's values() function, which will return a list of dictionaries containing name/value pairs for each attribute passed as parameters:\n>>> Foo.objects.all().values('user__id')\n[{'user__id': 1}, {'user__id' 2}, {'user__id': 3}]\n\nThe ORM will then be able to optimize the SQL query to only return the req...
[ 5, 4, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000476731_django_django_models_python.txt
Q: Client Server programming in python? Here is source code for multithreaed server and client in python. In the code client and server closes connection after the job is finished. I want to keep the connections alive and send more data over the same connections to avoid overhead of closing and opening sockets every ...
Client Server programming in python?
Here is source code for multithreaed server and client in python. In the code client and server closes connection after the job is finished. I want to keep the connections alive and send more data over the same connections to avoid overhead of closing and opening sockets every time. Following code is from : http://www....
[ "Spawning a new thread for every connection is a really bad design choice.\nWhat happens if you get hit by a lot of connections?\nIn fact, using threads to wait for network IO is not worth it. Your program gets really complex and you get absolutely no benefit since waiting for network in threads won't make you wait...
[ 20, 3, 0 ]
[]
[]
[ "client", "multithreading", "python", "sockets" ]
stackoverflow_0000487229_client_multithreading_python_sockets.txt
Q: pyqt import problem I am having some trouble doing this in Python: from PyQt4 import QtCore, QtGui from dcopext import DCOPClient, DCOPApp The traceback I get is from dcopext import DCOPClient, DCOPApp File "/usr/lib/python2.5/site-packages/dcopext.py", line 35, in <module> from dcop import DCOPClient Runtime...
pyqt import problem
I am having some trouble doing this in Python: from PyQt4 import QtCore, QtGui from dcopext import DCOPClient, DCOPApp The traceback I get is from dcopext import DCOPClient, DCOPApp File "/usr/lib/python2.5/site-packages/dcopext.py", line 35, in <module> from dcop import DCOPClient RuntimeError: the qt and PyQt4.Q...
[ "The dcopext module is part of PyKDE3, the Python bindings for KDE3 which uses Qt 3.x, while you're using PyQt/Qt 4.x. \nYou need to upgrade to PyKDE4, now released as part of KDE itself, unless you want to target KDE 3 in which case you need a corresponding old version of Qt and PyQt (3.x).\n" ]
[ 1 ]
[]
[]
[ "dcop", "pyqt", "python" ]
stackoverflow_0000487484_dcop_pyqt_python.txt
Q: Transferring object through Pyro I'm using Pyro in a project, and can't seem to understand how to transfer a complete object over the wire. The object is not distributed (my distributed objects works perfectly fine), but should function as an argument to an already available distributed object. My object is a der...
Transferring object through Pyro
I'm using Pyro in a project, and can't seem to understand how to transfer a complete object over the wire. The object is not distributed (my distributed objects works perfectly fine), but should function as an argument to an already available distributed object. My object is a derived from a custom class containing so...
[ "Operations is a class attribute, not the object attribute. That is why it's not transferred. Try setting it in __init__ via self.operations = <whatever>.\n", "Your receiving method, apply, has the same name as the built-in Python function.\n" ]
[ 4, 1 ]
[]
[]
[ "distributed", "python" ]
stackoverflow_0000487553_distributed_python.txt
Q: How can I get interactive Python to avoid using readline while allowing utf-8 input? I use a terminal (9term) that does command-line editing itself - programs that use readline just get in its way. It's fully utf-8 aware. How can I make an interactive python session disable readline while retaining utf-8 input and...
How can I get interactive Python to avoid using readline while allowing utf-8 input?
I use a terminal (9term) that does command-line editing itself - programs that use readline just get in its way. It's fully utf-8 aware. How can I make an interactive python session disable readline while retaining utf-8 input and output? Currently I use: LANG=en_GB.UTF-8 export LANG cat | python -i however this cause...
[ "In the past, I've disabled Python readline by rebuilding it from source: configure --disable-readline\nThis might be overkill, though, for your situation.\n" ]
[ 2 ]
[]
[]
[ "interactive", "python", "utf_8" ]
stackoverflow_0000487800_interactive_python_utf_8.txt
Q: ZipFile complains, is there a way around using the zipfile module? I am trying to decompress some MMS messages sent to me zipped. The problem is that sometimes it works, and others not. And when it doesnt work, the python zipfile module complains and says that it is a bad zip file. But the zipfile decompresses fin...
ZipFile complains, is there a way around using the zipfile module?
I am trying to decompress some MMS messages sent to me zipped. The problem is that sometimes it works, and others not. And when it doesnt work, the python zipfile module complains and says that it is a bad zip file. But the zipfile decompresses fine using the unix unzip command. This is what ive got zippedfile = open('...
[ "You should very probably open the file in binary mode, when writing zipped data into it. That is, you should use\nzippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')\n\n", "You might have to close and reopen the file, or maybe seek to the start of the file after writing it.\nfilename = '%stemp/...
[ 5, 1 ]
[]
[]
[ "popen", "python", "python_zipfile", "zip" ]
stackoverflow_0000488054_popen_python_python_zipfile_zip.txt
Q: How to copy a picture from canvas to clipboard? I have some Tkinter canvas and some picture of lines and text on it. Is there an easy way to copy it to a clipboard? A: You could use .postscript method of the canvas to get an Encapsulated PostScript (EPS) representation of the contents. Then, use `ImageMagick's ...
How to copy a picture from canvas to clipboard?
I have some Tkinter canvas and some picture of lines and text on it. Is there an easy way to copy it to a clipboard?
[ "You could use .postscript method of the canvas to get an Encapsulated PostScript (EPS) representation of the contents. Then, use `ImageMagick's Python bindings (PythonMagick or PythonMagickWand) to convert the EPS to a Windows Enhanced Metafile (EMF). Finally, copy it to the clipboard (e.g. using nosklo's soluti...
[ 5, 4 ]
[]
[]
[ "clipboard", "python", "tkinter" ]
stackoverflow_0000457514_clipboard_python_tkinter.txt
Q: Validating Python Arguments in Subclasses I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this. Here is an example of what I am attempting: class A(object): @accepts(int, int, int) def __init__(a, b, c): pass clas...
Validating Python Arguments in Subclasses
I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this. Here is an example of what I am attempting: class A(object): @accepts(int, int, int) def __init__(a, b, c): pass class B(A): @accepts(int, int, int, int) de...
[ "Why not just define an any value, and decorate the subclass constructor with @accepts(any, any, any, int)? Your decorator won't check parameters marked with any, and the @accepts on the superclass constructor will check all the arguments passed up to it by subclasses.\n", "You might want to play around with the ...
[ 1, 0 ]
[]
[]
[ "decorator", "inheritance", "python", "static_typing" ]
stackoverflow_0000488772_decorator_inheritance_python_static_typing.txt
Q: Why am I getting the following error in Python "ImportError: No module named py"? I'm a Python newbie, so bear with me :) I created a file called test.py with the contents as follows: test.py import sys print sys.platform print 2 ** 100 I then ran import test.py file in the interpreter to follow an example in my ...
Why am I getting the following error in Python "ImportError: No module named py"?
I'm a Python newbie, so bear with me :) I created a file called test.py with the contents as follows: test.py import sys print sys.platform print 2 ** 100 I then ran import test.py file in the interpreter to follow an example in my book. When I do this, I get the output with the import error on the end. win32 12676506...
[ "Instead of:\nimport test.py\n\nsimply write:\nimport test\n\nThis assumes test.py is in the same directory as the file that imports it.\n", "This strange-looking error is a result of how Python imports modules. \nPython sees: \nimport test.py\n\nPython thinks (simplified a bit):\n\nimport module test.\n\nsearch...
[ 44, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000489497_python.txt
Q: Integrating command-line generated python .coverage files with PyDev My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to...
Integrating command-line generated python .coverage files with PyDev
My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the cove...
[ "I don't know anything about PyDev's integration of coverage.py (or if it even uses coverage.py), but the .coverage files are pretty simple. They are marhsal'ed dictionaries.\nI haven't tested this code, but you can try this to combine two .coverage files into one:\nimport marshal\nc1_dict = marshal.load(open(file...
[ 3, 3 ]
[]
[]
[ "code_coverage", "eclipse", "pydev", "python", "python_coverage" ]
stackoverflow_0000297294_code_coverage_eclipse_pydev_python_python_coverage.txt
Q: Connecting to MySQL with Python 2.6...how? All my searches, including this question on Stack, point me to MySQLdb. Unfortunately MySQLdb doesn't have a version for Python 2.6. What am I to do? A: Have you tried compiling it for Python 2.6? The APIs change very little in minor releases, so it's likely to Just W...
Connecting to MySQL with Python 2.6...how?
All my searches, including this question on Stack, point me to MySQLdb. Unfortunately MySQLdb doesn't have a version for Python 2.6. What am I to do?
[ "Have you tried compiling it for Python 2.6? The APIs change very little in minor releases, so it's likely to Just Work (TM).\nEdit: According to this post, it does work and the poster mentions that Windows binaries have been posted.\n" ]
[ 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000489807_mysql_python.txt
Q: QScintilla scrollbar When I add a QsciScintilla object to my main window the horizontal scrollbar is active and super wide (tons of apparent white space). Easy fix? A: Easy fix: sc.SendScintilla(sc.SCI_SETHSCROLLBAR, 0)
QScintilla scrollbar
When I add a QsciScintilla object to my main window the horizontal scrollbar is active and super wide (tons of apparent white space). Easy fix?
[ "Easy fix:\nsc.SendScintilla(sc.SCI_SETHSCROLLBAR, 0)\n\n" ]
[ 1 ]
[]
[]
[ "python", "qt", "scintilla" ]
stackoverflow_0000490130_python_qt_scintilla.txt