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:
Getting python MySQLdb to run on Ubuntu
I created a virtualbox with a fresh install of ubuntu 9.10.
I am trying to get MySQLdb to run on python but I'm failing at the import MySQLdb
I first tried sudo easy_install MySQL_python-1.2.3c1-py2.6-linux-i686.egg and then sudo apt-get install python-mysqldb.
Both apparen... | Getting python MySQLdb to run on Ubuntu | I created a virtualbox with a fresh install of ubuntu 9.10.
I am trying to get MySQLdb to run on python but I'm failing at the import MySQLdb
I first tried sudo easy_install MySQL_python-1.2.3c1-py2.6-linux-i686.egg and then sudo apt-get install python-mysqldb.
Both apparently installed ok, but gave me the following e... | [
"Your MySQLdb egg installation looks like it is not working properly. You should go into /usr/local/lib/python2.6/dist-packages and remove it.\nThe Ubuntu python-mysqldb package should work fine. Unless you have a good reason, you should stick to your distribution's package manager when installing new software.\n"
... | [
7
] | [] | [] | [
"mysql",
"python",
"ubuntu_9.10"
] | stackoverflow_0002198260_mysql_python_ubuntu_9.10.txt |
Q:
no procedural code and non mvc in ruby and python?
i know that these 2 languages require oop.
but inside the classes, could you have procedural code?
and for the mvc part, that pattern comes with their frameworks right?
nothing to do with the actual language itself?
A:
Neither of these languages require OOP, esp... | no procedural code and non mvc in ruby and python? | i know that these 2 languages require oop.
but inside the classes, could you have procedural code?
and for the mvc part, that pattern comes with their frameworks right?
nothing to do with the actual language itself?
| [
"Neither of these languages require OOP, especially Python. In Python you can write as many ordinary functions as you want, and there are plenty of modules which don't define any classes. In Ruby you can do the same thing, except instead of functions you have methods on a module.\nYou are correct that MVC is rela... | [
4,
3
] | [] | [] | [
"model_view_controller",
"oop",
"python",
"ruby"
] | stackoverflow_0002198562_model_view_controller_oop_python_ruby.txt |
Q:
referencing static methods from class variable
I know it's wired to have such a case but somehow I have it:
class foo
#static method
@staticmethod
def test():
pass
# class variable
c = {'name' : <i want to reference test method here.>}
What's the way to it?
Just for the record:
I believe this shoul... | referencing static methods from class variable | I know it's wired to have such a case but somehow I have it:
class foo
#static method
@staticmethod
def test():
pass
# class variable
c = {'name' : <i want to reference test method here.>}
What's the way to it?
Just for the record:
I believe this should be considered as python worst practices. Using sta... | [
"class Foo:\n # static method\n @staticmethod\n def test():\n pass\n\n # class variable\n c = {'name' : test }\n\n",
"The problem is static methods in python are descriptor objects. So in the following code:\nclass Foo:\n # static method\n @staticmethod\n def test():\n pass\n... | [
5,
4
] | [] | [] | [
"class_variables",
"python",
"static_methods"
] | stackoverflow_0002194185_class_variables_python_static_methods.txt |
Q:
encoding mp3 from a audio stream of PyTTS
I work on text-to-speech trasforming text, in audio mp3 files, using python 2.5.
I use pyTSS as a python Text-To-Speech module, to transform text in audio .wav files (in pyTTS is not possible to encode in mp3 format directly). So after that, I code these wav files, in mp3 ... | encoding mp3 from a audio stream of PyTTS | I work on text-to-speech trasforming text, in audio mp3 files, using python 2.5.
I use pyTSS as a python Text-To-Speech module, to transform text in audio .wav files (in pyTTS is not possible to encode in mp3 format directly). So after that, I code these wav files, in mp3 format, using lame command line encoder.
Now, t... | [
"I don't think PyTTS produces default PCM data (i.e. 44100 Hz, stereo, 16-bit). You should check the format like this:\nmemStream = tts.SpeakToMemory(\"some text\")\nformat = memStream.Format.GetWaveFormatEx()\n\n...and hand it over correctly to acodec. Therefore you can use the attributes format.Channels, format.B... | [
1,
0
] | [] | [] | [
"encoder",
"mp3",
"python",
"text_to_speech"
] | stackoverflow_0002199151_encoder_mp3_python_text_to_speech.txt |
Q:
How do I turn a dictionary into a string?
params = {'fruit':'orange', 'color':'red', 'size':'5'}
How can I turn that into a string:
fruit=orange&color=red&size=5
A:
You can do it like this:
'&'.join('%s=%s' % (k,v) for k,v in params.items())
If you are building strings for a URL it would be better to use urlli... | How do I turn a dictionary into a string? | params = {'fruit':'orange', 'color':'red', 'size':'5'}
How can I turn that into a string:
fruit=orange&color=red&size=5
| [
"You can do it like this:\n'&'.join('%s=%s' % (k,v) for k,v in params.items())\n\nIf you are building strings for a URL it would be better to use urllib as this will escape correctly for you too:\n>>> params = { 'foo' : 'bar+baz', 'qux' : 'quux' }\n>>> urllib.urlencode(params)\n'qux=quux&foo=bar%2Bbaz'\n\n",
"If ... | [
11,
3,
3,
2
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0002199303_dictionary_python_string.txt |
Q:
Problem writing a database query
I have two models, Location and Event, that are linked by ForeignKey on the Event model. The models break down as follows:
class Location(models.Model):
city = models.CharField('city', max_length=25)
slug = models.SlugField('slug')
class Event(models.Model):
location =... | Problem writing a database query | I have two models, Location and Event, that are linked by ForeignKey on the Event model. The models break down as follows:
class Location(models.Model):
city = models.CharField('city', max_length=25)
slug = models.SlugField('slug')
class Event(models.Model):
location = models.ForeignKey(Location)
title... | [
"select id, (\n select * from event \n where location=location.id \n and start_date>NOW() \n order by start_date asc \n limit 1\n )\n from location\n\n",
"\"Ideally I would like to make this in a single query (I don't want to run a query for every location, as this would cause a lot of unnecessa... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0002198820_django_python_sql.txt |
Q:
matching multiple line in python regular expression
I want to extract the data between <tr> tags from an html page. I used the following code.But i didn't get any result. The html between the <tr> tags is in multiple lines
category =re.findall('<tr>(.*?)</tr>',data);
Please suggest a fix for this problem.
A:
ju... | matching multiple line in python regular expression | I want to extract the data between <tr> tags from an html page. I used the following code.But i didn't get any result. The html between the <tr> tags is in multiple lines
category =re.findall('<tr>(.*?)</tr>',data);
Please suggest a fix for this problem.
| [
"just to clear up the issue. Despite all those links to re.M it wouldn't work here as simple skimming of the its explanation would reveal. You'd need re.S, if you wouldn't try to parse html, of course:\n>>> doc = \"\"\"<table border=\"1\">\n <tr>\n <td>row 1, cell 1</td>\n <td>row 1, cell 2</td>\n ... | [
18,
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002199552_python.txt |
Q:
PyQt debugging in main loop
Can I debug PyQt application when is main loop running ?
Pdb, NetBeans, PyDev, all "freeze" when sys.exit(app.exec_()) is executed.
I probably missing something obvious. Or what can be problem, please ?
I apologize for my "creepy" english. Thanks.
A:
I'm assuming your main() function ... | PyQt debugging in main loop | Can I debug PyQt application when is main loop running ?
Pdb, NetBeans, PyDev, all "freeze" when sys.exit(app.exec_()) is executed.
I probably missing something obvious. Or what can be problem, please ?
I apologize for my "creepy" english. Thanks.
| [
"I'm assuming your main() function looks something like this:\ndef __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n myapp = MyApplication()\n myapp.show()\n sys.exit(app.exec_())\n\nIf not, post some example code to help determine what coudl be wrong.\nIf that is what your code looks like,... | [
1
] | [] | [] | [
"debugging",
"pyqt",
"python"
] | stackoverflow_0002199703_debugging_pyqt_python.txt |
Q:
pydoc fails under Windows and Python 2.6.4
When trying to use pydoc under Windows and python.org 2.6.4 I get the following error:
C:\>pydoc sys
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "C:\programs\Python26\Lib\pydoc.py", line 55, in ?
import sys, imp, os, re, types,... | pydoc fails under Windows and Python 2.6.4 | When trying to use pydoc under Windows and python.org 2.6.4 I get the following error:
C:\>pydoc sys
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "C:\programs\Python26\Lib\pydoc.py", line 55, in ?
import sys, imp, os, re, types, inspect, __builtin__, pkgutil
File "C:\progra... | [
"Typical windows problem: I had a program installed lately which brought its own Python 2.4. This installation overwrote the Windows file handlers for python scripts, but did not appear on the PATH. So scripts started from the console ran in the old-version python, but calling \"python\" ran the 2.6 version.\nThx t... | [
2,
0
] | [] | [] | [
"pydoc",
"python"
] | stackoverflow_0002199739_pydoc_python.txt |
Q:
extend Python namedtuple with many @properties?
How can namedtuples be extended or subclassed with many additional @properties ?
For a few, one can just write the text below; but there are many,
so I'm looking for a generator or property factory.
One way would be to generate text from _fields and exec it;
another ... | extend Python namedtuple with many @properties? | How can namedtuples be extended or subclassed with many additional @properties ?
For a few, one can just write the text below; but there are many,
so I'm looking for a generator or property factory.
One way would be to generate text from _fields and exec it;
another would be an add_fields with the same effect at runtim... | [
"The answer to your question\n\nHow can namedtuples be extended or\n subclassed with additional @properties\n ?\n\nis: exactly the way you're doing it! What error are you getting? To see a simpler case,\n>>> class x(collections.namedtuple('y', 'a b c')):\n... @property\n... def d(self): return 23\n... \n>>>... | [
18,
2
] | [
"Here's one approach, a little language: \nturn this into Python text like the above, and exec it.\n(Expanding text-to-text is easy to do, and easy to test —\nyou can look at the intermediate text.)\nI'm sure there are similar if not-so-little such, links please ?\n# example of a little language for describing mult... | [
-1
] | [
"namedtuple",
"properties",
"python"
] | stackoverflow_0002193009_namedtuple_properties_python.txt |
Q:
In Django, my request.session is not carrying over...does anyone know why?
In one view, I set:
request.session.set_expiry(999)
request.session['test'] = '123'
In another view, I do:
print request.session['test']
and it cannot be found. (error)
It's very simple, I just have 2 views.
It seems that once I leave a v... | In Django, my request.session is not carrying over...does anyone know why? | In one view, I set:
request.session.set_expiry(999)
request.session['test'] = '123'
In another view, I do:
print request.session['test']
and it cannot be found. (error)
It's very simple, I just have 2 views.
It seems that once I leave a view and come back to it...it's gone! Why?
| [
"Could it be related to this?, just found it at http://code.djangoproject.com/wiki/NewbieMistakes\nAppending to a list in session doesn't work \nProblem \nIf you have a list in your session, append operations don't get saved to the object.\nSolution \nCopy the list out of the session object, append to it, then copy... | [
18,
1
] | [] | [] | [
"django",
"python",
"session"
] | stackoverflow_0002199150_django_python_session.txt |
Q:
Images caching in browser - app-engine-patch application
I have a little problem with caching the images in the browser for my app-engine application
I`m sending last-modified, expires and cache-control headers but image is loaded from the server every time.
Here is the header part of the code:
response['Content-T... | Images caching in browser - app-engine-patch application | I have a little problem with caching the images in the browser for my app-engine application
I`m sending last-modified, expires and cache-control headers but image is loaded from the server every time.
Here is the header part of the code:
response['Content-Type'] = 'image/jpg'
response['Last-Modified'] = current_time.s... | [
"Here is an example code for my fix copy in dpaste here\ndef view_image(request, key):\n data = memcache.get(key) \n if data is not None: \n if(request.META.get('HTTP_IF_MODIFIED_SINCE') >= data['Last-Modified']): \n data.status_code = 304 \n return data \n else: \n image_content_blob = #some... | [
7
] | [] | [] | [
"app_engine_patch",
"browser",
"caching",
"google_app_engine",
"python"
] | stackoverflow_0002185449_app_engine_patch_browser_caching_google_app_engine_python.txt |
Q:
Access contents of PyBuffer from C
I have created a buffer object in python like so:
f = io.open('some_file', 'rb')
byte_stream = buffer(f.read(4096))
I'm now passing byte_stream as a parameter to a C function, through SWIG. I have a typemap for converting the data which looks like this:
%typemap(in) unsigned cha... | Access contents of PyBuffer from C | I have created a buffer object in python like so:
f = io.open('some_file', 'rb')
byte_stream = buffer(f.read(4096))
I'm now passing byte_stream as a parameter to a C function, through SWIG. I have a typemap for converting the data which looks like this:
%typemap(in) unsigned char * byte_stream {
PyObject *buf = $i... | [
"\nI'm using buffers because I want to\n avoid the overhead of converting the\n data to a string when reading it from\n the file\n\nYou are not avoiding anything. The string is already built by the read() method. Calling buffer() just builds an additional buffer object pointing to that string.\nAs for getting at... | [
2,
1
] | [] | [] | [
"pybuffer",
"python",
"python_c_api",
"swig"
] | stackoverflow_0002128195_pybuffer_python_python_c_api_swig.txt |
Q:
which is more efficient for buffer manipulations: python strings or array()
I am building a routine that processes disk buffers for forensic purposes. Am I better off using python strings or the array() type? My first thought was to use strings, but I'm trying to void unicode problems, so perhaps array('c') is bet... | which is more efficient for buffer manipulations: python strings or array() | I am building a routine that processes disk buffers for forensic purposes. Am I better off using python strings or the array() type? My first thought was to use strings, but I'm trying to void unicode problems, so perhaps array('c') is better?
| [
"Write the code using what is most natural (strings), find out if it's too slow and then improve it. \nArrays can be used as drop-in replacements for str in most cases, as long as you restrict yourself to index and slice access. Both are fixed-length. Both should have about the same memory requirements. Arrays are ... | [
9,
6
] | [] | [] | [
"arrays",
"performance",
"python"
] | stackoverflow_0002200027_arrays_performance_python.txt |
Q:
How bad is it to override a method from a third-party module?
How bad is it to redefine a class method from another, third-party module, in Python?
In fact, users can create NumPy matrices that contain numbers with uncertainty; ideally, I would like their code to run unmodified (compared to when the code manipulat... | How bad is it to override a method from a third-party module? | How bad is it to redefine a class method from another, third-party module, in Python?
In fact, users can create NumPy matrices that contain numbers with uncertainty; ideally, I would like their code to run unmodified (compared to when the code manipulates float matrices); in particular, it would be great if the inverse... | [
"Subclassing (which does involve overriding, as the term is generally used) is generally much preferable to \"monkey-patching\" (stuffing altered methods into existing classes or modules), even when the latter is available (built-in types, meaning ones implemented in C, can protect themselves against monkey-patchin... | [
12,
1,
1
] | [] | [] | [
"numpy",
"overriding",
"python"
] | stackoverflow_0002200880_numpy_overriding_python.txt |
Q:
Terracotta for Python world?
Would you know if something similar to Terracotta (in Java world) exists for Python world? Twisted ? Or something else.
A:
I think Twisted is the best alternative you can find.
Let me warn you that it will give you some headaches, as it forces you to code in a completely different wa... | Terracotta for Python world? | Would you know if something similar to Terracotta (in Java world) exists for Python world? Twisted ? Or something else.
| [
"I think Twisted is the best alternative you can find.\nLet me warn you that it will give you some headaches, as it forces you to code in a completely different way. But once you understand it, it's not that hard....\nhttp://twistedmatrix.com/projects/core/documentation/howto/index.html\n",
"Pyro can be used simi... | [
1,
1,
0,
0
] | [] | [] | [
"java",
"python",
"terracotta"
] | stackoverflow_0001393689_java_python_terracotta.txt |
Q:
Need code to get all files in directory and past another local?
i need code python to get all pic files in diretorie e paste another dir
for ex.
in "c:\capture" confirm exist pic files, if true get all and paste in c:\backup\paste.1
sleep 30 min and confirm new files in c:\capture if true get all and past in c:\b... | Need code to get all files in directory and past another local? | i need code python to get all pic files in diretorie e paste another dir
for ex.
in "c:\capture" confirm exist pic files, if true get all and paste in c:\backup\paste.1
sleep 30 min and confirm new files in c:\capture if true get all and past in c:\backup\paste.2
sorry my bad english
tks
| [
"I'm not sure what exactly you want to do, by are you looking for os.listdir(), os.rename() and the other functions of the os module?\nThe shutil module might also be useful, depending on the specifics of what you want to do.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002201173_python.txt |
Q:
Does a library to prevent duplicate form submissions exist for django?
I am trying to find a way to prevent users from double-submitting my forms. I have javascript that disables the submit button, but there is still an occasional user who finds a way to double-submit.
I have a vision of a re-usable library that... | Does a library to prevent duplicate form submissions exist for django? | I am trying to find a way to prevent users from double-submitting my forms. I have javascript that disables the submit button, but there is still an occasional user who finds a way to double-submit.
I have a vision of a re-usable library that I could create to protect from this.
In my ideal library, the code block w... | [
"You can use a session to store the hash \nimport hashlib\n\ndef contact(request):\n if request.method == 'POST':\n form = MyForm(request.POST)\n #join all the fields in one string\n hashstring=hashlib.sha1(fieldsstring)\n if request.session.get('sesionform')!=hashstring:\n ... | [
12,
6,
3,
3,
2
] | [] | [] | [
"code_reuse",
"django",
"python"
] | stackoverflow_0002136954_code_reuse_django_python.txt |
Q:
How do I access my classes from the python console on MAC OSX?
I'm trying to access my classes via
from project import *
But from the python console something seems to be off with the paths. How do I set the correct paths to my project so I can import classes?
My models are stored in:
/Users/username/project/... | How do I access my classes from the python console on MAC OSX? | I'm trying to access my classes via
from project import *
But from the python console something seems to be off with the paths. How do I set the correct paths to my project so I can import classes?
My models are stored in:
/Users/username/project/project/model
from project import *
And the error reads:
ImportErr... | [
"You have the following choices\n\nStart your python session in the /User/username/project folder\nChange your import line to from project.project import *\nSet the PYTHONPATH environment variable to /User/username/project (setenv PYTHONPATH /User/username/project)\nAppend /User/username/project to sys.path\n\nimpo... | [
4,
1,
1
] | [] | [] | [
"macos",
"pylons",
"python"
] | stackoverflow_0002201461_macos_pylons_python.txt |
Q:
Replace newlines in a Unicode string
I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.
My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a db.StringProperty() in my model.
So I do something like:
link.title = u... | Replace newlines in a Unicode string | I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.
My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a db.StringProperty() in my model.
So I do something like:
link.title = unicode(page_title,"utf-8").replace('\n',''... | [
"Try ''.join(unicode(page_title, 'utf-8').splitlines()). splitlines() should let the standard library take care of all the possible crazy Unicode line breaks, and then you just join them all back together with the empty string to get a single-line version.\n",
"Python uses these characters for splitting in unicod... | [
22,
11,
0
] | [] | [] | [
"google_app_engine",
"python",
"unicode"
] | stackoverflow_0002201633_google_app_engine_python_unicode.txt |
Q:
How to actually build 64-bit Python on OS X 10.6.2
Why? I want to do this because installation of SciPy recommends it, and I thought it would be a good learning experience. This question has been asked before (e.g. here). The preferred answer seems to be to use MacPorts, but as I say, I'd like to understand how... | How to actually build 64-bit Python on OS X 10.6.2 | Why? I want to do this because installation of SciPy recommends it, and I thought it would be a good learning experience. This question has been asked before (e.g. here). The preferred answer seems to be to use MacPorts, but as I say, I'd like to understand how it's done.
Anyway, I grab the source (Python-2.6.4.tgz)... | [
"Your ./configure option is not correct. --enable-universalsdk should be set to the correct SDK, not /! \nThat's why gcc got confused, see the option -isysroot.\nSo, check what SDKs you have in /Developer/SDKs, and set the correct one.\nMoreover, your gcc is called only with -arch ppc -arch i386, which do not inclu... | [
1,
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0002177705_macos_python.txt |
Q:
Implementing preg_match_all in Python
I basically want the same functionality of preg_match_all()from PHP in a Python way.
If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?
Example:
s = "superc... | Implementing preg_match_all in Python | I basically want the same functionality of preg_match_all()from PHP in a Python way.
If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?
Example:
s = "supercalifragilisticexpialidocious"
Would return... | [
"You can do this faster without regexp\n[(x,i) for i,x in enumerate(s) if x in \"aeiou\"]\n\nHere are some timings:\nFor s = \"supercalifragilisticexpialidocious\"\ntimeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]\n10000 loops, best of 3: 27.5 µs per loop\n\ntimeit [(x,i) for i,x in enumerate(s) i... | [
6,
5,
0
] | [] | [] | [
"php",
"python",
"regex"
] | stackoverflow_0002202360_php_python_regex.txt |
Q:
How to catch 404 error in urllib.urlretrieve
Background: I am using urllib.urlretrieve, as opposed to any other function in the urllib* modules, because of the hook function support (see reporthook below) .. which is used to display a textual progress bar. This is Python >=2.6.
>>> urllib.urlretrieve(url[, filenam... | How to catch 404 error in urllib.urlretrieve | Background: I am using urllib.urlretrieve, as opposed to any other function in the urllib* modules, because of the hook function support (see reporthook below) .. which is used to display a textual progress bar. This is Python >=2.6.
>>> urllib.urlretrieve(url[, filename[, reporthook[, data]]])
However, urlretrieve is... | [
"Check out urllib.urlretrieve's complete code:\ndef urlretrieve(url, filename=None, reporthook=None, data=None):\n global _urlopener\n if not _urlopener:\n _urlopener = FancyURLopener()\n return _urlopener.retrieve(url, filename, reporthook, data)\n\nIn other words, you can use urllib.FancyURLopener (it's par... | [
28,
15,
2
] | [] | [] | [
"http",
"python",
"url",
"urllib"
] | stackoverflow_0001308542_http_python_url_urllib.txt |
Q:
Python: deferToThread XMLRPC Server - Twisted - Cherrypy?
This question is related to others I have asked on here, mainly regarding sorting huge sets of data in memory.
Basically this is what I want / have:
Twisted XMLRPC server running. This server keeps several (32) instances of Foo class in memory. Each Foo c... | Python: deferToThread XMLRPC Server - Twisted - Cherrypy? | This question is related to others I have asked on here, mainly regarding sorting huge sets of data in memory.
Basically this is what I want / have:
Twisted XMLRPC server running. This server keeps several (32) instances of Foo class in memory. Each Foo class contains a list bar (which will contain several million re... | [
"The easiest way to get the app to be responsive is to break up the CPU-intensive processing in smaller chunks, while letting the twisted reactor run in between. For example by calling reactor.callLater(0, process_next_chunk) to advance to next chunk. Effectively implementing cooperative multitasking by yourself.\n... | [
1,
0
] | [] | [] | [
"cherrypy",
"multithreading",
"python",
"twisted"
] | stackoverflow_0002202231_cherrypy_multithreading_python_twisted.txt |
Q:
Yield multiple objects at a time from an iterable object?
How can I yield multiple items at a time from an iterable object?
For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?
A:
Your question is a bit vague, but c... | Yield multiple objects at a time from an iterable object? | How can I yield multiple items at a time from an iterable object?
For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?
| [
"Your question is a bit vague, but check out the grouper recipe in the itertools documentation.\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\n(Zipping the same iterator several t... | [
7,
2
] | [] | [] | [
"grouping",
"iterator",
"python",
"yield"
] | stackoverflow_0002202461_grouping_iterator_python_yield.txt |
Q:
S60 camera focusing
In my project I have to use mobile camera from my own program.
I use python with S60 platform under NOKIA 6220 Classic. It has 5mp-camera.
The problem is that photos quality are very-very low. Seems that auto-focusing doesn't work.
I'd like to know maybe anyone from you made something before. I... | S60 camera focusing | In my project I have to use mobile camera from my own program.
I use python with S60 platform under NOKIA 6220 Classic. It has 5mp-camera.
The problem is that photos quality are very-very low. Seems that auto-focusing doesn't work.
I'd like to know maybe anyone from you made something before. I can buy new telephone if... | [
"This is just a guess. Are you maybe getting low-res images that are suitable for sending via MMS? I would look at the API.\n"
] | [
0
] | [] | [] | [
"camera",
"python",
"s60"
] | stackoverflow_0002202991_camera_python_s60.txt |
Q:
Python: How do you call a method when you only have the string name of the method?
This is for use in a JSON API.
I don't want to have:
if method_str == 'method_1':
method_1()
if method_str == 'method_2':
method_2()
For obvious reasons this is not optimal. How would I use map strings to methods like this... | Python: How do you call a method when you only have the string name of the method? | This is for use in a JSON API.
I don't want to have:
if method_str == 'method_1':
method_1()
if method_str == 'method_2':
method_2()
For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in arguments to the called functions).... | [
"For methods of instances, use getattr\n>>> class MyClass(object):\n... def sayhello(self):\n... print \"Hello World!\"\n... \n>>> m=MyClass()\n>>> getattr(m,\"sayhello\")()\nHello World!\n>>> \n\nFor functions you can look in the global dict\n>>> def sayhello():\n... print \"Hello World!\"\n... \n>>> globals()... | [
25,
6,
6,
1
] | [] | [] | [
"api",
"json",
"python",
"serialization"
] | stackoverflow_0002203438_api_json_python_serialization.txt |
Q:
Distinguishing parent model's children with Django inheritance
Basically I have a Base class called "Program". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don't care whether or not a Program is one of the specific child types. Of course there's that 1% of ... | Distinguishing parent model's children with Django inheritance | Basically I have a Base class called "Program". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don't care whether or not a Program is one of the specific child types. Of course there's that 1% of the time that I do want to know if it's one of the children.
The pro... | [
"Have you tried hasattr()? Something like this:\nif hasattr(program, 'swimprogram'):\n # ...\nelif hasattr(program, 'campprogram'):\n # ...\n\nIf you are unsure about this approach, try it out in a simple test app first. Here are two simple models that should show if it will work for you and the version of ... | [
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002202232_django_python.txt |
Q:
Trouble with rdfstore with mysql - how to debug?
I have a mysql server running and can connect to it from my Django ORM. Can't connect using the rdflib functionality. How can I debug this problem? Thanks.
rdflib 2.4.2, python 2.6, MySQL Community 5.1.42
Trace:
configString = "host=localhost,user=root,password=.... | Trouble with rdfstore with mysql - how to debug? | I have a mysql server running and can connect to it from my Django ORM. Can't connect using the rdflib functionality. How can I debug this problem? Thanks.
rdflib 2.4.2, python 2.6, MySQL Community 5.1.42
Trace:
configString = "host=localhost,user=root,password=...,db=..."
print configString
host=localhost,user=r... | [
"I commented code in the rdflib/store directory in MySQL.py and now it all works:\n# test_db = MySQLdb.connect(user=configDict['user'],\n# passwd=configDict['password'],\n# db='test',\n# port=configDict['port'],\n# ... | [
1
] | [] | [] | [
"mysql",
"mysql_error_1049",
"python",
"rdflib",
"rdfstore"
] | stackoverflow_0002197157_mysql_mysql_error_1049_python_rdflib_rdfstore.txt |
Q:
Code Changes While Keeping Large Objects In Memory in Python
I have an application that starts by loading a large pickled trie (173M) from disk and then uses it to do some processing. I'm making frequent changes to the processing part, which is inconvenient because loading the trie takes 15 minutes or so. I'm lo... | Code Changes While Keeping Large Objects In Memory in Python | I have an application that starts by loading a large pickled trie (173M) from disk and then uses it to do some processing. I'm making frequent changes to the processing part, which is inconvenient because loading the trie takes 15 minutes or so. I'm looking for a way to eliminate the repeated loading during testing, ... | [
"You could try using Pythons built-in reload method or the livecoding project.\n",
"The usual problem with reload is that instances stay bound to the old version of the class. If you are not keeping old instances around, reload is simple and works very well.\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002203492_python.txt |
Q:
Is this a bug in Django or what? Logging out of the Django Authentication system...will remove all sessiosn?
I'm using sessions across my application.
And using logins.
When I do a simple:
#log out the user.
logout(request)
...the request.sessions get erased.
What is this??!
A:
If by request.sessions you mean r... | Is this a bug in Django or what? Logging out of the Django Authentication system...will remove all sessiosn? | I'm using sessions across my application.
And using logins.
When I do a simple:
#log out the user.
logout(request)
...the request.sessions get erased.
What is this??!
| [
"If by request.sessions you mean request.session, then it's a documented feature:\nhttp://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout\n",
"I believe the correct syntax is:\nlogout(request.user)\n\n"
] | [
4,
1
] | [] | [] | [
"django",
"python",
"session"
] | stackoverflow_0002203604_django_python_session.txt |
Q:
How do i set the PDU mode of a modem using python sms 0.3 module?
Am using python sms 0.3 module to access my modem on com port. Am trying to send an sms but am getting the following error
sms.ModemError: ['\r\n', '+CMS ERROR: 304\r\n']
When i read the Modem error codes, Error code 304 is for PDU mode, am just won... | How do i set the PDU mode of a modem using python sms 0.3 module? | Am using python sms 0.3 module to access my modem on com port. Am trying to send an sms but am getting the following error
sms.ModemError: ['\r\n', '+CMS ERROR: 304\r\n']
When i read the Modem error codes, Error code 304 is for PDU mode, am just wondering how do i set the mode using sms 0.3
Am using a USB modem, Huawei... | [
"Not sure if you can do it via the SMS library, but you can do it directly by sending via the serial port to the modem.:\n\"AT+CMGF=0\" sets PDU mode for SMS messages\n\"AT+CMGF=1\" sets text mode for SMS messages\n\"AT+CMGF?\" should give the current setting\n"
] | [
0
] | [] | [] | [
"modem",
"python",
"sms"
] | stackoverflow_0001415162_modem_python_sms.txt |
Q:
Python win32com: Excel set chart type to Line
This VBA macro works:
Sub Draw_Graph()
Columns("A:B").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=ActiveSheet.Range("$A:$B")
ActiveChart.ChartType = xlLine
End Sub
This Python (near) Equivalent almost works:
from win32co... | Python win32com: Excel set chart type to Line | This VBA macro works:
Sub Draw_Graph()
Columns("A:B").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=ActiveSheet.Range("$A:$B")
ActiveChart.ChartType = xlLine
End Sub
This Python (near) Equivalent almost works:
from win32com import client
excel=client.Dispatch("Excel.Appli... | [
"Needed to run the 'makepy.py' to get it to work.\nhttp://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html#UsingComConstants\n"
] | [
1
] | [] | [] | [
"charts",
"excel",
"python",
"python_2.6",
"win32com"
] | stackoverflow_0002204069_charts_excel_python_python_2.6_win32com.txt |
Q:
Loading Google App Engine app from one file for all the URLs or one file per URL for loading speed
I have a small web app running on AppEngine and have all my URL processing in one file and the other processing done in another file that is imported at the top of the main python.
e.g.
import wsgiref.handlers
from ... | Loading Google App Engine app from one file for all the URLs or one file per URL for loading speed | I have a small web app running on AppEngine and have all my URL processing in one file and the other processing done in another file that is imported at the top of the main python.
e.g.
import wsgiref.handlers
from wsgiref.handlers import format_date_time
import logging
import os
import cgi
import datetime
from time i... | [
"There's no need to split your handlers into separate files. However, if you're importing something that's going to use a lot of CPU when it's imported and won't be used by many of your handlers, it's best to move your imports inside your handler classes so you can take advantage of lazy loading.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"performance",
"python"
] | stackoverflow_0002203348_google_app_engine_performance_python.txt |
Q:
How can I optimize multiple nested SELECTs in SQLite (w/Python)?
I'm building a CGI script that polls a SQLite database and builds a table of statistics. The source database table is described below, as is the chunk of pertinent code. Everything works (functionally), but the CGI itself is very slow as I have multi... | How can I optimize multiple nested SELECTs in SQLite (w/Python)? | I'm building a CGI script that polls a SQLite database and builds a table of statistics. The source database table is described below, as is the chunk of pertinent code. Everything works (functionally), but the CGI itself is very slow as I have multiple nested SELECT COUNT(id) calls. I figure my best shot at optimizati... | [
"first of all you can use the group by clause:\nselect count(*), sender from messages group by sender;\n\nand with this you execute one query for all senders instead of on query for each sender. Another possibility could be:\nselect count(*), sender, day, hour\n from messages group by sender, day, hour\n orde... | [
3,
1
] | [] | [] | [
"optimization",
"perl",
"python",
"query_optimization",
"sqlite"
] | stackoverflow_0002203709_optimization_perl_python_query_optimization_sqlite.txt |
Q:
Python: defining new functions on the fly using "with"
I want to convert the following code:
...
urls = [many urls]
links = []
funcs = []
for url in urls:
func = getFunc(url, links)
funcs.append(func)
...
def getFunc(url, links):
def func():
page = open(url)
link = searchForLink(page)
l... | Python: defining new functions on the fly using "with" | I want to convert the following code:
...
urls = [many urls]
links = []
funcs = []
for url in urls:
func = getFunc(url, links)
funcs.append(func)
...
def getFunc(url, links):
def func():
page = open(url)
link = searchForLink(page)
links.append(link)
return func
into the much more conveni... | [
"It makes no sense to use with here. Instead use a list comprehension:\nfuncs = [getFunc(url, links) for url in urls]\n\n",
"A bit unconventional, but you can have a decorator register the func and bind any loop variables as default arguments:\nurls = [many urls]\nlinks = []\nfuncs = []\n\nfor url in urls:\n @... | [
6,
4,
2,
2,
1,
1,
1
] | [] | [] | [
"python",
"with_statement"
] | stackoverflow_0002200026_python_with_statement.txt |
Q:
What's a good web framework and/or tool for a software developer?
I'd like to make a website, it's not a huge project, but I'm a bit out of the web design loop. The last time I made a website was probably around 2002. I figure the web frameworks and tools have come a ways since then. It's mostly the design aspe... | What's a good web framework and/or tool for a software developer? | I'd like to make a website, it's not a huge project, but I'm a bit out of the web design loop. The last time I made a website was probably around 2002. I figure the web frameworks and tools have come a ways since then. It's mostly the design aspect that I'd like it to make easier. I can do the backend language in a... | [
"You'll get many different subjective answers for your question, but as for me I would recommend django. It is flexible unlike CMS and the admin saves you alot of pain.\n",
"For PHP, I like the CMS Drupal and have found it to be very fast in getting a site up and running. Drupal also has a ton of modules to do a... | [
5,
3,
1,
0,
0
] | [] | [] | [
"php",
"python",
"ruby"
] | stackoverflow_0002204223_php_python_ruby.txt |
Q:
Using a PFX Certificate to connect to an HTTP site
Here's the scenario: I need to connect to a web site to retrieve electronic lab results formatted in XML. In order to connect, I need to use a digital certificate.
I've been able to get a version of this working in Perl. It looks like this:
#!/usr/bin/env perl
... | Using a PFX Certificate to connect to an HTTP site | Here's the scenario: I need to connect to a web site to retrieve electronic lab results formatted in XML. In order to connect, I need to use a digital certificate.
I've been able to get a version of this working in Perl. It looks like this:
#!/usr/bin/env perl
use strict;
use WWW::Mechanize;
$|++;
my $username = 'x... | [] | [] | [
"I have no idea what is going on with your perl issues. However, mechanize for Python can be found here.\n"
] | [
-1
] | [
"certificate",
"perl",
"python",
"ssl"
] | stackoverflow_0002204252_certificate_perl_python_ssl.txt |
Q:
Error "Could not locate a bind configured on mapper" for SQLAlchemy and pylons
I'm not sure what I'm doing wrong here to warrant this message. Any help with my configuration would be appreciated.
"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm
from project.model import me... | Error "Could not locate a bind configured on mapper" for SQLAlchemy and pylons | I'm not sure what I'm doing wrong here to warrant this message. Any help with my configuration would be appreciated.
"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm
from project.model import meta
def now():
return datetime.datetime.now()
def init_model(engine):
"""Ca... | [
"This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:\nfrom paste.deploy import appconfig\nfrom pylons import config\n\nfrom project.config.environment import load_environment\n\nconf = appconfig('config:development.ini', relative_to='.')\nload_envir... | [
3
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002203496_pylons_python_sqlalchemy.txt |
Q:
I Keep receiving an "The MetaData is not bound to an Engine or Connection." when trying to create my SQL tables with pylons
Here is my current code:
def init_model(engine):
global t_user
t_user = sa.Table("User", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("name",... | I Keep receiving an "The MetaData is not bound to an Engine or Connection." when trying to create my SQL tables with pylons | Here is my current code:
def init_model(engine):
global t_user
t_user = sa.Table("User", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("name", sa.types.String(100), nullable=False),
sa.Column("first_name", sa.types.String(100), nullable=False),
sa.Column("last_na... | [
"This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:\nfrom paste.deploy import appconfig\nfrom pylons import config\n\nfrom project.config.environment import load_environment\n\nconf = appconfig('config:development.ini', relative_to='.')\nload_envir... | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002202927_pylons_python.txt |
Q:
Why am I getting an error about my class defining __slots__ when trying to pickle an object?
I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error:
>>> with open('temp/connection.pickle','w') as f:
... pickle.dump(c,f)
...
Traceback (most recent call last):
File... | Why am I getting an error about my class defining __slots__ when trying to pickle an object? | I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error:
>>> with open('temp/connection.pickle','w') as f:
... pickle.dump(c,f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.5/pickle.py", line 1362, in dump
Pick... | [
"The class defining __slots__ (and not __getstate__) can be either an ancestor class of yours, or a class (or ancestor class) of an attribute or item of yours, directly or indirectly: essentially, the class of any object in the directed graph of references with your object as root, since pickling needs to save the ... | [
32,
7,
2
] | [] | [] | [
"pickle",
"python",
"slots"
] | stackoverflow_0002204155_pickle_python_slots.txt |
Q:
How to isolate a single color in an image
I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish.
I tried to take only the red color channel but this includes the white spaces in the Image too.
What is a good way to do ... | How to isolate a single color in an image | I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish.
I tried to take only the red color channel but this includes the white spaces in the Image too.
What is a good way to do that?
| [
"Use a different color space: http://en.wikipedia.org/wiki/HSL_color_space\n",
"Use the HSV colorspace. Select pixels that have an H value in the range that you consider to contain \"red,\" and an S value large enough that you do not consider it to be neutral, maroon, brown, or pink. You might also need to thro... | [
4,
1,
0
] | [] | [] | [
"color_space",
"image_processing",
"opencv",
"python"
] | stackoverflow_0000968317_color_space_image_processing_opencv_python.txt |
Q:
Transform items from iterable with a sequence of unary functions
I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with map(), however this only takes a single function to be applied to all items in the sequence.
In the following ... | Transform items from iterable with a sequence of unary functions | I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with map(), however this only takes a single function to be applied to all items in the sequence.
In the following code for example, I wish to apply str.upper() to the first item, and i... | [
"What about...:\ndef transform(functions, arguments):\n return [f(a) for f, a in zip(functions, arguments)]\n\n",
">>> s=\"pid,5 user,8 program,28 dev,10 sent,9 received,15\".split()\n>>> [ ( m.upper(),int(n)) for m, n in [i.split(\",\") for i in s ] ]\n[('PID', 5), ('USER', 8), ('PROGRAM', 28), ('DEV', 10), ('S... | [
3,
1,
1
] | [] | [] | [
"map",
"predicate",
"python",
"transform",
"unary_function"
] | stackoverflow_0002204733_map_predicate_python_transform_unary_function.txt |
Q:
Write timestamp to file every hour in Python
I have a python script that is constantly grabbing data from Twitter and writing the messages to a file. The question that I have is every hour, I want my program to write the current time to the file. Below is my script. Currently, it gets into the timestamp function a... | Write timestamp to file every hour in Python | I have a python script that is constantly grabbing data from Twitter and writing the messages to a file. The question that I have is every hour, I want my program to write the current time to the file. Below is my script. Currently, it gets into the timestamp function and just keeps printing out the time every 10 secon... | [
"your code\nsc.enter(10, 1, t.timestamp, (sc,)\n\nis asking to be scheduled again in 10 seconds. If you want to be scheduled once an hour,\nsc.enter(3600, 1, t.timestamp, (sc,)\n\nseems better, since an hour is 3600 seconds, not 10!\nAlso, the line\ns.enter(1, 1, t.timestamp, (s,))\n\ngets a timestamp 1 second aft... | [
4
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002204856_file_io_python.txt |
Q:
Creating "classes" with Django
I'm just learning Django so feel free to correct me in any of my assumptions. I probably just need my mindset adjusted.
What I'm trying to do is creating a "class" in an OOP style. For example, let's say we're designing a bunch of Rooms. Each Room has Furniture. And each piece of... | Creating "classes" with Django | I'm just learning Django so feel free to correct me in any of my assumptions. I probably just need my mindset adjusted.
What I'm trying to do is creating a "class" in an OOP style. For example, let's say we're designing a bunch of Rooms. Each Room has Furniture. And each piece of Furniture has a Type and a Color. ... | [
"I don't get the problem with unique name. You can just specify it to be unique:\nclass FurniturePiece(models.Model):\n type = models.ForeignKey(FurnitureType)\n color = models.ForeignKey(FurnitureColor)\n sqft = models.IntegerField()\n name = models.CharField(max_length=200, unique=True)\n\nI don't kno... | [
4,
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002204874_django_python.txt |
Q:
Restricting RSS elements by date with feedparser. [Python]
I iterate a RSS feed like so where _file is the feed
d = feedparser.parse(_file)
for element in d.entries:
print repr(element.date)
The date output comes out like so
u'Thu, 16 Jul 2009 15:18:22 EDT'
I cant seem to understand how to actually quantify... | Restricting RSS elements by date with feedparser. [Python] | I iterate a RSS feed like so where _file is the feed
d = feedparser.parse(_file)
for element in d.entries:
print repr(element.date)
The date output comes out like so
u'Thu, 16 Jul 2009 15:18:22 EDT'
I cant seem to understand how to actually quantify the above date output so I can use it to limit feed elements. ... | [
"feedparser is supposed to give you a struct_time object from Python's time module. I'm guessing it doesn't recognize that date format and so is giving you the raw string.\nSee here on how to add support for parsing malformed timestamps:\nhttp://pythonhosted.org/feedparser/date-parsing.html\nIf you manage to get i... | [
5,
1,
0
] | [] | [] | [
"feedparser",
"python"
] | stackoverflow_0002204858_feedparser_python.txt |
Q:
Which is web.py killer app?
A killer app is an app that make a library or framework famous. I think web.py is quite famous, but I don't know any big, widely used app written in web.py.
Could you point out any? I've head that the first version of youtube.com was coded using web.py but I'd like you to mention an ope... | Which is web.py killer app? | A killer app is an app that make a library or framework famous. I think web.py is quite famous, but I don't know any big, widely used app written in web.py.
Could you point out any? I've head that the first version of youtube.com was coded using web.py but I'd like you to mention an open source one so I can see its cod... | [
"From web.py website here is a list of \"Real Web Apps\" written in web.py. None of them has yet become the next twitter.\n\nredditriver.com: a mobile version of reddit.com\nwebme: a blogging and podcasting system\nwebr: a flickr powered photo gallery\nhttp://www.colr.org/ (v5): A site for playing with colors.\nto... | [
7,
4,
0
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0002187610_python_web.py.txt |
Q:
Translate a python dict into a Solr query string
I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax.
The use case is a form defined like this:
class SearchForm(forms.Form):
text = forms.CharField()
metadata = for... | Translate a python dict into a Solr query string | I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax.
The use case is a form defined like this:
class SearchForm(forms.Form):
text = forms.CharField()
metadata = forms.CharField()
figures = forms.CharField()
Upon s... | [
"I would recommend creating a function in the form to handle this rather than in the view. So after you call form.isValid() to ensure the data is acceptable. You can invoke a form.generateSolrQuery() (or whatever name you would like).\nclass SearchForm(forms.Form):\n text = forms.CharField()\n metadata = forms.... | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"solr"
] | stackoverflow_0002203514_django_python_solr.txt |
Q:
TypeErrors using metaclasses in conjunction with multiple inheritance
I have two questions converning metaclasses and multiple inheritance. The first is: Why do I get a TypeError for the class Derived but not for Derived2?
class Metaclass(type): pass
class Klass(object):
__metaclass__ = Metaclass
#class Der... | TypeErrors using metaclasses in conjunction with multiple inheritance | I have two questions converning metaclasses and multiple inheritance. The first is: Why do I get a TypeError for the class Derived but not for Derived2?
class Metaclass(type): pass
class Klass(object):
__metaclass__ = Metaclass
#class Derived(object, Klass): pass # if I uncomment this, I get a TypeError
class O... | [
"The second question has already been well answered twice, though __new__ is actually a staticmethod, not a classmethod as erroneously claimed in a comment...:\n>>> class sic(object):\n... def __new__(cls, *x): return object.__new__(cls, *x)\n... \n>>> type(sic.__dict__['__new__'])\n<type 'staticmethod'>\n\nThe f... | [
7,
4,
0,
0
] | [] | [] | [
"metaclass",
"multiple_inheritance",
"python",
"python_2.x"
] | stackoverflow_0002203947_metaclass_multiple_inheritance_python_python_2.x.txt |
Q:
Using Mako In Windows
I plan to use wsgi + mako in Windows.
I install mako using
C:\wsgi>c:\Python26\Scripts\easy_install.exe Mako
No error. I get
Finished processing dependencies for Mako
at end of the message.
I check my Python directory, I am having the following structure :
C:\Python26\Lib\site-packages\mak... | Using Mako In Windows | I plan to use wsgi + mako in Windows.
I install mako using
C:\wsgi>c:\Python26\Scripts\easy_install.exe Mako
No error. I get
Finished processing dependencies for Mako
at end of the message.
I check my Python directory, I am having the following structure :
C:\Python26\Lib\site-packages\mako-0.2.5-py2.6.egg
C:\Python... | [
"a few things to try\n\nmake sure you're using python2.6\ntry import mako and see if you get a similar error\nif mako imports correctly look at the value of repr(mako) and make sure it corresponds to the path you have.\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002205836_python.txt |
Q:
best (python) setup for cpu / memory intensive task
i'm doing simulation which generates thousands of result objects.
Each object size is around 1mb, and all the result objects should be on memory to be queried for various ad hoc reports. And it takes 1~2 secs to make one result object.
So it takes more than 5 min... | best (python) setup for cpu / memory intensive task | i'm doing simulation which generates thousands of result objects.
Each object size is around 1mb, and all the result objects should be on memory to be queried for various ad hoc reports. And it takes 1~2 secs to make one result object.
So it takes more than 5 minutes to get one simulation done even though i fully use m... | [
"Since you can install all of those for free and it sounds like you already have the code implemented in both .Net and Java then I suggest you benchmark the program on all four platforms (windows/linux * java/.net). \nIt sounds like all the heavy lifting is done in Java/C#, so I suspect the relative performance of... | [
2,
2
] | [] | [] | [
".net",
"c#",
"java",
"memory",
"python"
] | stackoverflow_0002205832_.net_c#_java_memory_python.txt |
Q:
Is there a way to turn XML into dictionary and lists?
<things>
<fruit>apple</fruit>
<hardware>mouse</hardware>
...
</things>
Turn it into:
{'things':[{'fruit':'apple'}, {'hardware':'mouse'}]}
Is there an easy way to do this? Thanks.
A:
there's a nice recipe for that here:
http://code.activestate.com/re... | Is there a way to turn XML into dictionary and lists? | <things>
<fruit>apple</fruit>
<hardware>mouse</hardware>
...
</things>
Turn it into:
{'things':[{'fruit':'apple'}, {'hardware':'mouse'}]}
Is there an easy way to do this? Thanks.
| [
"there's a nice recipe for that here:\nhttp://code.activestate.com/recipes/570085/\nanother good one is here:\nhttp://code.activestate.com/recipes/522991/\n"
] | [
1
] | [] | [] | [
"list",
"python",
"string",
"xml"
] | stackoverflow_0002205987_list_python_string_xml.txt |
Q:
Can I make a field in database use this django code ,and don't use 'python manage.py startapp xx'
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Is this possible?
A:
If you only want to access a database ... | Can I make a field in database use this django code ,and don't use 'python manage.py startapp xx' | from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Is this possible?
| [
"If you only want to access a database from Python, I recommend you use SQLAlchemy instead.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002205857_django_python.txt |
Q:
Print string in a form of Unicode codes
How can I print a string as a sequence of unicode codes in Python?
Input: "если" (in Russian).
Output: "\u0435\u0441\u043b\u0438"
A:
This should work:
>>> s = u'если'
>>> print repr(s)
u'\u0435\u0441\u043b\u0438'
A:
Code:
txt = u"если"
print repr(txt)
Output:
u'\u0435\u... | Print string in a form of Unicode codes | How can I print a string as a sequence of unicode codes in Python?
Input: "если" (in Russian).
Output: "\u0435\u0441\u043b\u0438"
| [
"This should work:\n>>> s = u'если'\n>>> print repr(s)\nu'\\u0435\\u0441\\u043b\\u0438'\n\n",
"Code:\ntxt = u\"если\"\nprint repr(txt)\n\nOutput:\nu'\\u0435\\u0441\\u043b\\u0438'\n\n",
"a = u\"\\u0435\\u0441\\u043b\\u0438\"\nprint \"\".join(\"\\u{0:04x}\".format(ord(c)) for c in a)\n\n",
"If you need a specif... | [
9,
3,
1,
0
] | [] | [] | [
"python",
"string",
"unicode"
] | stackoverflow_0002206210_python_string_unicode.txt |
Q:
Problems using the python WConio library
I'm trying to use the WConio library for python, but when I import it, it gives this error:
Traceback (most recent call last):
File "WConioExample.py", line 15, in
< module>
import WConio File "d:\tools\development\python2.5\lib\site-packages\WConio.py",
line... | Problems using the python WConio library | I'm trying to use the WConio library for python, but when I import it, it gives this error:
Traceback (most recent call last):
File "WConioExample.py", line 15, in
< module>
import WConio File "d:\tools\development\python2.5\lib\site-packages\WConio.py",
line 23, in
from _WConio import * ImportError: DL... | [
"Probably, you've installed 32 bit library on 64 bit system.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002206125_python.txt |
Q:
moving a function out of my method in django
Hay i have a method in my view which uploads an image, the image is then saved to a db object. I want to remove this from my view and either put it in my model or a seperate file.
filename_bits = request.FILES['image'].name.split(".")
filename_bits.reverse()
extension =... | moving a function out of my method in django | Hay i have a method in my view which uploads an image, the image is then saved to a db object. I want to remove this from my view and either put it in my model or a seperate file.
filename_bits = request.FILES['image'].name.split(".")
filename_bits.reverse()
extension = filename_bits[0]
# create filename and open a de... | [
"You should consider using an ImageField in your model. For example in models.py you would have:\ndef get_random_filename(car_picture, filename):\n extension = filename.split('.')[-1]\n return u'_%s_%s.%s' % (random.randint(0,10000000),\n random.randint(0,10000000),\n ... | [
3
] | [] | [] | [
"django",
"methods",
"model",
"python",
"upload"
] | stackoverflow_0002206422_django_methods_model_python_upload.txt |
Q:
global variable from django to javascript
I would like some variables from my settings.py to be available in every javascript running across my project.
What is the most elegant way of achieving this?
Right now I can think of two:
write a context processor and declare those globals in a base template. All templat... | global variable from django to javascript | I would like some variables from my settings.py to be available in every javascript running across my project.
What is the most elegant way of achieving this?
Right now I can think of two:
write a context processor and declare those globals in a base template. All templates must extend the base template.
declare those... | [
"I would use option 1. You should use a base template in any case, and a context processor is probably the best way of getting the variables into it.\n",
"I'm not familiar with django, so this might be completely incorrect.\nCan you write out the variables to hidden HTML fields on the page. This will allow you to... | [
6,
1,
0
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0002206353_django_javascript_python.txt |
Q:
Need help using M2Crypto.Engine to access USB Token
I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl.
from M2Crypto import Engine
Engine.load_dynamic()
dynamic = Engine.Engine('dynamic')
# Load th... | Need help using M2Crypto.Engine to access USB Token | I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl.
from M2Crypto import Engine
Engine.load_dynamic()
dynamic = Engine.Engine('dynamic')
# Load the engine_pkcs from the OpenSC project
dynamic.ctrl_cmd_st... | [
"Found !!!!\nYes, exactly the way where I came from.\nSo, actually the ENGINE_init() is not implemented in M2Crypto.Engine. So, only one solution: patching!!! (very small...) so I've created a new Engine method (in Engine.py)\ndef engine_initz(self):\n \"\"\"Return engine name\"\"\"\n return m2.engine... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"m2crypto",
"python"
] | stackoverflow_0002195179_m2crypto_python.txt |
Q:
Debugging a subprocess.Popen call
I have been using subprocess.Popen successfully in the past, when wrapping binaries with a python script to format arguments / customize etc...
Developing a nth wrapper, I did as usual... but nothing happens.
Here is the little code:
print command
p = subprocess.Popen(command, she... | Debugging a subprocess.Popen call | I have been using subprocess.Popen successfully in the past, when wrapping binaries with a python script to format arguments / customize etc...
Developing a nth wrapper, I did as usual... but nothing happens.
Here is the little code:
print command
p = subprocess.Popen(command, shell = True)
result = p.communicate()[0]
... | [
"I've finally found the answer to my question, thanks to badp and his suggestions for debugging.\nFrom the python page on the subprocess module:\n\nThe executable argument specifies the program to execute. It is very seldom needed: Usually, the program to execute is defined by the args argument. If shell=True, the ... | [
6,
4
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002206407_python_subprocess.txt |
Q:
Send invitation emails on post_save or all at once in django view?
There's a requirement in a web app I'm building about the possibility of the user sending join invitations to his friends. These invitations are stored in the database through the Invitation model. The user can send multiple invitations at once.
Wh... | Send invitation emails on post_save or all at once in django view? | There's a requirement in a web app I'm building about the possibility of the user sending join invitations to his friends. These invitations are stored in the database through the Invitation model. The user can send multiple invitations at once.
What do you think is more appropriate: sending all emails at once in the b... | [
"If this is live application and user experience is important, then I suggest you avoid sending anything email-related in post_save handlers, or even in views.\nReasons are: SMTP can go down, network connection can go down, network can be up but speed can be that of a snail etc. In each of those cases either your p... | [
6
] | [] | [] | [
"django",
"email",
"notifications",
"python"
] | stackoverflow_0002207250_django_email_notifications_python.txt |
Q:
Python - best way to set a column in a 2d array to a specific value
I have a 2d array, I would like to set a column to a particular value, my code is below. Is this the best way in python?
rows = 5
cols = 10
data = (rows * cols) *[0]
val = 10
set_col = 5
for row in range(rows):
data[row * cols + set_col - 1]... | Python - best way to set a column in a 2d array to a specific value | I have a 2d array, I would like to set a column to a particular value, my code is below. Is this the best way in python?
rows = 5
cols = 10
data = (rows * cols) *[0]
val = 10
set_col = 5
for row in range(rows):
data[row * cols + set_col - 1] = val
If I want to set a number of columns to a particular value , how ... | [
"NumPy package provides powerful N-dimensional array object. If data is a numpy array then to set set_col column to val value:\ndata[:, set_col] = val\n\nComplete Example: \n>>> import numpy as np\n>>> a = np.arange(10)\n>>> a.shape = (5,2)\n>>> a\narray([[0, 1],\n [2, 3],\n [4, 5],\n [6, 7],\n ... | [
29,
15,
0,
0,
0
] | [] | [] | [
"multidimensional_array",
"python"
] | stackoverflow_0002207283_multidimensional_array_python.txt |
Q:
Python regex problem
What I am trying to do: Parse a query for a leading or trailing ? which will result in a search on the rest of the string.
"foobar?" or "?foobar" results in a search.
"foobar" results in some other behavior.
This code works as expected in the interpreter:
>>> import re
>>> print re.match(... | Python regex problem | What I am trying to do: Parse a query for a leading or trailing ? which will result in a search on the rest of the string.
"foobar?" or "?foobar" results in a search.
"foobar" results in some other behavior.
This code works as expected in the interpreter:
>>> import re
>>> print re.match(".+\?\s*$","foobar?")
<_s... | [
"The problem is in your second regex. It matches the whole query, so using re.sub() will replace it all with an empty string. I.e. lookForPrefix('foobar?',listOfPrefixes) will return ''. You are likely checking the return value in an if, so it evaluates the empty string as false.\nTo solve this, you just need to ch... | [
3,
0
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0002206026_django_python_regex.txt |
Q:
How to write dynamic Django models?
what i want, is to receive advices to define a re-usefull Product model, for a shopping site app, nowadays I know that the store is going to commerce with "clothing", so the product model will have a "season or collections" relationship, but in the future I should use that app t... | How to write dynamic Django models? | what i want, is to receive advices to define a re-usefull Product model, for a shopping site app, nowadays I know that the store is going to commerce with "clothing", so the product model will have a "season or collections" relationship, but in the future I should use that app to commerce with X product, e.g: "cars" wh... | [
"One way to define relationships between one object and many other types of objects is to use a GenericForeignKey and the ContentType framework. I'd guess you would be looking for a Product with some more specific related object such as Jacket. It may look something like this:\nclass Product(models.Model):\n p... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002207562_django_python.txt |
Q:
Using a method in a model to count objects filtered by the primary key
I wanted to use a method as part of my model to count all the occurrences of the object in another table that references it as a foreign key.
Will the below work?
class Tile(models.Model):
#...
def popularity(self):
return Playl... | Using a method in a model to count objects filtered by the primary key | I wanted to use a method as part of my model to count all the occurrences of the object in another table that references it as a foreign key.
Will the below work?
class Tile(models.Model):
#...
def popularity(self):
return PlaylistItem.objects.filter(tile__exact=self.id).count()
And the relevant inform... | [
"When you create a ForeignKey, Django creates a backref on referenced model for you, so you could just do:\ndef popularity(self):\n return self.playlistitem_set.count()\n\nSee http://docs.djangoproject.com/en/1.1/topics/db/queries/#backwards-related-objects.\n"
] | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002207875_django_django_models_python.txt |
Q:
Where would I import urllib2 for a class?
I have a class that needs access to urllib2, the trivial example for me is:
class foo(object):
myStringHTML = urllib2.urlopen("http://www.google.com").read()
How should I structure my code to include urllib2? In general, I want to store foo in a utility module with a... | Where would I import urllib2 for a class? | I have a class that needs access to urllib2, the trivial example for me is:
class foo(object):
myStringHTML = urllib2.urlopen("http://www.google.com").read()
How should I structure my code to include urllib2? In general, I want to store foo in a utility module with a number of other classes, and be able to import... | [
"You should import it in the utilpackage module, but only export the class foo from it:\nimport urllib2\n\n__all__ = [\"foo\"]\n\nclass foo(object):\n myStringHtml = urllib2.urlopen(\"http://www.google.com\").read()\n\nThen you can do\nfrom utilpackage import foo\n\nbut not\nfrom utilpackage import urllib2\n\nTh... | [
4,
2,
0
] | [] | [] | [
"coding_style",
"module",
"python"
] | stackoverflow_0002205712_coding_style_module_python.txt |
Q:
What is the most lightweight way to transmit data over the internet using Python?
I have two computers in geographically dispersed locations, both connected to the internet. On each computer I am running a Python program, and I would like to send and receive data from one to the other. I'd like to use the most sim... | What is the most lightweight way to transmit data over the internet using Python? | I have two computers in geographically dispersed locations, both connected to the internet. On each computer I am running a Python program, and I would like to send and receive data from one to the other. I'd like to use the most simple approach possible, while remaining somewhat secure.
I have considered the following... | [
"Protocol buffers are \"lightweight\" in the sense that they produce very compact wire representation, thus saving bandwidth, memory, storage, etc -- while staying very general-purpose and cross-language. We use them a lot at Google, of course, but it's not clear whether you care about these performance characteri... | [
9,
3,
1,
0,
0
] | [] | [] | [
"network_protocols",
"python"
] | stackoverflow_0002199963_network_protocols_python.txt |
Q:
How to redirect to a query string URL containing non-ascii characters in DJANGO?
How to redirect to a query string URL containing non-ascii characters in DJANGO?
When I use return HttpResponseRedirect(u'/page/?title=' + query_string) where the query_string contains characters like 你好, I get an error
'ascii' code... | How to redirect to a query string URL containing non-ascii characters in DJANGO? | How to redirect to a query string URL containing non-ascii characters in DJANGO?
When I use return HttpResponseRedirect(u'/page/?title=' + query_string) where the query_string contains characters like 你好, I get an error
'ascii' codec can't encode characters in position 21-26: ordinal not
in range(128), HTTP respons... | [
"HttpResponseRedirect(((u'/page/?title=' + query_string).encode('utf-8'))\n\nis the first thing to try (since UTF8 is the only popular encoding that can handle all Unicode characters). That should definitely get rid of the exception you're observing -- the issue then moves to ensuring the handler for /page can pro... | [
6,
6
] | [] | [] | [
"django",
"httpresponse",
"python",
"unicode"
] | stackoverflow_0002204914_django_httpresponse_python_unicode.txt |
Q:
How to use Django templatetags in static media files?
Im using a flash gallery and the settings xml file is stored in /media/xml/gallery.xml
In the gallery.xml file I want to add this snippet of code:
<items>
{% for image in images %}
<item source="{{ MEDIA_URL }}{{ image.image }}" thumb="" description="{... | How to use Django templatetags in static media files? | Im using a flash gallery and the settings xml file is stored in /media/xml/gallery.xml
In the gallery.xml file I want to add this snippet of code:
<items>
{% for image in images %}
<item source="{{ MEDIA_URL }}{{ image.image }}" thumb="" description="{{ image.title }}" />
{% endfor %}
</item>
But the sour... | [
"You will have to serve this document via a Django view, and render it as a template.\n",
"Static media is, by definition, static. If you want Django mechanisms to work then you need to process using Django.\n"
] | [
2,
2
] | [] | [] | [
"django",
"media",
"python",
"tags",
"templates"
] | stackoverflow_0002208551_django_media_python_tags_templates.txt |
Q:
How to make a multi choice form field on app engine
I'm building an application on app Engine and I want to make a form field with multiple choices.
Here is my form (it uses django.newforms from the app engine sdk (django 0.96)) :
from google.appengine.ext.db import djangoforms
from django import newforms
class K... | How to make a multi choice form field on app engine | I'm building an application on app Engine and I want to make a form field with multiple choices.
Here is my form (it uses django.newforms from the app engine sdk (django 0.96)) :
from google.appengine.ext.db import djangoforms
from django import newforms
class KeywordForm(djangoforms.ModelForm):
class Meta:
... | [
"I've found a solution !\nThe problem is self.request.POST dictionnary provided to my form's constructor.\nIt's format is not appreciated by MultipleChoiceField.clean() function, so I transformed it.\nHere is the working validation code :\n args = self.request.arguments()\n data = {}\n for i in args:\n data[i] ... | [
2
] | [] | [] | [
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0002208207_django_forms_google_app_engine_python.txt |
Q:
Django unable to open sqlite on SOME queries only?
I have had no troubles locally, but pushing a new project to an existing machine (one running plenty of other django apps without trouble) gave this:
OperationalError: unable to open database file
What is more perplexing is:
The sqlite file is read-write for all... | Django unable to open sqlite on SOME queries only? | I have had no troubles locally, but pushing a new project to an existing machine (one running plenty of other django apps without trouble) gave this:
OperationalError: unable to open database file
What is more perplexing is:
The sqlite file is read-write for all
This error only happens on some queries! Other's are fi... | [
"Write access on the directory. I thought i checked that first :-/\n"
] | [
0
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0002208643_django_python_sqlite.txt |
Q:
Index xml files from a outside website
Using python django I would like to access this site http://www.reta-vortaro.de/revo/ It is a dictionary site for a language called esperanto, I need to be able to search for a word, and get back its definition, it looks like Each Esperanto root word has an xml file,
I ... | Index xml files from a outside website | Using python django I would like to access this site http://www.reta-vortaro.de/revo/ It is a dictionary site for a language called esperanto, I need to be able to search for a word, and get back its definition, it looks like Each Esperanto root word has an xml file,
I need to index each xml file
store the name o... | [
"Most programming languages have access to both some sort of XML parser as well as some persistent embedded key-value store. Once you've decided on a programming language, just find one of each that you can feel comfortable with.\n",
"Wonder, if you have access to WSDL. You might be able to access the data that w... | [
2,
2,
1,
1,
0,
0
] | [] | [] | [
"django",
"python",
"xml"
] | stackoverflow_0002115290_django_python_xml.txt |
Q:
How to debug a MemoryError in Python? Tools for tracking memory use?
I have a Python program that dies with a MemoryError when I feed it a large file. Are there any tools that I could use to figure out what's using the memory?
This program ran fine on smaller input files. The program obviously needs some scalabi... | How to debug a MemoryError in Python? Tools for tracking memory use? | I have a Python program that dies with a MemoryError when I feed it a large file. Are there any tools that I could use to figure out what's using the memory?
This program ran fine on smaller input files. The program obviously needs some scalability improvements; I'm just trying to figure out where. "Benchmark before... | [
"Heapy is a memory profiler for Python, which is the type of tool you need.\n",
"The simplest and lightweight way would likely be to use the built in memory query capabilities of Python, such as sys.getsizeof - just run it on your objects for a reduced problem (i.e. a smaller file) and see what takes a lot of mem... | [
10,
4,
2,
1
] | [] | [] | [
"memory_management",
"out_of_memory",
"profiling",
"python"
] | stackoverflow_0001681836_memory_management_out_of_memory_profiling_python.txt |
Q:
How to do "performance-based" (benchmark) unit testing in Python
Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)
Next I want to test performance. To benchmark code to make sure that new commits are... | How to do "performance-based" (benchmark) unit testing in Python | Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)
Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's z... | [
"You will want to do performance testing at a system level if possible - test your application as a whole, in context, with data and behaviour as close to production use as possible.\nThis is not easy, and it will be even harder to automate it and get consistent results.\nMoreover, you can't use a VM for performanc... | [
7,
4,
2,
2
] | [] | [] | [
"benchmarking",
"linux",
"python",
"unit_testing"
] | stackoverflow_0000671503_benchmarking_linux_python_unit_testing.txt |
Q:
Access remote computer to launch Python script without disturbing user
First, I'll admit this is cross-posted at SuperUser but I decided to also post here as my objective is programming related and this community might have better solution scenarios than just the one I'm thinking of.
I have a Windows 7 computer th... | Access remote computer to launch Python script without disturbing user | First, I'll admit this is cross-posted at SuperUser but I decided to also post here as my objective is programming related and this community might have better solution scenarios than just the one I'm thinking of.
I have a Windows 7 computer that is acting as a Media Center so it is always on but not always in use. I w... | [
"How about wrapping their execution within Remote WSH? Not sure about the monitoring part, although I suppose you could simply have your scripts create a log on the remote machine, and then you can \"tail\" it in realtime while the remote script is still running...\n",
"For running remote python I like execnet. I... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"remote_desktop",
"windows_7"
] | stackoverflow_0002208944_python_remote_desktop_windows_7.txt |
Q:
Using Postgres in a web app: "transaction aborted" errors
Recently I moved a web app I'm developing from MySQL to PostgreSQL for performance reasons (I need functionality PostGIS provides). Now quite often encounter the following error:
current transaction is aborted, commands ignored until end of transaction bloc... | Using Postgres in a web app: "transaction aborted" errors | Recently I moved a web app I'm developing from MySQL to PostgreSQL for performance reasons (I need functionality PostGIS provides). Now quite often encounter the following error:
current transaction is aborted, commands ignored until end of transaction block
The server application uses mod_python. The error occurs in t... | [
"that error is caused because of a precedent error. look at this piece of code:\n>>> import psycopg2\n>>> conn = psycopg2.connect('')\n>>> cur = conn.cursor()\n>>> cur.execute('select current _date')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\npsycopg2.ProgrammingError: syntax erro... | [
14
] | [] | [] | [
"concurrency",
"postgresql",
"python"
] | stackoverflow_0002209169_concurrency_postgresql_python.txt |
Q:
How do I properly setup my python paths and permissions for Django+mod_wsgi deployment?
The issue I'm having is my wsgi file can't import the wsgi handlers properly.
/var/log/apache2/error.log reports:
ImportError: No module named
django.core.handlers.wsgi
Googling this brings up a couple results, mostly deali... | How do I properly setup my python paths and permissions for Django+mod_wsgi deployment? | The issue I'm having is my wsgi file can't import the wsgi handlers properly.
/var/log/apache2/error.log reports:
ImportError: No module named
django.core.handlers.wsgi
Googling this brings up a couple results, mostly dealing with permissions errors because www-data can't read certain files and/or the pythonpath is... | [
"Since I'm on Debian it appears that django is in /usr/lib/pymodules/python2.5 and not /usr/lib/python2.5/site-packages.\nI added\nsys.path.append('/usr/lib/pymodules/python2.5') \n\nto the top of my wsgi file and that did it, although I feel as though I should be fixing this in a more proper manner.\n",
"I don't... | [
2,
1,
0
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0002205105_django_mod_wsgi_python.txt |
Q:
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
https://developer.mozilla.org/en/New_in_JavaScript_1.7
A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. Ho... | What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement | https://developer.mozilla.org/en/New_in_JavaScript_1.7
A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed
for (i = 0; i < arr.length; i++) {
/* ... */
}
for really simple operations? Wouldn't this be e... | [
"While this question is a bit old, and is marked \"answered\" - I found it on Google and the answers given are possibly inaccurate, or if not, definitely incomplete.\nIt's very important to note that Javascript is NOT A STANDARD. Ken correctly mentioned that ECMAScript is the cross-browser standard that all browser... | [
33,
8,
1
] | [] | [] | [
"arrays",
"cross_browser",
"internet_explorer",
"javascript",
"python"
] | stackoverflow_0001330498_arrays_cross_browser_internet_explorer_javascript_python.txt |
Q:
InternalError: current transaction is aborted, commands ignored until end of transaction block
I'm getting this error when doing database calls in a sub process using multiprocessing library.
Visit : Pastie
InternalError: current transaction is aborted, commands ignored until
end of transaction block
this is t... | InternalError: current transaction is aborted, commands ignored until end of transaction block | I'm getting this error when doing database calls in a sub process using multiprocessing library.
Visit : Pastie
InternalError: current transaction is aborted, commands ignored until
end of transaction block
this is to a Postgre Database, using psycopg2 driver in web.py.
However if I use threading.Thread instead of ... | [
"multiprocessing works (on UNIX systems) by forking the current process. If you have an existing database connection, this will leave the two processes (the current one and the new one) with the same database connection. Trying to use it from both is bad. Create a new database connection in the child process instea... | [
9
] | [] | [] | [
"multiprocessing",
"postgresql",
"psycopg2",
"python",
"web.py"
] | stackoverflow_0002209560_multiprocessing_postgresql_psycopg2_python_web.py.txt |
Q:
SQLAlchemy ORM Inserting Related Objects without Selecting Them
In the SQLAlchemy ORM tutorial, it describes the process of creating object relations roughly as follows. Let's pretend I have a table Articles, a table Keywords, and a table Articles_Keywords which creates a many-many relationship.
article = meta.Se... | SQLAlchemy ORM Inserting Related Objects without Selecting Them | In the SQLAlchemy ORM tutorial, it describes the process of creating object relations roughly as follows. Let's pretend I have a table Articles, a table Keywords, and a table Articles_Keywords which creates a many-many relationship.
article = meta.Session.query(Article).filter(id=1).one()
keyword1 = meta.Session.query... | [
"Unfortunately the ORM cannot keep the object state sane without querying the database. However you can easily go around the ORM and insert into the association table. Assuming that Articles_Keywords is a Table object:\n meta.Session.execute(Articles_Keywords.delete(Articles_Keywords.c.article_id == 1))\n meta.Sess... | [
3,
1
] | [] | [] | [
"orm",
"performance",
"python",
"sqlalchemy"
] | stackoverflow_0002180522_orm_performance_python_sqlalchemy.txt |
Q:
PIP install a Python Package without a setup.py file?
I'm trying to figure out how I can install a python package that doesn't have a setup.py file with pip. (package in question is http://code.google.com/p/django-google-analytics/)
Normally I would just checkout the code from the repo and symlink into my site-pac... | PIP install a Python Package without a setup.py file? | I'm trying to figure out how I can install a python package that doesn't have a setup.py file with pip. (package in question is http://code.google.com/p/django-google-analytics/)
Normally I would just checkout the code from the repo and symlink into my site-packages, but I'm trying to get my whole environment frozen in... | [
"Fork the repo and add a working setup.py. Then send a pull request to the author.\nOh, it's on Google Code. Well then, file a bug and post a patch.\nIf the author refuses to make their code into an installable Python distribution (never happened to me), just host your fork somewhere and put that in your requiremen... | [
16,
7
] | [] | [] | [
"easy_install",
"pip",
"python",
"setuptools"
] | stackoverflow_0002204811_easy_install_pip_python_setuptools.txt |
Q:
How do I do this with Python list? (itemgetter?)
[{'id':44}, {'name':'alexa'},{'color':'blue'}]
I want to select whatever in the list that is "id".
Basically, I want to print 44, since that's "id" in the list.
A:
That's a weird data structure... A list of one item dictionaries.
key = 'id'
l = [{'id':44}, {'name... | How do I do this with Python list? (itemgetter?) | [{'id':44}, {'name':'alexa'},{'color':'blue'}]
I want to select whatever in the list that is "id".
Basically, I want to print 44, since that's "id" in the list.
| [
"That's a weird data structure... A list of one item dictionaries.\nkey = 'id'\nl = [{'id':44}, {'name':'alexa'},{'color':'blue'}]\n\nprint [ x[key] for x in l if key in x ][0]\n\nAssuming you can rely on key being present precisely once...\nMaybe you should just convert the list into a dictionary first:\nkey = 'id... | [
5,
4,
3,
3,
2,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0002206543_dictionary_list_python.txt |
Q:
How to use C++ operators within python using boost::python (pyopencv)
I'm using the pyopencv bindings. This python lib uses boost::python to connect to OopenCV. Now I'm trying to use the SURF class but don't know how to handle the class operator in my python code.
The C++ class is defined as:
void SURF::operator()... | How to use C++ operators within python using boost::python (pyopencv) | I'm using the pyopencv bindings. This python lib uses boost::python to connect to OopenCV. Now I'm trying to use the SURF class but don't know how to handle the class operator in my python code.
The C++ class is defined as:
void SURF::operator()(const Mat& img, const Mat& mask,
vector<KeyPoint>& keypo... | [
"You just call it as if it was a function. If surf_inst is an instance of the SURF class, you would call:\nnewKeyPoints = surf_inst(img, mask, keypoints)\n\nThe argument keypoints is expected to be a tuple, and img and mask should be an instance of the Mat class. The C++ function modifies its keypoints parameter. T... | [
1
] | [] | [] | [
"boost_python",
"c++",
"operator_overloading",
"operators",
"python"
] | stackoverflow_0002209889_boost_python_c++_operator_overloading_operators_python.txt |
Q:
Python != operation vs "is not"
In a comment on this question, I saw a statement that recommended using
result is not None
vs
result != None
I was wondering what the difference is, and why one might be recommended over the other?
A:
== is an equality test. It checks whether the right hand side and the left han... | Python != operation vs "is not" | In a comment on this question, I saw a statement that recommended using
result is not None
vs
result != None
I was wondering what the difference is, and why one might be recommended over the other?
| [
"== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)\nis is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the... | [
365,
177,
48,
23,
11
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0002209755_operators_python.txt |
Q:
print beautiful value with error
I want to display in a HTML page some datas with errors, for example:
(value, error) -> string
(123, 12) -> (12 +- 1) x 10^1
(4234.3, 2) -> (4234 +- 2)
(0.02312, 0.003) -> (23 +- 3) x 10^-3
I've produced this:
from math import log10
def format_value_error(value,error):
E = i... | print beautiful value with error | I want to display in a HTML page some datas with errors, for example:
(value, error) -> string
(123, 12) -> (12 +- 1) x 10^1
(4234.3, 2) -> (4234 +- 2)
(0.02312, 0.003) -> (23 +- 3) x 10^-3
I've produced this:
from math import log10
def format_value_error(value,error):
E = int(log10(abs(error)))
val = float(... | [
"I'm not sure exactly what you want, but I assume you just want to round the numbers you have to the nearest integer? If so, you can use the built-in function round: \n>>> int(round(1.5))\n2\n\nHere's the help:\n>>> help(round)\nHelp on built-in function round in module __builtin__:\n\nround(...)\n round(number[... | [
3,
0
] | [] | [] | [
"math",
"printing",
"python",
"statistics"
] | stackoverflow_0002210475_math_printing_python_statistics.txt |
Q:
Map list of tuples into a dictionary
I've got a list of tuples extracted from a table in a DB which looks like (key , foreignkey , value). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that... | Map list of tuples into a dictionary | I've got a list of tuples extracted from a table in a DB which looks like (key , foreignkey , value). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey, i.e. { foreignkey , sumof( va... | [
"Assuming all your values are ints, you could use a defaultdict to make this easier:\nfrom collections import defaultdict\n\nmyDict = defaultdict(int)\n\nfor item in myTupleList:\n myDict[item[1]] += item[2]\n\ndefaultdict is like a dictionary, except if you try to get a key that isn't there it fills in the valu... | [
9,
5,
4,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"tuples"
] | stackoverflow_0002210581_dictionary_list_python_tuples.txt |
Q:
How do I generate a table of contents for HTML text in Python?
Assume that I have some HTML code, like this (generated from Markdown or Textile or something):
<h1>A header</h1>
<p>Foo</p>
<h2>Another header</h2>
<p>More content</p>
<h2>Different header</h2>
<h1>Another toplevel header
<!-- and so on -->
How could... | How do I generate a table of contents for HTML text in Python? | Assume that I have some HTML code, like this (generated from Markdown or Textile or something):
<h1>A header</h1>
<p>Foo</p>
<h2>Another header</h2>
<p>More content</p>
<h2>Different header</h2>
<h1>Another toplevel header
<!-- and so on -->
How could I generate a table of contents for it using Python?
| [
"Use an HTML parser such as lxml or BeautifulSoup to find all header elements.\n",
"Here's an example using lxml and xpath.\nfrom lxml import etree\ndoc = etree.parse(\"test.xml\")\nfor node in doc.xpath('//h1|//h2|//h3|//h4|//h5'):\n print node.tag, node.text\n\n"
] | [
6,
3
] | [] | [] | [
"html",
"python",
"tableofcontents"
] | stackoverflow_0002210265_html_python_tableofcontents.txt |
Q:
Dynamically select database based on request
I'm trying to keep my RESTful site DRY, and I can't come up with a good way to factor out the code to dynamically select from each "user's" separate database. We've got a separate database for each client. This comes in as a part of the URL, and is passed into each view... | Dynamically select database based on request | I'm trying to keep my RESTful site DRY, and I can't come up with a good way to factor out the code to dynamically select from each "user's" separate database. We've got a separate database for each client. This comes in as a part of the URL, and is passed into each view as a keyword arg. I want to give each and every v... | [
"We do this by the following technique.\n\nApache picks off the first part of the path and routes this to a specific mod_wsgi Daemon.\nEach mod_wsgi daemon is a different customer's installation.\n\nWe have many parallel customers, each with (nearly) identical code, all based off a single common installation of the... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002210914_django_python.txt |
Q:
Python Build Problem on Mac OS 10.6 / Snow Leopard
I'm encountering a build problem for Python 2.6.4 on Snow Leopard.
Mac OS X 10.6
Yonah CPU, 32-bit
gcc-4.2.1
Update I
Solved by removing all non-standard includes and libraries from CFLAGS (there happened to be a uuid/uuid.h in there ...). Still, it compiled des... | Python Build Problem on Mac OS 10.6 / Snow Leopard | I'm encountering a build problem for Python 2.6.4 on Snow Leopard.
Mac OS X 10.6
Yonah CPU, 32-bit
gcc-4.2.1
Update I
Solved by removing all non-standard includes and libraries from CFLAGS (there happened to be a uuid/uuid.h in there ...). Still, it compiled despite the error describe below, with /usr/include/hfs/hf... | [
"Try adding --universal-archs=32-bit to the configure arguments.\nEDIT: You may also need to set environment variable MACOSX_DEPLOYMENT_TARGET=10.6 and explicitly use the 10.6 SDK:\nexport MACOSX_DEPLOYMENT_TARGET=10.6\n./configure --universal-archs=32-bit --enable-universalsdk=/Developer/SDKs/MacOSX10.6.sdk ...\n\... | [
4,
1
] | [] | [] | [
"32_bit",
"build",
"gcc",
"macos",
"python"
] | stackoverflow_0002211387_32_bit_build_gcc_macos_python.txt |
Q:
Python module matrix class that implements Modulo 2 arithmetic?
I'm looking for a pure Python module that implements a matrix class where the underlying matrix operations are computed in modulo 2 arithmetic as in
(x+y)%2
I need to do a lot of basic matrix manipulations ( transpose, multiplication, etc. ).
Any hel... | Python module matrix class that implements Modulo 2 arithmetic? | I'm looking for a pure Python module that implements a matrix class where the underlying matrix operations are computed in modulo 2 arithmetic as in
(x+y)%2
I need to do a lot of basic matrix manipulations ( transpose, multiplication, etc. ).
Any help appreciated.
Thanks in advance
| [
"This might help you. Look for the Matrix module on that page. Here is the source.\ncheers\n"
] | [
1
] | [] | [] | [
"math",
"matrix",
"python"
] | stackoverflow_0002211405_math_matrix_python.txt |
Q:
why my django code can not be a 'Standalone Django scripts'
before you look my code , see http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
i want to be a Standalone Django scripts'
this is my code :
from django.db import models
from djangosphinx.models import SphinxSearch,SphinxQuerySet
import... | why my django code can not be a 'Standalone Django scripts' | before you look my code , see http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
i want to be a Standalone Django scripts'
this is my code :
from django.db import models
from djangosphinx.models import SphinxSearch,SphinxQuerySet
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings... | [
"The code that you use to set the django settings module has to come before any django-related code, including the django db imports at the top of the script.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002211624_django_python.txt |
Q:
selfClosingTags in BeautifulSoup
Using BeautifulSoup to parse my XML
import BeautifulSoup
soup = BeautifulSoup.BeautifulStoneSoup( """<alan x="y" /><anne>hello</anne>""" ) # selfClosingTags=['alan'])
print soup.prettify()
This will output:
<alan x="y">
<anne>
hello
</anne>
</alan>
ie, the anne tag is a chi... | selfClosingTags in BeautifulSoup | Using BeautifulSoup to parse my XML
import BeautifulSoup
soup = BeautifulSoup.BeautifulStoneSoup( """<alan x="y" /><anne>hello</anne>""" ) # selfClosingTags=['alan'])
print soup.prettify()
This will output:
<alan x="y">
<anne>
hello
</anne>
</alan>
ie, the anne tag is a child of the alan tag.
If I pass selfClos... | [
"You are asking what was in the mind of an author, after having noted that he gives names like Beautiful[Stone]Soup to classes/modules :-)\nHere are two more examples of the behaviour of BeautifulStoneSoup:\n>>> soup = BeautifulSoup.BeautifulStoneSoup(\n \"\"\"<alan x=\"y\" ><anne>hello</anne>\"\"\"\n )\n>>> ... | [
3,
1
] | [] | [] | [
"beautifulsoup",
"python",
"xml"
] | stackoverflow_0002211589_beautifulsoup_python_xml.txt |
Q:
Django model with filterable attributes
I've got two models. One represents a piece of equipment, the other represents a possible attribute the equipment has. Semantically, this might look like:
Equipment: tractor, Attributes: wheels, towing
Equipment: lawnmower, Attributes: wheels, blades
Equipment: hedgetrimmer... | Django model with filterable attributes | I've got two models. One represents a piece of equipment, the other represents a possible attribute the equipment has. Semantically, this might look like:
Equipment: tractor, Attributes: wheels, towing
Equipment: lawnmower, Attributes: wheels, blades
Equipment: hedgetrimmer, Attributes: blades
I want to make queries ... | [
"Your second example is pretty close, but you need to understand how the QuerySet API works across relationships (i.e. joins).\nclass Attribute(models.Model):\n name = models.CharField(max_length=20)\n\nclass Equipment(models.Model):\n name = models.CharField(max_length=20)\n attributes = models.ManyToMany... | [
1
] | [] | [] | [
"django",
"django_models",
"mysql",
"python",
"sql"
] | stackoverflow_0002211631_django_django_models_mysql_python_sql.txt |
Q:
why 'list index out of range' in my django code;
IndexError: list index out of range
this is my django code :
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings"
#from django.core.management import setup_environ
#from sphinx_test import settings
#setup_environ(settings)
from django.db import... | why 'list index out of range' in my django code; | IndexError: list index out of range
this is my django code :
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings"
#from django.core.management import setup_environ
#from sphinx_test import settings
#setup_environ(settings)
from django.db import models
from djangosphinx.models import SphinxSearch,... | [
"You need to set Meta.app_label to something usable.\n",
"That's odd, that part of the code is just supposed to determine your app name. See the section here starting line 45. What's your app name for this?\nYou may be able to avoid the error by setting app_label to the name of your app in the Meta section of you... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002211705_django_python.txt |
Q:
How to animate a graph I've drawn in PyQt?
So I've managed to get a graph drawn up on my screen like such:
class Window(QWidget):
#stuff
graphicsView = QGraphicsView(self)
scene = QGraphicsScene(self)
#draw our nodes and edges.
for i in range(0, len(MAIN_WORLD.currentMax.to... | How to animate a graph I've drawn in PyQt? | So I've managed to get a graph drawn up on my screen like such:
class Window(QWidget):
#stuff
graphicsView = QGraphicsView(self)
scene = QGraphicsScene(self)
#draw our nodes and edges.
for i in range(0, len(MAIN_WORLD.currentMax.tour) - 1):
node = QGraphicsRectItem(M... | [
"QGraphicsScene manages the drawing of the items you've added to it. If the position of the rectangles or lines has changed you can update them if you old onto them:\nfor i in range( ):\n nodes[i] = node = QGraphicsRectItem()\n scene.add(nodes[i])\n\nLater, you can update a node's position:\nnodes[j].setRect(... | [
2
] | [] | [] | [
"animation",
"pyqt",
"python"
] | stackoverflow_0002190210_animation_pyqt_python.txt |
Q:
what is the simplest way to create a table use django db api ,and base on 'Standalone Django scripts'
we can call this 'Standalone Django table'
i am not successful now .
can you ???
thanks
if you don't know 'Standalone Django scripts', look this http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts... | what is the simplest way to create a table use django db api ,and base on 'Standalone Django scripts' | we can call this 'Standalone Django table'
i am not successful now .
can you ???
thanks
if you don't know 'Standalone Django scripts', look this http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
2.this is my code:
from django.core.management import setup_environ
from sphinx_test import settings
se... | [
"The article you linked is a pretty damn good explanation of the simplest way to do it.\nEdit: Re-arranged this for clarity.\nStarting with a fresh app, create a model, sync the database to create the tables, and then use the setup_environ function from within your standalone script.\nOf course this is assuming tha... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002211816_django_python.txt |
Q:
Method of Multiple Assignment in Python
I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as a, b, c = 1, 2, 3 leaves me bewildered for a moment, until I realize that there ar... | Method of Multiple Assignment in Python | I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as a, b, c = 1, 2, 3 leaves me bewildered for a moment, until I realize that there are multiple assignments going on. To make thin... | [
"It's extremely easy to check, with the dis module:\n>>> import dis\n>>> dis.dis(compile('a,b,c=1,2,3','','exec'))\n 1 0 LOAD_CONST 4 ((1, 2, 3))\n 3 UNPACK_SEQUENCE 3\n 6 STORE_NAME 0 (a)\n 9 STORE_NAME 1 (b)\n ... | [
13,
11,
2,
1
] | [] | [] | [
"python",
"syntax",
"variable_assignment"
] | stackoverflow_0002211822_python_syntax_variable_assignment.txt |
Q:
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
I've always preferred these:
not 'x' in 'abc'
not 'x' is 'a'
(assuming, of course that everyone knows in and is out-prioritize not -- I probably should use parentheses) over the more (English) gramma... | Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."? | I've always preferred these:
not 'x' in 'abc'
not 'x' is 'a'
(assuming, of course that everyone knows in and is out-prioritize not -- I probably should use parentheses) over the more (English) grammatical:
'x' not in 'abc'
'x' is not 'a'
but didn't bother to think why until I realized they do not make syntactical sen... | [
"It's easy to check if there's any difference, with the dis module:\n>>> dis.dis(compile('not a in b','','exec'))\n 1 0 LOAD_NAME 0 (a)\n 3 LOAD_NAME 1 (b)\n 6 COMPARE_OP 7 (not in)\n 9 POP_TOP \n 1... | [
7,
4,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002211706_python.txt |
Q:
Why does gethostbyaddr(gethostname()) return my IPv6 IP?
I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this:
HOST = gethostbyaddr(gethostname())
With a little more processing after this, it should give me j... | Why does gethostbyaddr(gethostname()) return my IPv6 IP? | I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this:
HOST = gethostbyaddr(gethostname())
With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 addre... | [
"Getting your IP address is harder than you might think.\nCheck this answer I gave for the one reliable way I've found.\nHere's what the answer says in case you don't like clicking on things:\nUse the netifaces module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what... | [
11,
5,
2
] | [] | [] | [
"ip_address",
"ipv4",
"ipv6",
"python",
"sockets"
] | stackoverflow_0000415407_ip_address_ipv4_ipv6_python_sockets.txt |
Q:
optional arguments when calling a function without modifying function definition
I want to know how to call a function, passing a parameter that it might not be expecting.
I faced this problem a few days ago, and found a way around it. But today, I decided I'd see if what I wanted to do was possible. Unfortunately... | optional arguments when calling a function without modifying function definition | I want to know how to call a function, passing a parameter that it might not be expecting.
I faced this problem a few days ago, and found a way around it. But today, I decided I'd see if what I wanted to do was possible. Unfortunately, I don't remember the context which I used it in. So here is a stupid example in whic... | [
"Inspecting the function is the only way to explicitly differentiate between functions with different numbers of arguments without altering or decorating the originals. The only change I would do to your wrapper is to generalize it for any number of arguments:\ndef padArgsWithTrue(func, *args):\n passed_args = l... | [
1,
0
] | [] | [] | [
"function_calls",
"optional_parameters",
"python"
] | stackoverflow_0002212185_function_calls_optional_parameters_python.txt |
Q:
Accessing C header magic numbers/flags with Cython
Some standard C libraries that I want to access with Cython have a ton of flags. The Cython docs state that I must replicate the parts of the header I need. Which is fine when it comes to functions definitions. They are usually replicated everywhere, docs included... | Accessing C header magic numbers/flags with Cython | Some standard C libraries that I want to access with Cython have a ton of flags. The Cython docs state that I must replicate the parts of the header I need. Which is fine when it comes to functions definitions. They are usually replicated everywhere, docs included. But what about all those magic numbers?
If I want to ... | [
"To use these constants from Cython, you don't need to figure exactly where they came from or what they are any more than you do from C. For example, your .pxd file can look like\ncdef extern from \"foo.h\":\n void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)\n cdef int PROT_RE... | [
6,
2,
1
] | [] | [] | [
"cython",
"header_files",
"python"
] | stackoverflow_0002206557_cython_header_files_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.