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: Documenting class attribute Following sample is taken from "Dive into python" book. class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = ... This sample shows documenting the MP3FileInfo, but how can I add help to MP3FileInfo. tagDataMap A: The PEP 224 on attribute docstrings was rejected ...
Documenting class attribute
Following sample is taken from "Dive into python" book. class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = ... This sample shows documenting the MP3FileInfo, but how can I add help to MP3FileInfo. tagDataMap
[ "The PEP 224 on attribute docstrings was rejected (long time ago), so this is a problem for me as well, sometimes I don't know to choose a class attribute or an instance property -- the second can have a docstring.\n", "Change it into a property method.\n", "Do it like this:\nclass MP3FileInfo(FileInfo):\n \...
[ 4, 1, 0 ]
[]
[]
[ "attributes", "class", "python", "self_documenting" ]
stackoverflow_0001347566_attributes_class_python_self_documenting.txt
Q: passing ctrl+z to pexpect How do I pass a certain key combination to a spawned/child process using the pexpect module? I'm using telnet and have to pass Ctrl+Z to a remote server. Tnx A: use sendcontrol() for example: p = pexpect.spawn(your_cmd_here) p.sendcontrol('z')
passing ctrl+z to pexpect
How do I pass a certain key combination to a spawned/child process using the pexpect module? I'm using telnet and have to pass Ctrl+Z to a remote server. Tnx
[ "use sendcontrol()\nfor example:\np = pexpect.spawn(your_cmd_here)\np.sendcontrol('z')\n\n" ]
[ 8 ]
[]
[]
[ "pexpect", "python" ]
stackoverflow_0001348283_pexpect_python.txt
Q: How do I create a file in python without overwriting an existing file Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and t...
How do I create a file in python without overwriting an existing file
Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a...
[ "Use os.open() with os.O_CREAT and os.O_EXCL to create the file. That will fail if the file already exists:\n>>> fd = os.open(\"x\", os.O_WRONLY | os.O_CREAT | os.O_EXCL)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOSError: [Errno 17] File exists: 'x'\n\nOnce you've created a new ...
[ 39, 7, 0 ]
[]
[]
[ "file", "multithreading", "python" ]
stackoverflow_0001348026_file_multithreading_python.txt
Q: Confusion about the Python path in Python shell vs FCGI server: Why are they different? I'm trying to deploy my Django app into production on a shared server. It seems I'm having problems with the Python path because I'm getting the error from the server: No module named products.models However, when I go to the r...
Confusion about the Python path in Python shell vs FCGI server: Why are they different?
I'm trying to deploy my Django app into production on a shared server. It seems I'm having problems with the Python path because I'm getting the error from the server: No module named products.models However, when I go to the root of the app and run the shell the modules load fine. '>>> from products.models import Answ...
[ "I'm somewhat confused -- if what you have in the path in the working case is:\n'/home/SecretUserAcct/django-projects/review_app'\n\ni.e., including the app, why are you instead, in the second non-working case, inserting\n'/home/SecretUserAcct/django-projects/'\n\ni.e., WITHOUT the app? Surely you'll need differen...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001347851_django_python.txt
Q: Where is the best place to put cache-evicting logic in an AppEngine application? I've written an application for Google AppEngine, and I'd like to make use of the memcache API to cut down on per-request CPU time. I've profiled the application and found that a large chunk of the CPU time is in template rendering an...
Where is the best place to put cache-evicting logic in an AppEngine application?
I've written an application for Google AppEngine, and I'd like to make use of the memcache API to cut down on per-request CPU time. I've profiled the application and found that a large chunk of the CPU time is in template rendering and API calls to the datastore, and after chatting with a co-worker I jumped (perhaps a ...
[ "I've got just such a decorator up in an open source Github project:\nhttp://github.com/jamslevy/gae_memoize/tree/master\nIt's a bit more in-depth, allowing for things like forcing execution of the function (when you want to refresh the cache) or forcing caching locally...these were just things that I needed in my ...
[ 1, 1 ]
[]
[]
[ "caching", "google_app_engine", "memcached", "optimization", "python" ]
stackoverflow_0001313626_caching_google_app_engine_memcached_optimization_python.txt
Q: Different versions of msvcrt in ctypes In Windows, the ctypes.cdll.msvcrt object automatically exists when I import the ctypes module, and it represents the msvcrt Microsoft C++ runtime library according to the docs. However, I notice that there is also a find_msvcrt function which will "return the filename of the...
Different versions of msvcrt in ctypes
In Windows, the ctypes.cdll.msvcrt object automatically exists when I import the ctypes module, and it represents the msvcrt Microsoft C++ runtime library according to the docs. However, I notice that there is also a find_msvcrt function which will "return the filename of the VC runtype library used by Python". It furt...
[ "It's not just that ctypes.cdll.msvcrt automatically exists, but ctypes.cdll.anything automatically exists, and is loaded on first access, loading anything.dll. So ctypes.cdll.msvcrt loads msvcrt.dll, which is a library that ships as part of Windows. It is not the C runtime that Python links with, so you shouldn't ...
[ 11 ]
[]
[]
[ "ctypes", "msvcrt", "python" ]
stackoverflow_0001348547_ctypes_msvcrt_python.txt
Q: ctype question char** I'm trying to figure out why this works after lots and lots of messing about with obo.librar_version is a c function which requires char ** as the input and does a strcpy to passed in char. from ctypes import * _OBO_C_DLL = 'obo.dll' STRING = c_char_p OBO_VERSION = _stdcall_libraries[_OBO_C...
ctype question char**
I'm trying to figure out why this works after lots and lots of messing about with obo.librar_version is a c function which requires char ** as the input and does a strcpy to passed in char. from ctypes import * _OBO_C_DLL = 'obo.dll' STRING = c_char_p OBO_VERSION = _stdcall_libraries[_OBO_C_DLL].OBO_VERSION OBO_VERSI...
[ "When you cast s to c_char_p you store a new object in t, not a reference. So when you pass t to your function by reference, s doesn't get updated.\nUPDATE:\nYou are indeed correct: \n\ncast takes two parameters, a ctypes\n object that is or can be converted to\n a pointer of some kind, and a ctypes\n pointer ...
[ 1, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001347280_ctypes_python.txt
Q: How do you control MySQL timeouts from SQLAlchemy? What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The connect_timeout URL parameter seems to be insufficient. I'm more interested in what happens when the machine that the database is running on, e...
How do you control MySQL timeouts from SQLAlchemy?
What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The connect_timeout URL parameter seems to be insufficient. I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly. I'm not ...
[ "this isn't possible due to the way TCP works. if the other computer drops off the network, it will simply stop responding to incoming packets. the \"18 seconds\" you're seeing is something on your TCP stack timing out due to no response.\nthe only way you can get your desired behavior is to have the computer gener...
[ 6, 2, 1 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0001209640_mysql_python_sqlalchemy.txt
Q: Gracefully-degrading pickling in Python (You may read this question for some background) I would like to have a gracefully-degrading way to pickle objects in Python. When pickling an object, let's call it the main object, sometimes the Pickler raises an exception because it can't pickle a certain sub-object of the...
Gracefully-degrading pickling in Python
(You may read this question for some background) I would like to have a gracefully-degrading way to pickle objects in Python. When pickling an object, let's call it the main object, sometimes the Pickler raises an exception because it can't pickle a certain sub-object of the main object. For example, an error I've been...
[ "You can decide and implement how any previously-unpicklable type gets pickled and unpickled: see standard library module copy_reg (renamed to copyreg in Python 3.*).\nEssentially, you need to provide a function which, given an instance of the type, reduces it to a tuple -- with the same protocol as the reduce spe...
[ 3, 0, 0 ]
[]
[]
[ "graceful_degradation", "pickle", "python" ]
stackoverflow_0001348315_graceful_degradation_pickle_python.txt
Q: Threads in python I am beginar in python script. I want read msaccess database records and write into XML file. Access database table have more than 20000 records. Now i am able to do but , it is taking 4 to 5 minutes. So i implement threading concept. But threading also taking more than 5 to 6 minutes. Because ea...
Threads in python
I am beginar in python script. I want read msaccess database records and write into XML file. Access database table have more than 20000 records. Now i am able to do but , it is taking 4 to 5 minutes. So i implement threading concept. But threading also taking more than 5 to 6 minutes. Because each thread open datasour...
[ "As mentioned please paste your code snippet. First - threads have a synchronisation overhead which is causing multi-threads to run slower.\nSecond - the msaccess/JET database is very slow and not really suited to multi-threaded use. You might like to consider SQL Server instead - SQL Server Express is free.\nThird...
[ 5, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001346098_multithreading_python.txt
Q: How do you add a custom section to the Django admin home page? In the Django admin each app you have registered with the admin gets its own section. I want to add a custom section for reporting that isn't associated with any app. How do I do that? A: To add a section not associated with an app, you'll have to ov...
How do you add a custom section to the Django admin home page?
In the Django admin each app you have registered with the admin gets its own section. I want to add a custom section for reporting that isn't associated with any app. How do I do that?
[ "To add a section not associated with an app, you'll have to override the admin index template. Create an admin/ directory in your project templates directory, and copy the file django/contrib/admin/templates/admin/index.html into it. Then you can add whatever markup you want to this file. The only downside (unfort...
[ 6 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001348710_django_django_admin_python.txt
Q: Programming a Self Learning Music Maker I want to learn how to program a music application that will analyze songs. How would I get started in this and is there a library for analyzing soundwaves? I know C, C++, Java, Python, some assembly, and some Perl. Related question: Algorithm for music imitation A: Compos...
Programming a Self Learning Music Maker
I want to learn how to program a music application that will analyze songs. How would I get started in this and is there a library for analyzing soundwaves? I know C, C++, Java, Python, some assembly, and some Perl. Related question: Algorithm for music imitation
[ "Composition and analysis of music by computer is a huge field. There are two basic areas in this type of work, which overlap somewhat.\n\nAlgorithmic composition is concerned with the generation of music. This can be based on statistical approaches such as Markov chaining, mathematical models employing fractal or ...
[ 10, 6, 3, 0, 0 ]
[]
[]
[ "perl", "python", "waveform" ]
stackoverflow_0001344884_perl_python_waveform.txt
Q: Novice needs advice for script that gets data and returns it in a usable format I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direc...
Novice needs advice for script that gets data and returns it in a usable format
I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direction. I want the script to get the width and height of each image, then format this ...
[ "Check out the PIL:\nfrom PIL import Image\nim = Image.open(\"yourfile.jpg\")\nprint im.size\n\nFor looping through files see this tutorial.\n", "Maybe the better solution would be not to create a script that generates a list of all the image elements for you to put in your document but rather generate the image ...
[ 3, 1, 0, 0 ]
[]
[]
[ "image_processing", "php", "python", "scripting", "web" ]
stackoverflow_0001349932_image_processing_php_python_scripting_web.txt
Q: Check whether debug is enabled in a Pylons application I'm working on a fairly simple Pylons 0.9.7 application. How do I tell, in code, whether or not debugging is enabled? That is, I'm interested in the value of the debug setting under [app:main] in my INI file. More generally, how do I access the other values fr...
Check whether debug is enabled in a Pylons application
I'm working on a fairly simple Pylons 0.9.7 application. How do I tell, in code, whether or not debugging is enabled? That is, I'm interested in the value of the debug setting under [app:main] in my INI file. More generally, how do I access the other values from there in my code?
[ "# tmp.py\nprint __debug__\n\n\n$ python tmp.py\nTrue\n$ python -O tmp.py\nFalse\n\nI'm not sure if this holds in Pylons, as I've never used that -- but in \"normal\" command line Python, debug is enabled if optimizations are not enabled. The -O flag indicates to Python to turn on optimizations.\nActually, there's...
[ 3 ]
[]
[]
[ "configuration", "pylons", "python" ]
stackoverflow_0001350227_configuration_pylons_python.txt
Q: sqlalchemy create a foreign key? I have a composite PK in table Strings (integer id, varchar(2) lang) I want to create a FK to ONLY the id half of the PK from other tables. This means I'd have potentially many rows in Strings table (translations) matching the FK. I just need to store the id, and have referential i...
sqlalchemy create a foreign key?
I have a composite PK in table Strings (integer id, varchar(2) lang) I want to create a FK to ONLY the id half of the PK from other tables. This means I'd have potentially many rows in Strings table (translations) matching the FK. I just need to store the id, and have referential integrity maintained by the DB. Is this...
[ "This is from wiki\n\nThe columns in the referencing table\n must be the primary key or other\n candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table.\n\nLet's say you have this:\nid | var \n1 | 10 \n1 | ...
[ 3 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0001350121_python_sql_sqlalchemy.txt
Q: SQLAlchemy session query with INSERT IGNORE I'm trying to do a bulk insert/update with SQLAlchemy. Here's a snippet: for od in clist: where = and_(Offer.network_id==od['network_id'], Offer.external_id==od['external_id']) o = session.query(Offer).filter(where).first() if not o: ...
SQLAlchemy session query with INSERT IGNORE
I'm trying to do a bulk insert/update with SQLAlchemy. Here's a snippet: for od in clist: where = and_(Offer.network_id==od['network_id'], Offer.external_id==od['external_id']) o = session.query(Offer).filter(where).first() if not o: o = Offer() o.network_id = od['network_id'] ...
[ "The way you should be doing these things is with session.merge(). \nYou should also be using your objects relation properties. So the o above should have o.offerpayout and this a list (of objects) and your offerpayout has offerpayout.country property which is the related countries object.\nSo the above would look...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001348510_python_sqlalchemy.txt
Q: How do I get PyParsing set up on the Google App Engine? I saw on the Google App Engine documentation that http://www.antlr.org/ Antlr3 is used as the parsing third party library. But from what I know Pyparsing seems to be the easier to use and I am only aiming to parse some simple syntax. Is there an alternative?...
How do I get PyParsing set up on the Google App Engine?
I saw on the Google App Engine documentation that http://www.antlr.org/ Antlr3 is used as the parsing third party library. But from what I know Pyparsing seems to be the easier to use and I am only aiming to parse some simple syntax. Is there an alternative? Can I get pyparsing working on the App Engine?
[ "Pyparsing's runtime footprint is intentionally small for just this purpose. It is a single source file, pyparsing.py, so just drop it in amongst your own source files and parse away!\n-- Paul\n", "\"Just do it\"!-) Get pyparsing.py, e.g. from here, and put it in your app engine app's directory; now you can jus...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "pyparsing", "python" ]
stackoverflow_0001341137_google_app_engine_pyparsing_python.txt
Q: Parsing an existing config file I have a config file that is in the following form: protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } ...
Parsing an existing config file
I have a config file that is in the following form: protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } The real file may not have thes...
[ "pyparsing is pretty handy for quick and simple parsing like this. A bare minimum would be something like:\nimport pyparsing\nstring = pyparsing.CharsNotIn(\"{} \\t\\r\\n\")\ngroup = pyparsing.Forward()\ngroup << pyparsing.Group(pyparsing.Literal(\"{\").suppress() + \n pyparsing.ZeroOrMore(...
[ 10, 2, 1, 1, 1, 0, 0 ]
[ "Maybe you could write a simple script that will convert your config into xml file and then read it just using lxml, Beatuful Soup or anything else? And your converter could use PyParsing or regular expressions for example.\n" ]
[ -2 ]
[ "config", "parsing", "python" ]
stackoverflow_0000996183_config_parsing_python.txt
Q: IBOutlet in Python Is there a way to use a Cocoa IBOutlet in Python? Or do I need to do this in ObjC? Thanks in advance. A: This article (found by searching Google for “pyobjc iboutlet”) has an example. Basically, you create objc.IBOutlet objects and set them as the values of class variables.
IBOutlet in Python
Is there a way to use a Cocoa IBOutlet in Python? Or do I need to do this in ObjC? Thanks in advance.
[ "This article (found by searching Google for “pyobjc iboutlet”) has an example. Basically, you create objc.IBOutlet objects and set them as the values of class variables.\n" ]
[ 1 ]
[]
[]
[ "cocoa", "objective_c", "python" ]
stackoverflow_0001351480_cocoa_objective_c_python.txt
Q: Strategy for maintaining complex filter states? I need to maintain a list of filtered and sorted objects, preferably in a generic manner, that can be used in multiple views. This is necessary so I can generate next, prev links, along with some other very useful things for the user. Examples of filters: field__isnu...
Strategy for maintaining complex filter states?
I need to maintain a list of filtered and sorted objects, preferably in a generic manner, that can be used in multiple views. This is necessary so I can generate next, prev links, along with some other very useful things for the user. Examples of filters: field__isnull=True field__exact="so" field__field__isnull=False ...
[ "You've identified the two options for maintaining user-specific state in a web application: store it in cookies/session, or pass it around on URLs. I don't believe there's a third \"silver bullet\" waiting in the wings to solve your problem.\nThe URL query-string option has the advantage that a particular view sta...
[ 2, 1 ]
[]
[]
[ "django", "http", "python" ]
stackoverflow_0001349840_django_http_python.txt
Q: What are some of the core conceptual differences between C# and Python? I'm new to Python, coming from a C# background and I'm trying to get up to speed. I understand that Python is dynamically typed, whereas C# is strongly-typed. -> see comments. What conceptual obstacles should I watch out for when attempting to...
What are some of the core conceptual differences between C# and Python?
I'm new to Python, coming from a C# background and I'm trying to get up to speed. I understand that Python is dynamically typed, whereas C# is strongly-typed. -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How i...
[ "\" I understand that Python is dynamically typed, whereas C# is strongly-typed. \"\nThis is weirdly wrong.\n\nPython is strongly typed. A list or integer or dictionary is always of the given type. The object's type cannot be changed.\nPython variables are not strongly typed. Indeed, Python variables are just la...
[ 9, 4, 3, 2, 1 ]
[]
[]
[ "asp.net", "c#", "django", "programming_languages", "python" ]
stackoverflow_0001351227_asp.net_c#_django_programming_languages_python.txt
Q: Show/hide a plot's legend I'm relatively new to python and am developing a pyqt GUI. I want to provide a checkbox option to show/hide a plot's legend. Is there a way to hide a legend? I've tried using pyplot's '_nolegend_' and it appears to work on select legend entries but it creates a ValueError if applied to a...
Show/hide a plot's legend
I'm relatively new to python and am developing a pyqt GUI. I want to provide a checkbox option to show/hide a plot's legend. Is there a way to hide a legend? I've tried using pyplot's '_nolegend_' and it appears to work on select legend entries but it creates a ValueError if applied to all entries. I can brute force ...
[ "Here's something you can try on the command line:\nplot([3,1,4,1],label='foo')\nlgd=legend()\n\n# when you want it to be invisible:\nlgd.set_visible(False)\ndraw()\n\n# when you want it to be visible:\nlgd.set_visible(True)\ndraw()\n\nIn a GUI program it's best to avoid pyplot and use the object-oriented API, i.e....
[ 10 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001349202_matplotlib_python.txt
Q: What does matrix**2 mean in python/numpy? I have a python ndarray temp in some code I'm reading that suffers this: x = temp**2 Is this the dot square (ie, equivalent to m.*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code: ...
What does matrix**2 mean in python/numpy?
I have a python ndarray temp in some code I'm reading that suffers this: x = temp**2 Is this the dot square (ie, equivalent to m.*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code: temp = num.transpose(whatever) num.sum(temp**2,...
[ "It's just the square of each element.\nfrom numpy import *\na = arange(4).reshape((2,2))\nprint a**2\n\nprints\n[[0 1]\n [4 9]]\n\n", "You should read NumPy for Matlab Users. The elementwise power operation is mentioned there, and you can also see that in numpy, some operators apply differently to array and matr...
[ 15, 6, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001350174_numpy_python.txt
Q: Running doctests through iPython and pseudo-consoles I've got a fairly basic doctestable file: class Foo(): """ >>> 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest doctest.testmod(verbose=True) which works as expected when run directly through python. However, in iPyt...
Running doctests through iPython and pseudo-consoles
I've got a fairly basic doctestable file: class Foo(): """ >>> 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest doctest.testmod(verbose=True) which works as expected when run directly through python. However, in iPython, I get 1 items had no tests: __main__ 0 tests in 1...
[ "The root problem is that ipython plays weird tricks with __main__ (through its own FakeModule module) so that, by the time doctest is introspecting that \"alleged module\" through its __dict__, Foo is NOT there -- so doctest doesn't recurse into it.\nHere's one solution:\nclass Foo():\n \"\"\"\n >>> 3+2\n ...
[ 8, 2 ]
[]
[]
[ "django", "ipython", "python" ]
stackoverflow_0001336980_django_ipython_python.txt
Q: How do I form a URL in Django for what I'm doing Desperate, please help. Will work for food :) I want to be able to have pages at the following URLs, and I want to be able to look them up by their URL (ie, If somebody goes to a certain URL, I want to be able to check for a page there). mysite.com/somepage/somesub...
How do I form a URL in Django for what I'm doing
Desperate, please help. Will work for food :) I want to be able to have pages at the following URLs, and I want to be able to look them up by their URL (ie, If somebody goes to a certain URL, I want to be able to check for a page there). mysite.com/somepage/somesubpage/somesubsubpage/ mysite.com/somepage/somesubpage/a...
[ "You need to also store level and parent attributes, so that you can always get the right object.\nThe requirement to store hierarchical data comes up very frequently, and I always recommend django-mptt. It's the Django implementation of an efficient algorithm for storing hierarchical data in a database. I've used ...
[ 2, 0 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0001352073_django_django_urls_python_regex.txt
Q: Object store for objects in Django between requests I had the following idea: Say we have a webapp written using django which models some kind of bulletin board. This board has many threads but a few of them get the most posts/views per hour. The thread pages look a little different for each user, so you can't cac...
Object store for objects in Django between requests
I had the following idea: Say we have a webapp written using django which models some kind of bulletin board. This board has many threads but a few of them get the most posts/views per hour. The thread pages look a little different for each user, so you can't cache the rendered page as whole and caching only some parts...
[ "In a production WSGI environment, you would probably have multiple worker processes serving requests at the same time. These worker processes would be recycled from time to time, meaning local memory objects would be lost.\nBut if you really need this (and make sure you do), I suggest you look into Django's cachin...
[ 7, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001351323_django_python.txt
Q: suppress/redirect stderr when calling python webrowser I have a python program that opens several urls in seperate tabs in a new browser window, however when I run the program from the command line and open the browser using webbrowser.open_new(url) The stderr from firefox prints to bash. Looking at the docs I c...
suppress/redirect stderr when calling python webrowser
I have a python program that opens several urls in seperate tabs in a new browser window, however when I run the program from the command line and open the browser using webbrowser.open_new(url) The stderr from firefox prints to bash. Looking at the docs I can't seem to find a way to redirect or suppress them I have ...
[ "What is webbrowser.get() giving you?\nIf you do\n webbrowser.get('firefox').open(url)\n\nthen you shouldn't see any output. The webbrowser module choses to leave stderr for some browsers - in particular the text browsers, and then ones where it isn't certain. For all UnixBrowsers that have set background to True, ...
[ 6, 0, 0 ]
[]
[]
[ "browser", "python", "stderr" ]
stackoverflow_0001352361_browser_python_stderr.txt
Q: Why is Python's enumerate so slow? Why is "enumerate" slower than "xrange + lst[i]"? >>> from timeit import Timer >>> lst = [1,2,3,0,1,2]*1000 >>> setup = 'from __main__ import lst' >>> s1 = """ for i in range(len(lst)): elem = lst[i] """ >>> s2 = """ for i in xrange(len(lst)): elem = lst[i] """ >>> s3 = ...
Why is Python's enumerate so slow?
Why is "enumerate" slower than "xrange + lst[i]"? >>> from timeit import Timer >>> lst = [1,2,3,0,1,2]*1000 >>> setup = 'from __main__ import lst' >>> s1 = """ for i in range(len(lst)): elem = lst[i] """ >>> s2 = """ for i in xrange(len(lst)): elem = lst[i] """ >>> s3 = """ for i, v in enumerate(lst): ele...
[ "If you measure properly you'll see there's essentially no difference (enumerate is microscopically faster than xrange in this example, but well within noise):\n$ python -mtimeit -s'lst=[1,2,3,0,1,2]*1000' 'for i in xrange(len(lst)): elem=lst[i]'\n1000 loops, best of 3: 480 usec per loop\n$ python -mtimeit -s'lst=[...
[ 18, 6 ]
[]
[]
[ "python" ]
stackoverflow_0001352497_python.txt
Q: What classes of applications or problems do you prefer Python to strictly OO Languages? I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading Programming Collective Intelligence. I under...
What classes of applications or problems do you prefer Python to strictly OO Languages?
I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading Programming Collective Intelligence. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to kno...
[ "My motto is (and has long been) \"Python where I can, C++ where I must\" (one day I'll find opportunity to actually use Java, C#, &c &C, in a real-world project, but I haven't yet, except for a pilot project in Java 1.1, more tha ten years ago...;-) -- Javascript (with dojo) when code has to run in the client's br...
[ 10, 4, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "c#", "c++", "java", "programming_languages", "python" ]
stackoverflow_0001022971_c#_c++_java_programming_languages_python.txt
Q: Tool for analysing and stepping through code? Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc. I can't fi...
Tool for analysing and stepping through code?
Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc. I can't find the reference to it again. Would anyone know wha...
[ "cProfile or Hotshot.\n", "RunSnakeRun is user interface for cProfile/Hotshot (see James' answer), which also provides a visualization of the profiling data.\nAnother useful link might be the link to the PyCon2009 Talk Introduction to Python Profiling (#65)\n", "Found what I was looking for: Code Investigator\n...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "code_analysis", "profiling", "python" ]
stackoverflow_0001350864_code_analysis_profiling_python.txt
Q: Python script performance as a background process Im in the process of writing a python script to act as a "glue" between an application and some external devices. The script itself is quite straight forward and has three distinct processes: Request data (from a socket connection, via UDP) Receive response (from ...
Python script performance as a background process
Im in the process of writing a python script to act as a "glue" between an application and some external devices. The script itself is quite straight forward and has three distinct processes: Request data (from a socket connection, via UDP) Receive response (from a socket connection, via UDP) Process response and make...
[ "If you are using blocking I/O to your devices, then the script won't consume any processor while waiting for the data. How much processor you use depends on what sorts of computation you are doing with the data.\n", "Twisted -- the best async framework for Python -- would allow you do perform these tasks with t...
[ 5, 4 ]
[]
[]
[ "background", "performance", "process", "python" ]
stackoverflow_0001352760_background_performance_process_python.txt
Q: Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'? Anyone know this? I've never been able to find an answer. A: If you're prone to installing python in various and interesting places on your PATH (as in $PATH in typical Unix shells, %PATH on typical Windows ones), using /usr/bi...
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
Anyone know this? I've never been able to find an answer.
[ "If you're prone to installing python in various and interesting places on your PATH (as in $PATH in typical Unix shells, %PATH on typical Windows ones), using /usr/bin/env will accomodate your whim (well, in Unix-like environments at least) while going directly to /usr/bin/python won't. But losing control of what...
[ 67, 24, 10, 5, 3 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0001352922_bash_python.txt
Q: Nice copying from Python Interpreter When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ... Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean th...
Nice copying from Python Interpreter
When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ... Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output. Additionally, sometimes I would ...
[ "IPython lets you show, save and edit your command history, for example to show the first three commands of your session without line numbers you'd type %hist -n 1 4.\n", "WingIDE from Wingware will let you evaluate any chunk of code in a separate interpreter window.\n", "IPython will let you paste Python code ...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001352886_python.txt
Q: Remove elements as you traverse a list in Python In Java I can do by using an Iterator and then using the .remove() method of the iterator to remove the last element returned by the iterator, like this: import java.util.*; public class ConcurrentMod { public static void main(String[] args) { List<Stri...
Remove elements as you traverse a list in Python
In Java I can do by using an Iterator and then using the .remove() method of the iterator to remove the last element returned by the iterator, like this: import java.util.*; public class ConcurrentMod { public static void main(String[] args) { List<String> colors = new ArrayList<String>(Arrays.asList("red"...
[ "Best approach in Python is to make a new list, ideally in a listcomp, setting it as the [:] of the old one, e.g.:\ncolors[:] = [c for c in colors if c != 'green']\n\nNOT colors = as some answers may suggest -- that only rebinds the name and will eventually leave some references to the old \"body\" dangling; colors...
[ 30, 24, 4, 0 ]
[]
[]
[ "iterator", "list", "loops", "python", "python_datamodel" ]
stackoverflow_0001352885_iterator_list_loops_python_python_datamodel.txt
Q: Issues with scoped_session in sqlalchemy - how does it work? I'm not really sure how scoped_session works, other than it seems to be a wrapper that hides several real sessions, keeping them separate for different requests. Does it do this with thread locals? Anyway the trouble is as follows: S = elixir.session # =...
Issues with scoped_session in sqlalchemy - how does it work?
I'm not really sure how scoped_session works, other than it seems to be a wrapper that hides several real sessions, keeping them separate for different requests. Does it do this with thread locals? Anyway the trouble is as follows: S = elixir.session # = scoped_session(...) f = Foo(bar=1) S.add(f) # ERROR, f is already...
[ "Scoped session creates a proxy object that keeps a registry of (by default) per thread session objects created on demand from the passed session factory. When you access a session method such as ScopedSession.add it finds the session corresponding to the current thread and returns the add method bound to that sess...
[ 7, 2 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0001353131_python_python_elixir_sqlalchemy.txt
Q: I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive? I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer. I am in a quandary putting this into practice. I want to know specific w...
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer. I am in a quandary putting this into practice. I want to know specific ways that using Python or Ruby can make me a more productive .NET developer. One specific way per answer, and eve...
[ "IronPython / IronRuby\nIronPython in Action will do a better job explaining this (and exactly how best to use IronPython) that can possibly be accommodated in a SO answer. I'm biased -- I was a tech reviewer and am a friend of one of the authors -- but objectively think it's a great book. (No idea if IronRuby is b...
[ 5, 4, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ ".net", "python", "ruby" ]
stackoverflow_0001353211_.net_python_ruby.txt
Q: Multiprocessing debug techniques I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in th...
Multiprocessing debug techniques
I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module. Are there an...
[ "Yah, debugging deadlocks is fun. You can set the logging level to be higher -- see the Python documentation for a description of it, but really quickly:\nimport multiprocessing, logging\nlogger = multiprocessing.log_to_stderr()\nlogger.setLevel(multiprocessing.SUBDEBUG)\n\nAlso, add logging for anything in your c...
[ 45, 12 ]
[]
[]
[ "deadlock", "debugging", "multiprocessing", "python" ]
stackoverflow_0001352980_deadlock_debugging_multiprocessing_python.txt
Q: How to put Google login box inside flash in GAE? I am putting my old flash site into GAE. I want to use Google's user authentication too. Now, I want to put Googles login box inside the flash instead of redirecting to Google's login page. Same thing I want for forgot password. Is it possible to do this? How to do ...
How to put Google login box inside flash in GAE?
I am putting my old flash site into GAE. I want to use Google's user authentication too. Now, I want to put Googles login box inside the flash instead of redirecting to Google's login page. Same thing I want for forgot password. Is it possible to do this? How to do this?
[ "Of course this is possible\nyou just need to use flash to post http request to your server\nand your server could communicate to flash through several ways like: xml , html, and AMF or even johnson( I am not sure).\nI recommend you use pyamf at server side to build a native support for flash at server side\n" ]
[ 1 ]
[]
[]
[ "authentication", "flash", "google_app_engine", "python" ]
stackoverflow_0001079022_authentication_flash_google_app_engine_python.txt
Q: Python SOAP clients will not work with this WSDL Thus far I've tried to access this WSDL: https://login.azoogleads.com/affiliate/tool/soap_api from the two common Python SOAP clients that I'm aware of: SOAPpy and ZSI.client.Binding. SOAPpy raises an exception in PyXML (xml.parsers.expat.ExpatError: not well-forme...
Python SOAP clients will not work with this WSDL
Thus far I've tried to access this WSDL: https://login.azoogleads.com/affiliate/tool/soap_api from the two common Python SOAP clients that I'm aware of: SOAPpy and ZSI.client.Binding. SOAPpy raises an exception in PyXML (xml.parsers.expat.ExpatError: not well-formed (invalid token)) and ZSI raises an exception in the ...
[ "your not actually giving it a valid WSDL endpoint try explicilty giving it the WSDL location rather than the directory it is in. Remember computer are exceptually stupid things!\n" ]
[ 2 ]
[]
[]
[ "python", "soap", "soappy", "zsi" ]
stackoverflow_0001349325_python_soap_soappy_zsi.txt
Q: Summing up two columns the Unix way # To fix the symptom How can you sum up the following columns effectively? Column 1 1 3 3 ... Column 2 2323 343 232 ... This should give me Expected result 2324 346 235 ... I have the columns in two files. # Initial situation I use sometimes too many curly brackets such t...
Summing up two columns the Unix way
# To fix the symptom How can you sum up the following columns effectively? Column 1 1 3 3 ... Column 2 2323 343 232 ... This should give me Expected result 2324 346 235 ... I have the columns in two files. # Initial situation I use sometimes too many curly brackets such that I have used one more this { than this...
[ "Using python:\ntotals = [ int(i)+int(j) for i, j in zip ( open(fname1), open(fname2) ) ]\n\n", "If c1 and c2 are youre files, you can do this:\n$ paste c1 c2 | awk '{print $1 + $2}'\n\nOr (without AWK):\n$ paste c1 c2 | while read i j; do echo $(($i+$j)); done\n\n", "You can avoid the intermediate steps by jus...
[ 11, 11, 3, 1, 0, 0 ]
[]
[]
[ "awk", "brackets", "perl", "python", "unix" ]
stackoverflow_0001347457_awk_brackets_perl_python_unix.txt
Q: Creating SVGs using Python I'm building a set of SVG files that include an unfortunate number of hardcoded values (they must print with some elements sized in mm, while others must be scaled as a percent, and most of the values are defined relative to each other). Rather than managing those numbers by hand (heaven...
Creating SVGs using Python
I'm building a set of SVG files that include an unfortunate number of hardcoded values (they must print with some elements sized in mm, while others must be scaled as a percent, and most of the values are defined relative to each other). Rather than managing those numbers by hand (heaven forbid I want to change somethi...
[ "A markup based templating engine, such as genshi might be useful. It would let you do most of the authoring using a SVG tool and do the customization in the template. I'd definitely prefer it to XSLT.\n", "Since SVG is XML, maybe you could use XSLT to transform a source XML file containing your variables to SVG....
[ 4, 0 ]
[]
[]
[ "graphics", "python", "svg", "xml" ]
stackoverflow_0001353976_graphics_python_svg_xml.txt
Q: Is Python the right hammer for this nail? (build script) Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc. But the problem is, batch files are evil. So I would li...
Is Python the right hammer for this nail? (build script)
Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc. But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate m...
[ "For a tool that is scripted with Python, I happen to think Paver is a more easily-managed and more flexible build automator than SCons. Unlike SCons, Paver is designed for the plethora of not-compiling-programs tasks that go along with managing and distributing a software project.\n", "Batch files aren't evil - ...
[ 16, 9, 7, 4, 4, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "build_automation", "build_process", "python" ]
stackoverflow_0000792629_build_automation_build_process_python.txt
Q: Using HTML Parser with HTTPResponse in Python 3.1 The response data from HTTPResponse object is of type bytes. conn = http.client.HTTPConnection(www.yahoo.com) conn.request("GET","/") response = conn.getresponse(); data = response.read() type(data) The data is of type bytes. I would like to use the response alon...
Using HTML Parser with HTTPResponse in Python 3.1
The response data from HTTPResponse object is of type bytes. conn = http.client.HTTPConnection(www.yahoo.com) conn.request("GET","/") response = conn.getresponse(); data = response.read() type(data) The data is of type bytes. I would like to use the response along with the built-in HTML parser of Python 3.1. However ...
[ "\nIs there a reason why HTTP response\n does not return string?\n\nYou nailed it yourself. A HTTP response isn't necessarily a string.\nIt can be an image, for example, and even when it is a string it can't know the encoding.\nIf you know the encoding (or have an encoding detection library) then it's very easy to...
[ 2 ]
[]
[]
[ "html", "http", "python" ]
stackoverflow_0001354338_html_http_python.txt
Q: Should I optimise my python code like C++? Does it matter? I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++. Thi...
Should I optimise my python code like C++? Does it matter?
I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++. Things like: In an if statement with an or always put the conditio...
[ "My answer to that would be :\n\nWe should forget about small\n efficiencies, say about 97% of the\n time: premature optimization is the\n root of all evil.\n\n(Quoting Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268)\n\nIf your applicati...
[ 14, 13, 10, 4, 3, 2, 2, 2, 1, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0001353715_performance_python.txt
Q: Storing huge hash table in a file in Python Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I k...
Storing huge hash table in a file in Python
Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there'...
[ "For a list of primes up to 10**9, why do you need a hash? What would the KEYS be?! Sounds like a perfect opportunity for a simple, straightforward binary file! By the Prime Number Theorem, there's about 10**9/ln(10**9) such primes -- i.e. 50 millions or a bit less. At 4 bytes per prime, that's only 200 MB or le...
[ 11, 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "file", "hashtable", "python" ]
stackoverflow_0001354520_file_hashtable_python.txt
Q: Split Twitter RSS string using Python I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example: MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money What I want to do is create one column for the main content ...
Split Twitter RSS string using Python
I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example: MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money What I want to do is create one column for the main content (Miami Pete…now up), one column for the URL...
[ "It seems like your data-driven design is rather flawed. Unless all your entries have a text part, an url and up to 4 tags, it's not going to work.\nYou also need to separate saving to db from parsing. Parsing could be easily done with a regexep (or even string methods):\n>>> s = your_string\n>>> s.split()\n['Miami...
[ 4, 2, 1, 1 ]
[]
[]
[ "bit.ly", "python", "split", "sqlite", "string" ]
stackoverflow_0001354415_bit.ly_python_split_sqlite_string.txt
Q: Python code to download a webpage using JavaScript Im trying to download share data from a stock exchange using python. The problem is that there is no direct download link, but rather a javascript to export the data. The data page url: http://tase.co.il/TASE/Templates/Company/CompanyHistory.aspx?NRMODE=Publishe...
Python code to download a webpage using JavaScript
Im trying to download share data from a stock exchange using python. The problem is that there is no direct download link, but rather a javascript to export the data. The data page url: http://tase.co.il/TASE/Templates/Company/CompanyHistory.aspx?NRMODE=Published&NRORIGINALURL=%2fTASEEng%2fGeneral%2fCompany%2fcompany...
[ "You could use Selenium or other ways to automate a browser to take advantage of the browser's built-in Javascript interpreter -- to control Selenium with Python, see e.g. here.\n" ]
[ 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0001355244_javascript_python.txt
Q: Latin letters with acute : DjangoUnicodeDecodeError I have a problem reading a txt file to insert in the mysql db table, te sniped of this code: file contains the in first line: "aclaración" archivo = open('file.txt',"r") for line in archivo.readlines(): ....body = body + line model = MyModel(body=body) ...
Latin letters with acute : DjangoUnicodeDecodeError
I have a problem reading a txt file to insert in the mysql db table, te sniped of this code: file contains the in first line: "aclaración" archivo = open('file.txt',"r") for line in archivo.readlines(): ....body = body + line model = MyModel(body=body) model.save() i get a DjangoUnicodeDecodeError: 'utf8' co...
[ "Judging from the \\xf3 code for 'ó', it does look like the data is encoded in ISO-8859-1 (or some close relative). So body.decode('iso-8859-1') should be a valid Unicode string (you don't specify what \"without solution\" means -- what error message do you get, and where?); if what you need is a utf-8 encoded byt...
[ 5 ]
[]
[]
[ "character_encoding", "django", "python", "utf_8" ]
stackoverflow_0001355285_character_encoding_django_python_utf_8.txt
Q: Python classes -- mutability Im having a problem with python.. I have a binary tree node type: class NODE: element = 0 leftchild = None rightchild = None And I had to implement a function deletemin: def DELETEMIN( A ): if A.leftchild == None: retval = A.element ...
Python classes -- mutability
Im having a problem with python.. I have a binary tree node type: class NODE: element = 0 leftchild = None rightchild = None And I had to implement a function deletemin: def DELETEMIN( A ): if A.leftchild == None: retval = A.element A = A.rightchild ...
[ "Python passes arguments by object-reference, just like java, not by variable-reference. When you assign to a local variable (including an argument) to a new value, you're changing only the local variable, nothing else (don't confuse that with calling mutators or assigning to ATTRIBUTES of objects: we're talking ab...
[ 2, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001355555_class_python.txt
Q: How can python call a class that is never defined in the code? I don't know if it is feasable to paste all of the code here but I am looking at the code in this git repo. If you look at the example they do: ec2 = EC2('access key id', 'secret key') ...but there is no EC2 class. However, it looks like in libcloud\...
How can python call a class that is never defined in the code?
I don't know if it is feasable to paste all of the code here but I am looking at the code in this git repo. If you look at the example they do: ec2 = EC2('access key id', 'secret key') ...but there is no EC2 class. However, it looks like in libcloud\providers.py there is a dict that maps the EC2 to the EC2NodeDriver ...
[ "example.py includes an import statement that reads:\nfrom libcloud.drivers import EC2, Slicehost, Rackspace\n\nThis means that the EC2 class is imported from the libcloud.drivers module. However, in this case, libcloud.drivers is actually a package (a Python package contains modules), which means that EC2 should b...
[ 5, 0 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001355710_python_python_import.txt
Q: Is there a stable integration procedure/pluggin for Django 1.1 and Google app engine? What is the best procedure/plugging to use to integrate django and google app engine? I have read many articles in the internet and seen videos on how to go round this. Am still left wondering which is the best procedure to use. ...
Is there a stable integration procedure/pluggin for Django 1.1 and Google app engine?
What is the best procedure/plugging to use to integrate django and google app engine? I have read many articles in the internet and seen videos on how to go round this. Am still left wondering which is the best procedure to use. Is there an official procedure documented in django or google app engine. Examples and sit...
[ "There is NO way you can run Python 2.6 on App Engine: it's 2.5 only.\nIf you're rarin' to have Django 1.1 (with Python 2.5), I suggest app-engine patch which now supports it (it's a release candidate, not a final release, but close). I find their docs good and thorough, and their code well written and solid.\n" ]
[ 3 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001355813_django_google_app_engine_python.txt
Q: How to call super() in Python 3.0? I have the strangest error I have seen for a while in Python (version 3.0). Changing the signature of the function affects whether super() works, despite the fact that it takes no arguments. Can you explain why this occurs? Thanks, Chris >>> class tmp: ... def __new__(*args):...
How to call super() in Python 3.0?
I have the strangest error I have seen for a while in Python (version 3.0). Changing the signature of the function affects whether super() works, despite the fact that it takes no arguments. Can you explain why this occurs? Thanks, Chris >>> class tmp: ... def __new__(*args): ... super() ... >>> tmp() ...
[ "As the docs say, \"The zero argument form automatically searches the stack frame for the class (__class__) and the first argument.\" Your first example of __new__ doesn't HAVE a first argument - it claims it can be called with zero or more arguments, so argumentless super is stumped. Your second example DOES have...
[ 6, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001355931_python_python_3.x.txt
Q: Why is the C++ syntax so complicated? I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago. This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?" Writing "Hello world." in Python i...
Why is the C++ syntax so complicated?
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago. This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?" Writing "Hello world." in Python is as simple as "print 'Hello world.'" but i...
[ "C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is n...
[ 91, 14, 7, 6, 6, 5, 5, 3, 2, 0 ]
[]
[]
[ "c++", "python", "syntax" ]
stackoverflow_0001355803_c++_python_syntax.txt
Q: How to Extract the key from unnecessary Html Wrapping in python The HTML page containing the key and some \n character .I need to use only key block i.e from -----BEGIN PGP PUBLIC KEY BLOCK----- to -----END PGP PUBLIC KEY BLOCK----- and after putting extracting key in a file can i pass it in any function.... A: ...
How to Extract the key from unnecessary Html Wrapping in python
The HTML page containing the key and some \n character .I need to use only key block i.e from -----BEGIN PGP PUBLIC KEY BLOCK----- to -----END PGP PUBLIC KEY BLOCK----- and after putting extracting key in a file can i pass it in any function....
[ "in it's simpliest form\nimport re\nclean = re.sub(\"</?[^\\W].{0,10}?>|\\n|\\r\\n\", \"\", your_html) #remove tags and newlines\nkey = re.search(r'BEGIN PGP PUBLIC KEY BLOCK.+?END PGP PUBLIC KEY BLOCK', clean)\n\nor if you don't need BEGIN PGP ... BLOCK and END PGP ... BLOCK:\nkey = re.search(r'BEGIN PGP PUBLIC K...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001356705_python.txt
Q: Display jpg images in python I am creating a simple tool to add album cover images to mp3 files in python. So far I am just working on sending a request to amazon with artist and album title, and get the resulting list, as well as finding the actual images for each result. What I want to do is to display a simple ...
Display jpg images in python
I am creating a simple tool to add album cover images to mp3 files in python. So far I am just working on sending a request to amazon with artist and album title, and get the resulting list, as well as finding the actual images for each result. What I want to do is to display a simple frame with a button/link for each ...
[ "you can modify this using urllib.urlopen(). But I don't know (as I haven't tested it) if you can make this step without saving the (image) file locally. But IMHO urlopen returns a file handle that is usable in tk.PhotoImage().\nFor jpg files in PhotoImage you need PIL:\nfrom PIL import Image, ImageTk\nimage = Imag...
[ 3 ]
[ "For displaying jpgs in Python check out PIL \n" ]
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0001356255_python_tkinter.txt
Q: file system performance testing I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain? A: File system performance test...
file system performance testing
I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain?
[ "File system performance testing is a very complex topic. You can easily make a lots of mistakes that basically make your whole tests worthless.\nStony Brook University and IBM Watson Labs have published an highly recommended journal paper in the \"Transaction of Storage\" about file system benchmarking, in which t...
[ 3, 0, 0, 0 ]
[]
[]
[ "filesystems", "performance_testing", "python" ]
stackoverflow_0001356240_filesystems_performance_testing_python.txt
Q: Handling KeyboardInterrupt in a KDE Python application? I'm working on a PyKDE4/PyQt4 application, Autokey, and I noticed that when I send the program a CTRL+C, the keyboard interrupt is not processed until I interact with the application, by ie. clicking on a menu item or changing a checkbox. lfaraone@stone:~$ /...
Handling KeyboardInterrupt in a KDE Python application?
I'm working on a PyKDE4/PyQt4 application, Autokey, and I noticed that when I send the program a CTRL+C, the keyboard interrupt is not processed until I interact with the application, by ie. clicking on a menu item or changing a checkbox. lfaraone@stone:~$ /usr/bin/autokey ^C^C^C Traceback (most recent call last): F...
[ "Try doing this:\nimport signal\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\nbefore invoking a.main().\nUpdate: Remember, Ctrl-C can be used for Copy in GUI applications. It's better to use Ctrl+\\ in Qt, which will cause the event loop to terminate and the application to close.\n" ]
[ 8 ]
[]
[]
[ "autokey", "keyboardinterrupt", "pykde", "pyqt", "python" ]
stackoverflow_0001353823_autokey_keyboardinterrupt_pykde_pyqt_python.txt
Q: python object to native c++ pointer Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer. So this is my class: class CGEGameModeB...
python object to native c++ pointer
Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer. So this is my class: class CGEGameModeBase { public: virtual void FunctionCa...
[ "Thanks to Stefan from the python c++ mailling list, i was missing \nsuper(Alpha, self).__init__()\n\nfrom the constructor call meaning it never made the parent class. Thought this would of been automatic :D\nOnly other issue i had was saving the new class instance as a global var otherwise it got cleaned up as it ...
[ 2, 1, 0 ]
[]
[]
[ "boost", "c++", "embedded_language", "python" ]
stackoverflow_0001355187_boost_c++_embedded_language_python.txt
Q: How do I line up text from python into columns in my terminal? I'm printing out some values from a script in my terminal window like this: for i in items: print "Name: %s Price: %d" % (i.name, i.price) How do I make these line up into columns? A: If you know the maximum lengths of data in the two columns, t...
How do I line up text from python into columns in my terminal?
I'm printing out some values from a script in my terminal window like this: for i in items: print "Name: %s Price: %d" % (i.name, i.price) How do I make these line up into columns?
[ "If you know the maximum lengths of data in the two columns, then you can use format qualifiers. For example if the name is at most 20 chars long and the price will fit into 10 chars, you could do\nprint \"Name: %-20s Price: %10d\" % (i.name, i.price)\n\nThis is better than using tabs as tabs won't line up in some ...
[ 18, 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001356029_python.txt
Q: Detecting case mismatch on filename in Windows (preferably using python)? I have some xml-configuration files that we create in a Windows environment but is deployed on Linux. These configuration files reference each other with filepaths. We've had problems with case-sensitivity and trailing spaces before, and I'd...
Detecting case mismatch on filename in Windows (preferably using python)?
I have some xml-configuration files that we create in a Windows environment but is deployed on Linux. These configuration files reference each other with filepaths. We've had problems with case-sensitivity and trailing spaces before, and I'd like to write a script that checks for these problems. We have Cygwin if that ...
[ "os.listdir on a directory, in all case-preserving filesystems (including those on Windows), returns the actual case for the filenames in the directory you're listing.\nSo you need to do this check at each level of the path:\ndef onelevelok(parent, thislevel):\n for fn in os.listdir(parent):\n if fn.lower() == ...
[ 3, 0 ]
[]
[]
[ "case_sensitive", "python", "windows" ]
stackoverflow_0001356386_case_sensitive_python_windows.txt
Q: Django ModelChoiceField initial data not working for ForeignKey I am filling my form with initial data using the normail: form = somethingForm(initial = { 'title' : something.title, 'category' : something.category_id, }) The title works f...
Django ModelChoiceField initial data not working for ForeignKey
I am filling my form with initial data using the normail: form = somethingForm(initial = { 'title' : something.title, 'category' : something.category_id, }) The title works fine, but if the category is a ModelChoiceField and a ForeignKey in th...
[ "Perhaps try using an instance of a category rather than its ID?\n", "You need to do this\nform = somethingForm(initial = {\n 'title' : something.title, \n 'category' : [(\"database value\",\"display value\")],\n })\n\nWhy list of tuples?\n\n...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001296938_django_python.txt
Q: Creating database schema for parsed feed Additional questions regarding SilentGhost's initial answer to a problem I'm having parsing Twitter RSS feeds. See also partial code below. First, could I insert tags[0], tags[1], etc., into the database, or is there a different/better way to do it? Second, almost all of t...
Creating database schema for parsed feed
Additional questions regarding SilentGhost's initial answer to a problem I'm having parsing Twitter RSS feeds. See also partial code below. First, could I insert tags[0], tags[1], etc., into the database, or is there a different/better way to do it? Second, almost all of the entries have a url, but a few don't; likewi...
[ "I would suggest reading up on database normalisation, especially on 1st and 2nd normal forms. Once you're done with it, I hope there won't be need for default values, and your db schema evolves into something more appropriate.\nThere are plenty of options for sharing your source code on the web, depending on what ...
[ 2 ]
[]
[]
[ "database_schema", "python", "rss" ]
stackoverflow_0001358501_database_schema_python_rss.txt
Q: Homework: Triangle angle calculation all sides known I know I should do my homework on my own but I simply can't get my homework to work the way I want it to: from __future__ import division import turtle import math def triangle(c,a,b,beta,gamma): turtle.forward(c) turtle.right(180+beta) turtle.forwa...
Homework: Triangle angle calculation all sides known
I know I should do my homework on my own but I simply can't get my homework to work the way I want it to: from __future__ import division import turtle import math def triangle(c,a,b,beta,gamma): turtle.forward(c) turtle.right(180+beta) turtle.forward(a) turtle.right(beta) turtle.left(beta+gamma) ...
[ "I think what you're looking for is the Law of Cosines, using acos and asin like you are presumes a right triangle.\n", "you can use law of cosines: c² = a² + b² - 2abcos(alpha)\n", "Old Indian Chief (as I was taught):\nSohCahToa\nSine = Opposite/Hypoteneuse\nCosine = Adjacent/Hypoteneuse\nTangent = Opposite/A...
[ 7, 1, 1 ]
[]
[]
[ "math", "python", "trigonometry" ]
stackoverflow_0001358584_math_python_trigonometry.txt
Q: Raising an exception on updating a 'constant' attribute in python As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #...
Raising an exception on updating a 'constant' attribute in python
As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this c...
[ "Customizing __setattr__ in every class (e.g. as exemplified in my old recipe that @ainab's answer is pointing to, and other answers), only works to stop assignment to INSTANCE attributes and not to CLASS attributes. So, none of the existing answers would actually satisfy your requirement as stated.\nIf what you a...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "attributes", "constants", "exception", "python" ]
stackoverflow_0001358711_attributes_constants_exception_python.txt
Q: Wildcard Downloads with Python How can I download files from a website using wildacrds in Python? I have a site that I need to download file from periodically. The problem is the filenames change each time. A portion of the file stays the same though. How can I use a wildcard to specify the unknown portion of ...
Wildcard Downloads with Python
How can I download files from a website using wildacrds in Python? I have a site that I need to download file from periodically. The problem is the filenames change each time. A portion of the file stays the same though. How can I use a wildcard to specify the unknown portion of the file in a URL?
[ "If the filename changes, there must still be a link to the file somewhere (otherwise nobody would ever guess the filename). A typical approach is to get the HTML page that contains a link to the file, search through that looking for the link target, and then send a second request to get the actual file you're afte...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001359090_python.txt
Q: Generate two lists at once Background The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then th...
Generate two lists at once
Background The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then the analytics have to stripe the t...
[ "Just use a for loop:\naprime = []\nbprime = []\nfor a1, b1, c1 in zip(a, b, c):\n if c1 == 0:\n aprime.append(a1) \n bprime.append(b1) \n\n", "This might win the ugliest code award, but it works in one line:\naprime, bprime = zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0])\n\n", "There's n...
[ 4, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001359232_python.txt
Q: Global hotkey for Python application in Gnome I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-) A: There is python-keybinder which is that same code, but packaged standalone. Also availa...
Global hotkey for Python application in Gnome
I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-)
[ "There is python-keybinder which is that same code, but packaged standalone. Also available in debian and ubuntu repositories now.\nhttps://github.com/engla/keybinder\n", "Check out the Deskbar source code - they do this; afaik, they call out a C library that interacts with X11 to do the job\n" ]
[ 9, 2 ]
[]
[]
[ "gnome", "python" ]
stackoverflow_0000302163_gnome_python.txt
Q: Killing the background window when running a .exe from a Python program the following is a line from a python program that calls the "demo.exe" file. a window for demo.exe opens when it is called, is there any way for demo.exe to run in the "background"? that is, i don't want the window for it show, i just want de...
Killing the background window when running a .exe from a Python program
the following is a line from a python program that calls the "demo.exe" file. a window for demo.exe opens when it is called, is there any way for demo.exe to run in the "background"? that is, i don't want the window for it show, i just want demo.exe to run. p = subprocess.Popen(args = "demo.exe", stdout = subprocess.P...
[ "Thanks to another StackOverflow thread, I think this is what you need:\nstartupinfo = subprocess.STARTUPINFO()\nstartupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\np = subprocess.Popen(args = \"demo.exe\", stdout=subprocess.PIPE, startupinfo=startupinfo)\n\nI tested on my Python 2.6 on XP and it does indeed hi...
[ 4, 3 ]
[]
[]
[ "executable", "python" ]
stackoverflow_0001360066_executable_python.txt
Q: Python/Suds: Type not found: 'xs:complexType' I have the following simple python test script that uses Suds to call a SOAP web service (the service is written in ASP.net): from suds.client import Client url = 'http://someURL.asmx?WSDL' client = Client( url ) result = client.service.GetPackageDetails( "MyPackage...
Python/Suds: Type not found: 'xs:complexType'
I have the following simple python test script that uses Suds to call a SOAP web service (the service is written in ASP.net): from suds.client import Client url = 'http://someURL.asmx?WSDL' client = Client( url ) result = client.service.GetPackageDetails( "MyPackage" ) print result When I run this test script I a...
[ "Ewall's resource is a good one. If you try to search in suds trac tickets, you could see that other people have problems similar to yours, but with different object types. It can be a good way to learn from it's examples and how they import their namespaces.\n\nThe problem is that your wsdl contains\n a schema de...
[ 14 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0001329190_python_soap_suds.txt
Q: Can Selenium RC tests written in Python be integrated into PHPUnit? I'm working on large project in PHP and I'm running phpundercontrol with PHPUnit for my unit tests. I would like to use Selenium RC for running acceptance tests. Unfortunately the only person I have left to write tests only knows Python. Can Sel...
Can Selenium RC tests written in Python be integrated into PHPUnit?
I'm working on large project in PHP and I'm running phpundercontrol with PHPUnit for my unit tests. I would like to use Selenium RC for running acceptance tests. Unfortunately the only person I have left to write tests only knows Python. Can Selenium tests written in Python be integrated into PHPUnit? Thanks!
[ "The only thing that comes to my mind is running them through the shell.\nIt would be:\n<?php\n$output = shell_exec('python testScript.py');\necho $output;\n?>\n\nIt's not too integrated with phpunit, but once you get the output in a variable ($output), you can then parse the text inside it to see if you have \"E\"...
[ 1 ]
[]
[]
[ "phpunit", "python", "selenium" ]
stackoverflow_0001350114_phpunit_python_selenium.txt
Q: Generating a list from complex dictionary I have a dictionary dict1['a'] = [ [1,2], [3,4] ] and need to generate a list out of it as l1 = [2, 4]. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as dict1['a'] = [2,4]. A: Given a list: ...
Generating a list from complex dictionary
I have a dictionary dict1['a'] = [ [1,2], [3,4] ] and need to generate a list out of it as l1 = [2, 4]. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as dict1['a'] = [2,4].
[ "Given a list:\n>>> lst = [ [1,2], [3,4] ]\n\nYou can extract the second element of each sublist with a simple list comprehension:\n>>> [x[1] for x in lst]\n[2, 4]\n\nIf you want to do this for every value in a dictionary, you can iterate over the dictionary. I'm not sure exactly what you want your final data to l...
[ 8, 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001360507_python_python_3.x.txt
Q: How to make custom buttons in wx? I'd like to make a custom button in wxPython. Where should I start, how should I do it? A: Here is a skeleton which you can use to draw totally custom button, its up to your imagination how it looks or behaves class MyButton(wx.PyControl): def __init__(self, parent, id, bmp...
How to make custom buttons in wx?
I'd like to make a custom button in wxPython. Where should I start, how should I do it?
[ "Here is a skeleton which you can use to draw totally custom button, its up to your imagination how it looks or behaves\nclass MyButton(wx.PyControl):\n\n def __init__(self, parent, id, bmp, text, **kwargs):\n wx.PyControl.__init__(self,parent, id, **kwargs)\n\n self.Bind(wx.EVT_LEFT_DOWN, self._on...
[ 8, 5, 3, 2 ]
[]
[]
[ "button", "python", "wxpython" ]
stackoverflow_0001351448_button_python_wxpython.txt
Q: Why does namespace after method call changes? I'm creating a class, but having some trouble with the namespacing in python. You can see the code below, and it mostly works ok, but after the call to guiFrame._stateMachine() the time module is somehow not defined anymore. If I re-import the time module in _stateMach...
Why does namespace after method call changes?
I'm creating a class, but having some trouble with the namespacing in python. You can see the code below, and it mostly works ok, but after the call to guiFrame._stateMachine() the time module is somehow not defined anymore. If I re-import the time module in _stateMachine() it works. But why is the time module not in t...
[ "Why do you assign to time? You can't use it as local variable, it will overshadow the module! If you look closely it complains that you use time before you assign to it -- since to use it as a local variable in _stateMachine.\ntime = 4\n\n", "You seem to use time as a variable. What happens here:\n\n\"C:\\Script...
[ 7, 2, 2 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0001361393_namespaces_python.txt
Q: KeyboardInterrupt in Windows? How to generate a KeyboardInterrupt in Windows? while True: try: print 'running' except KeyboardInterrupt: break I expected CTRL+C to stop this program but it doesn't work. A: Your code is working ok when ran into a windows console. Ctrl+C generating a Key...
KeyboardInterrupt in Windows?
How to generate a KeyboardInterrupt in Windows? while True: try: print 'running' except KeyboardInterrupt: break I expected CTRL+C to stop this program but it doesn't work.
[ "Your code is working ok when ran into a windows console.\nCtrl+C generating a KeyboardInterrupt is a console feature. If you run it from a text editor like SciTE, it will not work.\n" ]
[ 2 ]
[]
[]
[ "keyboardinterrupt", "python", "windows" ]
stackoverflow_0001361217_keyboardinterrupt_python_windows.txt
Q: stop python object going out of scope in c++ Is there a way to transfer a new class instance (python class that inherits c++ class) into c++ with out having to hold on to the object return and just treat it as a c++ pointer. For example: C++ object pyInstance = GetLocalDict()["makeNewGamePlay"](); CGEPYGameMode* m...
stop python object going out of scope in c++
Is there a way to transfer a new class instance (python class that inherits c++ class) into c++ with out having to hold on to the object return and just treat it as a c++ pointer. For example: C++ object pyInstance = GetLocalDict()["makeNewGamePlay"](); CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( pyInstance...
[ "You must increment the reference count of the pyInstance. That will prevent Python from deleting it. When you are ready to delete it, you can simply decrement the reference count and Python will clean it up for you.\n" ]
[ 2 ]
[]
[]
[ "boost", "c++", "object", "python" ]
stackoverflow_0001361028_boost_c++_object_python.txt
Q: IMAP interface access to existing user messaging system in Python I am running a site where users can private message each other. As with any other such website, to read and mark their messages, users must log on to the site. I wish to expose an IMAP interface so that users may read their site messages using their...
IMAP interface access to existing user messaging system in Python
I am running a site where users can private message each other. As with any other such website, to read and mark their messages, users must log on to the site. I wish to expose an IMAP interface so that users may read their site messages using their standard email client. There would be few complications in such approa...
[ "Twisted Mail project:\n\nTwisted Mail contains high-level, efficient protocol implementations for both clients and servers of SMTP, POP3, and IMAP4. Additionally, it contains an \"out of the box\" combination SMTP/POP3 virtual-hosting mail server. Also included is a read/write Maildir implementation and a basic Ma...
[ 1 ]
[]
[]
[ "imap", "interface", "python" ]
stackoverflow_0001361671_imap_interface_python.txt
Q: Match multiple patterns in a multiline string I have some data which look like that: PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be ...
Match multiple patterns in a multiline string
I have some data which look like that: PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to gui...
[ "How about:\nimport re\nreg4 = re.compile(r'^(?:PMID- (?P<pmid>[0-9]+)|TI - (?P<title>.*?)^PG|AB - (?P<abstract>.*?)^AD)', re.MULTILINE | re.DOTALL)\nfor i in reg4.finditer(data):\n print i.groupdict()\n\nOutput:\n{'pmid': '19587274', 'abstract': None, 'title': None}\n{'pmid': None, 'abstract': None, 'title': ...
[ 2, 2, 0, 0 ]
[ "The problem were the greedy qualifiers. Here's a regex that is more specific, and non-greedy:\n#!/usr/bin/python\nimport re\nfrom pprint import pprint\ndata = open(\"testdata.txt\").read()\n\nreg4 = r'''\n ^PMID # Start matching at the string PMID\n \\s*?- # As little whitespace as ...
[ -1 ]
[ "python", "regex" ]
stackoverflow_0001361373_python_regex.txt
Q: Why saving of MSWord document can silently fail? I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file: import win32com.client MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = False doc = MSWord.Documents.Open(file) doc.Cust...
Why saving of MSWord document can silently fail?
I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file: import win32com.client MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = False doc = MSWord.Documents.Open(file) doc.CustomDocumentProperties('Some Property').Value = 'Some Ne...
[ "You were using the CustomDocumentProperties in the wrong way, and as other people pointed out, you could not see it, because you were swallowing the exception.\nMoreover - and here I could not find anything in the documentation - the Saved property was not reset while changing properties, and for this reason the f...
[ 3, 1, 0, 0 ]
[]
[]
[ "automation", "ms_word", "ole", "python" ]
stackoverflow_0001340950_automation_ms_word_ole_python.txt
Q: Is it safe to rely on condition evaluation order in if statements? Is it bad practice to use the following format when my_var can be None? if my_var and 'something' in my_var: #do something The issue is that 'something' in my_var will throw a TypeError if my_var is None. Or should I use: if my_var: if 'so...
Is it safe to rely on condition evaluation order in if statements?
Is it bad practice to use the following format when my_var can be None? if my_var and 'something' in my_var: #do something The issue is that 'something' in my_var will throw a TypeError if my_var is None. Or should I use: if my_var: if 'something' in my_var: #do something or try: if 'something' i...
[ "It's safe to depend on the order of conditionals (Python reference here), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.\nThis sort of code pops up in most languages:\nIF exists(variable) AND variabl...
[ 104, 41, 4, 2, 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0000752373_if_statement_python.txt
Q: How to unload a .NET assembly reference in IronPython After loading a reference to an assembly with something like: import clr clr.AddRferenceToFileAndPath(r'C:\foo.dll') How can I unload the assembly again? Why would anyone ever want to do this? Because I'm recompiling foo.dll and want to reload it, but the comp...
How to unload a .NET assembly reference in IronPython
After loading a reference to an assembly with something like: import clr clr.AddRferenceToFileAndPath(r'C:\foo.dll') How can I unload the assembly again? Why would anyone ever want to do this? Because I'm recompiling foo.dll and want to reload it, but the compiler is giving me a fuss, since IronPython is allready acce...
[ ".NET itself doesn't support unloading just a single assembly. Instead, you need to unload a whole AppDomain. I don't know exactly how IronPython works with AppDomains, but that's the normal .NET way of doing things. (Load the assembly into a new AppDomain, use it, discard the AppDomain, create a new AppDomain with...
[ 6 ]
[]
[]
[ ".net", "ironpython", "python", "python.net" ]
stackoverflow_0001362114_.net_ironpython_python_python.net.txt
Q: Django : save a new value in a ManyToManyField I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling save_model, but I'm not sure). class PostAdmin(admin.ModelAdmin): def save_model(self, request, post, form, change): post.save() # Authors...
Django : save a new value in a ManyToManyField
I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling save_model, but I'm not sure). class PostAdmin(admin.ModelAdmin): def save_model(self, request, post, form, change): post.save() # Authors must be saved after saving post print form....
[ "You need to save the post again, after the post.authors.add(authors). \n", "I found the solution. I've just changed the value in cleaned_data and it works :\nif not form.cleaned_data['authors']:\n form.cleaned_data['authors'] = [request.user]\n\nThank for helping me. :)\n", "I don't know what kind of field ...
[ 2, 1, 0 ]
[]
[]
[ "add", "django", "manytomanyfield", "python", "save" ]
stackoverflow_0001356761_add_django_manytomanyfield_python_save.txt
Q: Django: how to retrieve an object selected by the ``object_detail`` generic view? Hi (sorry for my ugly english) I wonder if this is possible to retrieve an object which was selected with the object_detail generic view. For example : from django.views.generic.list_detail import object_detail def my_view(request, s...
Django: how to retrieve an object selected by the ``object_detail`` generic view?
Hi (sorry for my ugly english) I wonder if this is possible to retrieve an object which was selected with the object_detail generic view. For example : from django.views.generic.list_detail import object_detail def my_view(request, slug) response = object_detail(request, MyModel.objects.all(), slug=slug, ...
[ "You can't get the object this way, since object_detail simply returns a rendered response. If you need it, you'll just have to get it manually:\nobject = MyModel.objects.get(slug=slug)\n\n" ]
[ 5 ]
[]
[]
[ "django", "generics", "python", "view" ]
stackoverflow_0001362782_django_generics_python_view.txt
Q: Encapsulation severely hurts performance? I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test: def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_...
Encapsulation severely hurts performance?
I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test: def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): ...
[ "Function call overheads are not big; you won't normally notice them. You only see them in this case because your actual code (x*x) is itself so completely trivial. In any real program that does real work, the amount of time spent in function-calling overhead will be negligably small.\n(Not that I'd really recommen...
[ 6, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0001362997_performance_python.txt
Q: Python version shipping with Mac OS X Snow Leopard? I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version") Thanks! A: It ships with both python 2.6.1 and 2.5.4. $ python2.5 Python 2.5.4 (...
Python version shipping with Mac OS X Snow Leopard?
I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version") Thanks!
[ "It ships with both python 2.6.1 and 2.5.4.\n\n$ python2.5\nPython 2.5.4 (r254:67916, Jul 7 2009, 23:51:24)\n$ python\nPython 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)\n\n", "bot:nasuni jesse$ python\nPython 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\",...
[ 12, 5, 3, 3, 1 ]
[]
[]
[ "macos", "osx_snow_leopard", "python" ]
stackoverflow_0001347376_macos_osx_snow_leopard_python.txt
Q: calling vb dll in python So I have a function in vb that is converted to a dll that I want to use in python. However trying to use it, I get an error message this is the VB function Function DISPLAYNAME(Name) MsgBox ("Hello " & Name & "!") End Function and this is how I call it in python from ctypes import * tes...
calling vb dll in python
So I have a function in vb that is converted to a dll that I want to use in python. However trying to use it, I get an error message this is the VB function Function DISPLAYNAME(Name) MsgBox ("Hello " & Name & "!") End Function and this is how I call it in python from ctypes import * test = windll.TestDLL print test ...
[ "I dunno the answer to your specific question, but if it's VB.NET, you can natively call it in IronPython.\n", "It might be a scoping issue, with out the Public access modifier, the function may not be visible to external callers. Try\nPublic Function DISPLAYNAME(Name)\nMsgBox (\"Hello \" & Name & \"!\")\nEnd Fun...
[ 0, 0 ]
[]
[]
[ "dll", "python", "vb.net", "vb6" ]
stackoverflow_0001363305_dll_python_vb.net_vb6.txt
Q: Django newbie deployment question - ImportError: Could not import settings 'settings' The app runs fine using django internal server however when I use apache + mod_python I get the below error File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "C...
Django newbie deployment question - ImportError: Could not import settings 'settings'
The app runs fine using django internal server however when I use apache + mod_python I get the below error File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self...
[ "Your apache configuration should look like this:\n<Location \"/mysite\">\n SetHandler python-program\n PythonHandler django.core.handlers.modpython\n SetEnv DJANGO_SETTINGS_MODULE mysite.settings\n PythonOption django.root /mysite\n PythonPath \"['/root/djangoprojects/', '/root/djangoprojects/mysite...
[ 5, 0 ]
[]
[]
[ "deployment", "django", "mod_python", "python" ]
stackoverflow_0001216340_deployment_django_mod_python_python.txt
Q: Python singleton / object instantiation I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows: _Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.n...
Python singleton / object instantiation
I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows: _Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self...
[ "Assigning to an argument or any other local variable (barename) cannot ever, possibly have ANY effect outside the function; that applies to your self = whatever as it would to ANY other assignment to a (barename) argument or other local variable.\nRather, override __new__:\nclass Singleton(object):\n\n __instan...
[ 22, 6, 4, 3, 0 ]
[]
[]
[ "python", "singleton" ]
stackoverflow_0001363839_python_singleton.txt
Q: Invoking a method on an object Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this: PyObject* obj = .... PyObject* args = Py_BuildValue("(s)", "An arg"); PyObject* method = PyWHATGOESHERE(obj, "foo"); PyObject* ret = PyWHATGOESH...
Invoking a method on an object
Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this: PyObject* obj = .... PyObject* args = Py_BuildValue("(s)", "An arg"); PyObject* method = PyWHATGOESHERE(obj, "foo"); PyObject* ret = PyWHATGOESHERE(obj, method, args); if (!ret) { ...
[ "PyObject* obj = ....\nPyObject *ret = PyObject_CallMethod(obj, \"foo\", \"(s)\", \"An arg\");\nif (!ret) {\n // check error...\n}\n\nRead up on the Python C API documentation. In this case, you want the object protocol.\n\nPyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...)\n\nReturn valu...
[ 9, 3 ]
[]
[]
[ "c", "embedded_language", "python" ]
stackoverflow_0001364117_c_embedded_language_python.txt
Q: Python 3.1 inline division override I don't know if this is a bug in 3.1, but if I remember correctly "inline" division worked like this in pre-3k versions: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ...
Python 3.1 inline division override
I don't know if this is a bug in 3.1, but if I remember correctly "inline" division worked like this in pre-3k versions: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class A: ... def __init__(self, x): ....
[ "Gaaah! Found __floordiv__ and __truediv__. Sorry!\nIf you'd like to tell me why 2to3 doesn't translate __idiv__ into a __truediv__ with a __floordiv__(self, y): self.__truediv__(y), please go ahead!\n" ]
[ 6 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001364583_python_python_3.x.txt
Q: Python on Snow Leopard, how to open >255 sockets? Consider this code: import socket store = [] scount = 0 while True: scount+=1 print "Creating socket %d" % (scount) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) store.append(s) Gives the following result: Creating socket 1 Creating socket ...
Python on Snow Leopard, how to open >255 sockets?
Consider this code: import socket store = [] scount = 0 while True: scount+=1 print "Creating socket %d" % (scount) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) store.append(s) Gives the following result: Creating socket 1 Creating socket 2 ... Creating socket 253 Creating socket 254 Traceback...
[ "You can increase available sockets with ulimit. Looks like 1200 is the max for non-root users in bash. I can get up to 10240 with zsh.\n$ ulimit -n 1200\n$ python sockets\n....\nCreating socket 1197\nCreating socket 1198\nTraceback (most recent call last):\n File \"sockets\", line 7, in <module>\n File \"/System...
[ 17, 1 ]
[]
[]
[ "macos", "python", "sockets" ]
stackoverflow_0001364955_macos_python_sockets.txt
Q: Python packages depending on libxml2 and libxslt Apart from lxml, is anyone aware of Python packages that depend on libxml2 and libxslt? A: See e.g. the list here -- not exhaustive, as the page itself says, but a start.
Python packages depending on libxml2 and libxslt
Apart from lxml, is anyone aware of Python packages that depend on libxml2 and libxslt?
[ "See e.g. the list here -- not exhaustive, as the page itself says, but a start.\n" ]
[ 1 ]
[]
[]
[ "dependencies", "libxml2", "libxslt", "lxml", "python" ]
stackoverflow_0001365075_dependencies_libxml2_libxslt_lxml_python.txt
Q: Python generating Python I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on eff...
Python generating Python
I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experiment...
[ "We use Jinja2 to fill in a template. It's much simpler.\nThe template looks a lot like Python code with a few {{something}} replacements in it.\n", "This is pretty much the best way to generate Python source code. However, you can also generate Python executable code at runtime using the ast library. You can bu...
[ 35, 10, 7, 1, 1 ]
[]
[]
[ "code_generation", "python" ]
stackoverflow_0001364640_code_generation_python.txt
Q: Is storing user configuration settings on database OK? I'm building a fairly large enterprise application made in python that on its first version will require network connection. I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder. Some of the advant...
Is storing user configuration settings on database OK?
I'm building a fairly large enterprise application made in python that on its first version will require network connection. I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder. Some of the advantages I've thought of are: the user can change computers kee...
[ "This is pretty standard. Go for it.\nThe caveat is that when you take the database down for maintenance, no one can use the app because their profile is inaccessible. You can either solve that by making a 100%-on db solution, or, more easily, through some form of caching of profiles locally (an \"offline\" mode of...
[ 8, 5, 3, 3 ]
[]
[]
[ "database", "python", "settings" ]
stackoverflow_0001365164_database_python_settings.txt
Q: How to deal with user authentication and wrongful modification in scripting languages? I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechani...
How to deal with user authentication and wrongful modification in scripting languages?
I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial esp...
[ "How malicious are your users? Really.\nExactly how malicious?\nIf your users are evil sociopaths and can't be trusted with a desktop solution, then don't build a desktop solution. Build a web site.\nIf your users are ordinary users, they'll screw the environment up by installing viruses, malware and keyloggers f...
[ 3, 1 ]
[]
[]
[ "authentication", "cracking", "design_patterns", "python", "security" ]
stackoverflow_0001365254_authentication_cracking_design_patterns_python_security.txt
Q: python DST and GMT management into a scheduler I'm planning to write a sheduler app in python and I wouldn't be in trouble with DST and GMT handling. As example see also PHP related question 563053. Does anyone worked already on something similar? Does anyone already experienced with PyTZ - Python Time Zone Libr...
python DST and GMT management into a scheduler
I'm planning to write a sheduler app in python and I wouldn't be in trouble with DST and GMT handling. As example see also PHP related question 563053. Does anyone worked already on something similar? Does anyone already experienced with PyTZ - Python Time Zone Library?
[ "Sure, many of us have worked on calendars / schedulers and are familiar with pytz. What's your specific question, that's not already well answered in the SO question you point to and ITS answers / comments...?\nEdit: so there are no special, particular pitfalls if you do things as recommended in the best answers t...
[ 3, 3 ]
[]
[]
[ "calendar", "python", "time", "timezone", "utc" ]
stackoverflow_0001363692_calendar_python_time_timezone_utc.txt
Q: Anyone get python26 install in Snow Leopard via Macports? I got build error after run in Snow Leopard (MacPort v.1.8.0) sudo port install python26 any workaround please? Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org...
Anyone get python26 install in Snow Leopard via Macports?
I got build error after run in Snow Leopard (MacPort v.1.8.0) sudo port install python26 any workaround please? Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/mak...
[ "There are apparently problems with Python via Macports on Snow Leopard, see this thread. From there, here's an entry suggesting a way to get it working.\n" ]
[ 4 ]
[]
[]
[ "macports", "osx_snow_leopard", "python" ]
stackoverflow_0001366542_macports_osx_snow_leopard_python.txt
Q: Replace AppEngine Devserver With Spawning (BaseHTTPRequestHandler as WSGI) I'm looking to replace AppEngine's devserver with spawning. Spawning handles standard wsgi handlers, just like appengine, so running your app on it is easy. But the devserver takes into account your app.yaml file that has url redirects etc....
Replace AppEngine Devserver With Spawning (BaseHTTPRequestHandler as WSGI)
I'm looking to replace AppEngine's devserver with spawning. Spawning handles standard wsgi handlers, just like appengine, so running your app on it is easy. But the devserver takes into account your app.yaml file that has url redirects etc. I've been going through the devserver code and it is pretty easy to get the Bas...
[ "I don't think you're going to be able to pull out a part of the dev_appserver and use it in a custom WSGI server quite so easily. The dev_appserver does a lot of 'magic', and it isn't really structured to be pulled out and used as a WSGI wrapper in another server (more's the pity).\nYou may want to check out Twist...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "wsgi" ]
stackoverflow_0001293249_google_app_engine_python_wsgi.txt
Q: What would cause a zip file to not be recognized on Google App Engine's when it reads properly in my local GAE sdk My code executes successfully when I run it locally, but when I upload it to GAE and attempt to run it throws me a BadZipfile: File is not a zip file, or ends with a comment raw_file = urllib2.urlopen...
What would cause a zip file to not be recognized on Google App Engine's when it reads properly in my local GAE sdk
My code executes successfully when I run it locally, but when I upload it to GAE and attempt to run it throws me a BadZipfile: File is not a zip file, or ends with a comment raw_file = urllib2.urlopen(url) buffer = cStringIO.StringIO(raw_file.read()) z = zipfile.ZipFile(buffer) zipped file size is 2.5 mb unzipped size...
[ "The maximum size you can fetch using urlfetch (App Engine's API for making HTTP requests to other sites) is 1MB, so your file is getting truncated. The dev_appserver doesn't enforce the 1MB limit.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "zip" ]
stackoverflow_0001366274_google_app_engine_python_zip.txt
Q: How to download a webpage in every five minutes? I want to download a list of web pages. I know wget can do this. However downloading every URL in every five minutes and save them to a folder seems beyond the capability of wget. Does anyone knows some tools either in java or python or Perl which accomplishes the t...
How to download a webpage in every five minutes?
I want to download a list of web pages. I know wget can do this. However downloading every URL in every five minutes and save them to a folder seems beyond the capability of wget. Does anyone knows some tools either in java or python or Perl which accomplishes the task? Thanks in advance.
[ "Sounds like you'd want to use cron with wget\n\nBut if you're set on using python:\nimport time\nimport os\n\nwget_command_string = \"wget ...\"\n\nwhile true:\n os.system(wget_command_string)\n time.sleep(5*60)\n\n", "Write a bash script that uses wget and put it in your crontab to run every 5 minutes. (*...
[ 7, 5 ]
[]
[]
[ "download", "python", "web_crawler", "webpage", "wget" ]
stackoverflow_0001367189_download_python_web_crawler_webpage_wget.txt
Q: Diff django model objects with ManyToMany fields I have a situation where I need to notify some users when something in DB changes. My idea is to catch pre_save and post_save signal and make some kind of diff and mail that. Generally it works good, but I don't know how to get diff for m2m fields. At the moment I ...
Diff django model objects with ManyToMany fields
I have a situation where I need to notify some users when something in DB changes. My idea is to catch pre_save and post_save signal and make some kind of diff and mail that. Generally it works good, but I don't know how to get diff for m2m fields. At the moment I have something like this: def pre_save(sender, **kwarg...
[ "First of all, you don't need to use deepcopy for this. Re-querying the sender from the database returns a \"fresh\" object.\ndef pre_save(sender, **kwargs):\n pk = kwargs['instance'].pk\n instance = sender.objects.get(pk=pk)\n tracking[sender] = instance\n\nYou can get a list of all the many-to-many field...
[ 6 ]
[]
[]
[ "diff", "django", "models", "python" ]
stackoverflow_0001365963_diff_django_models_python.txt