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:
Problems with VLC and instant messaging
I've have asked these questions before with no proper answer. I hope I'll get some response here.
I'm developing an instant messenger in python and I'd like to handle video/audio streaming with VLC. Tha basic idea right now is that in each IM client I'm running one VLC inst... | Problems with VLC and instant messaging | I've have asked these questions before with no proper answer. I hope I'll get some response here.
I'm developing an instant messenger in python and I'd like to handle video/audio streaming with VLC. Tha basic idea right now is that in each IM client I'm running one VLC instance that acts as a server that streams to al... | [
"I think they were suggesting you run your program on a LAN which has no ports blocked.\n"
] | [
0
] | [] | [] | [
"instant_messaging",
"p2p",
"python",
"streaming",
"vlc"
] | stackoverflow_0004015227_instant_messaging_p2p_python_streaming_vlc.txt |
Q:
AppEngine data strategy to handle a large index per user?
I’m building an AppEngine app in Python.
For the sake of discussion, imagine I’m building a Gmail clone. Except with a million short emails per user.
The point is, each user will have a large search index, all to theirself; just like Gmail, each user has ... | AppEngine data strategy to handle a large index per user? | I’m building an AppEngine app in Python.
For the sake of discussion, imagine I’m building a Gmail clone. Except with a million short emails per user.
The point is, each user will have a large search index, all to theirself; just like Gmail, each user has a personal “search engine” of their own content.
Now imagine th... | [
"How about storing a list of User keys in each mail message? That's assuming that a single message won't be owned by more than a hundred or so users.\nclass User(db.Model):\n \"usual properties like name, etc\"\n\nclass Message(db.Model):\n\n # list of users that have this message\n users = db.ListPropert... | [
2,
0
] | [] | [] | [
"database_design",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004120468_database_design_google_app_engine_google_cloud_datastore_python.txt |
Q:
problem with reading RGB values of pixels using pyglet
For a programming project, I need to read pixels from a loaded image using pyglet.
I used "pyglet.image.load('map.png')" to load the image, and I found out that you can retrieve the image data using img.get_image_data().
I use line mapImage.get_region(x,y,1,1... | problem with reading RGB values of pixels using pyglet | For a programming project, I need to read pixels from a loaded image using pyglet.
I used "pyglet.image.load('map.png')" to load the image, and I found out that you can retrieve the image data using img.get_image_data().
I use line mapImage.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)
to read the data from... | [
"Your mapImage... returns a string with 4 characters representing rgba.\nTry this:\npix = mapImage.get_region(x,y,1,1).get_image_data().get_data(\"RGBA\", 4)\n\nprint 'r = ' + str(ord(pix[0]))\nprint 'g = ' + str(ord(pix[1]))\nprint 'b = ' + str(ord(pix[2]))\nprint 'a = ' + str(ord(pix[3]))\n\n"
] | [
1
] | [] | [] | [
"pixels",
"pyglet",
"python"
] | stackoverflow_0004200212_pixels_pyglet_python.txt |
Q:
[Python]How to launch a program using Thread
professionals
I know how to launch a command in Linux's terminal via process, sth likes following:
import subprocess
subprocess.Popen('ifconfig -a')
But this is opened in process, how can I launch that in a thread instead?
I know "thread.start_new_thread", while this s... | [Python]How to launch a program using Thread | professionals
I know how to launch a command in Linux's terminal via process, sth likes following:
import subprocess
subprocess.Popen('ifconfig -a')
But this is opened in process, how can I launch that in a thread instead?
I know "thread.start_new_thread", while this should call a function. Within the function, I stil... | [
"A command like ifconfig always runs in a separate process. There is no way to run that command within only a \"thread\" of your application.\nPerhaps you could provide more detail about why you believe this is necessary, and we may be able to suggest a different approach. For example, if you need to capture the ou... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004200742_python.txt |
Q:
Does the latest stable pygame release work with python2.7?
Like the subject says: Does the latest stable pygame release work with python2.7?
I've got both versions installed on my OSX Snow Leopard, but import pygame only works on python2.6 - That's the official distro which is 2.6.6, not the pre-installed one whic... | Does the latest stable pygame release work with python2.7? | Like the subject says: Does the latest stable pygame release work with python2.7?
I've got both versions installed on my OSX Snow Leopard, but import pygame only works on python2.6 - That's the official distro which is 2.6.6, not the pre-installed one which is 2.6.1).
And if it does work, how can I make it work on my m... | [
"My guess is that you installed it for 2.6 and so it is residing in 2.6's library directory. Install it in 2.7's library directory and you should be good to go. I don't know OSX so I can't help with the details but a little bit of googling shouldn't be too hard. The problem is that the two python installations have... | [
0
] | [] | [] | [
"macos",
"pygame",
"python"
] | stackoverflow_0004200644_macos_pygame_python.txt |
Q:
what methods does `foo < bar < baz` actually invoke?
In python we can say:
if foo < bar < baz:
do something.
and similarly, we can overload the comparision operators like:
class Bar:
def __lt__(self, other):
do something else
but what methods of the types of the operands of those interval compari... | what methods does `foo < bar < baz` actually invoke? | In python we can say:
if foo < bar < baz:
do something.
and similarly, we can overload the comparision operators like:
class Bar:
def __lt__(self, other):
do something else
but what methods of the types of the operands of those interval comparisions are actually called? is the above equivalent to
if ... | [
"if foo < bar < baz:\n\nis equivalent to\nif foo < bar and bar < baz:\n\nwith one important distinction: if bar is a mutating, it will be cached. I.e.:\nif foo < bar() < baz:\n\nis equivalent to\ntmp = bar()\nif foo < tmp and tmp < baz:\n\nBut to answer your question, it will end up being:\nif foo.__lt__(bar) and b... | [
13,
4,
3,
1
] | [] | [] | [
"operator_overloading",
"python"
] | stackoverflow_0004200822_operator_overloading_python.txt |
Q:
Overriding authenticate method - Django admin
I'm trying to figure out how to enhance the authenticate method with additional functionality.
e.g.
Expiring passwords
special password formats
length requirements
etc...
It is pretty straight forward for the site's frontend, but what about the admin panel?
I re... | Overriding authenticate method - Django admin | I'm trying to figure out how to enhance the authenticate method with additional functionality.
e.g.
Expiring passwords
special password formats
length requirements
etc...
It is pretty straight forward for the site's frontend, but what about the admin panel?
I reckon that I should override the User's Manager obje... | [
"You can create custom authentication backend by following the instructions in http://docs.djangoproject.com/en/dev/topics/auth/#authentication-backends. Essentially, you create a backend class that has an authenticate method:\nclass MyBackend:\n def authenticate(self, username=None, password=None):\n # C... | [
6,
0
] | [] | [] | [
"django",
"django_admin",
"django_authentication",
"django_models",
"python"
] | stackoverflow_0004197389_django_django_admin_django_authentication_django_models_python.txt |
Q:
python script output to webpage
I wrote a python script that reads in text from a file and writes a text file of definitions. I want to somehow integrate my program with a webpage for the whole world to see.
I want to be able to retrieve input text from one text box, have the python script process it, then displa... | python script output to webpage | I wrote a python script that reads in text from a file and writes a text file of definitions. I want to somehow integrate my program with a webpage for the whole world to see.
I want to be able to retrieve input text from one text box, have the python script process it, then display the output in the other text box.
... | [
"It's a much bigger question, involving:\n\nWhere are you going to host the site, \nHow slow is the script (can it execute in a few seconds or not), \nDoes it need access data from files or a database,\nHow complex is it,\netc.\n\nI would suggest you read about Django:\n\nhttp://docs.djangoproject.com/en/1.2/\n\nTh... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004201405_python.txt |
Q:
Using lxml to extract data where all elements are not known in advance
I have some sgml files that are roughly standardized. However, there can be data contained within a tag that I do not know exists before I open the file and personally read it. For example, the files have addresses and generally the addresses... | Using lxml to extract data where all elements are not known in advance | I have some sgml files that are roughly standardized. However, there can be data contained within a tag that I do not know exists before I open the file and personally read it. For example, the files have addresses and generally the addresses have a street, a city, a state, a zip and a phone. Each element of the ad... | [
"To get all the tags, we iter through the document like this:\nSuppose your XML structure is like this:\n<ADDRESS>\n <STREET>One Main Street</STREET>\n <CITY>Gotham City</CITY>\n <ZIP>99999 0123</ZIP>\n <PHONE>555-123-5467</PHONE>\n </ADDRESS>\n\nWe parse it:\n>>> from lxml import etree\n>>> f = etree.parse('foo.xm... | [
2
] | [] | [] | [
"lxml",
"parsing",
"python",
"sgml"
] | stackoverflow_0004201562_lxml_parsing_python_sgml.txt |
Q:
Ubuntu:What is the right way to reinstall from source after package was installed via apt?
I have a python package previously installed via apt(by default).
Now I want to install new version and compile it manually from the sources with all the required modules.
How can I do that?
I suppose that
apt-get purge pyt... | Ubuntu:What is the right way to reinstall from source after package was installed via apt? | I have a python package previously installed via apt(by default).
Now I want to install new version and compile it manually from the sources with all the required modules.
How can I do that?
I suppose that
apt-get purge python
And then install from sources is not possible because python have lots of dependencies and ... | [
"Don't replace your system's default Python interpreter. It can break things which will be difficult to fix later. Instead you probably want to use virtualenv. You can then isolate any issues from your environment and have the added advantage of multiple Python installations which can tested independently. \nHer... | [
1
] | [
"sudo apt-get remove name-of-package\n\nthen\nsudo apt-get autoclean\n\nwill remove the package and any dependencies that are no longer needed.\n"
] | [
-3
] | [
"compilation",
"debian",
"installation",
"python",
"ubuntu"
] | stackoverflow_0004199894_compilation_debian_installation_python_ubuntu.txt |
Q:
In django, how can I retrieve a value from db into a custom field template?
I am using a custom class on my model to provide image uploading, through an app called django-filebrowser.
# myapp/models.py
class Book(models.Model):
name = models.CharField(max_length=30)
image = FileBrowseField("Image", max_len... | In django, how can I retrieve a value from db into a custom field template? | I am using a custom class on my model to provide image uploading, through an app called django-filebrowser.
# myapp/models.py
class Book(models.Model):
name = models.CharField(max_length=30)
image = FileBrowseField("Image", max_length=200, blank=True, null=True)
...
The model uses filebrowser's custom fiel... | [
"Found a solution elsewhere, so I thought I'd share it:\n# models.py\nclass Book(models.Model):\n name = models.CharField(max_length=30)\n image = FileBrowseField(\"Image\", max_length=200, blank=True, null=True)\n\n...\n\n def __init__(self, *args, **kargs): ... | [
2
] | [] | [] | [
"django",
"django_filebrowser",
"django_models",
"python"
] | stackoverflow_0004194041_django_django_filebrowser_django_models_python.txt |
Q:
When does Python do automatic type conversion?
When does Python do automatic type conversion?
--
Update:
I asked this after reading this post: In praise of Go or : "Why I moved from Python and C++ to Go". The one of the points the poster makes is that:
It is statically typed, so it is more explicit and the code o... | When does Python do automatic type conversion? | When does Python do automatic type conversion?
--
Update:
I asked this after reading this post: In praise of Go or : "Why I moved from Python and C++ to Go". The one of the points the poster makes is that:
It is statically typed, so it is more explicit and the code of a third
party is more readable. Also it
elimi... | [
"It doesn't - it has duck typing instead.\n(I may have misunderstood what you meant by automatic type conversion, though, so it would help if you give more detail in your question.)\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004201941_python.txt |
Q:
Is it good form to have an __init__ method that checks the type of its input?
I have a class that wants to be initialized from a few possible inputs. However a combination of no function overloading and my relative inexperience with the language makes me unsure of how to proceed. Any advice?
A:
Check out this q... | Is it good form to have an __init__ method that checks the type of its input? | I have a class that wants to be initialized from a few possible inputs. However a combination of no function overloading and my relative inexperience with the language makes me unsure of how to proceed. Any advice?
| [
"Check out this question asked earlier.\nIn short, the recommendation is that you use classmethods or isinstance(), with classmethods being heavily favored.\n",
"With Python, you should use duck typing. Wikipedia has a good section on its use in Python at http://en.wikipedia.org/wiki/Duck_typing#In_Python\n",
"... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004201590_python.txt |
Q:
Python auto completing directory when I press tab (./)
I have a rather peculiar problem, when i'm working on Python in Max OSX terminal, my tab key no longer indents, it now inserts a ./
It seems it is auto-completing directories, if I press tab twice it lists directories, if i type in part of a directory and pre... | Python auto completing directory when I press tab (./) | I have a rather peculiar problem, when i'm working on Python in Max OSX terminal, my tab key no longer indents, it now inserts a ./
It seems it is auto-completing directories, if I press tab twice it lists directories, if i type in part of a directory and press tab it autocompletes. I understand this is a standard fun... | [
"It's a bug; see here for details. Most likely you are using the Python 2.7 from the python.org OS X 32-bit/64-bit installer for 10.5 and above or you are using a Python 2.7 or 3.2alpha built from source. If you are using 2.7, the easiest workaround is to install the other python.org OS X installer: the one for 3... | [
1
] | [] | [] | [
"autocomplete",
"macos",
"python",
"tabs",
"terminal"
] | stackoverflow_0004201791_autocomplete_macos_python_tabs_terminal.txt |
Q:
win32: get current DEVMODE of a monitor
How can I get the current resolution in win32? I know I can use GetMonitorInfo to get the current bounding rectangle of the monitor, but how can I also get the bit-depth? Pretty much, how do I get the DEVMODE struct of a given monitor?
I'm using python and pywin32, so solut... | win32: get current DEVMODE of a monitor | How can I get the current resolution in win32? I know I can use GetMonitorInfo to get the current bounding rectangle of the monitor, but how can I also get the bit-depth? Pretty much, how do I get the DEVMODE struct of a given monitor?
I'm using python and pywin32, so solutions addressing those specifically are nice, ... | [
"In addition to the EnumDisplayMonitors function mentioned in Dean's answer you need GetDeviceCaps(). See parameter BITSPIXEL: it gives you the number of adjacent color bits for each pixel.\n",
"You'll want to use the EnumDisplayMonitors function, which calls a callback for each monitor and passes the rectangle a... | [
1,
0
] | [] | [] | [
"monitor",
"python",
"pywin32",
"winapi"
] | stackoverflow_0004200560_monitor_python_pywin32_winapi.txt |
Q:
python 3: how to check if an object is a function?
Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?
How can I check that an object is a function?
I can do this I guess:
def is_function(x):
def tmp()
... | python 3: how to check if an object is a function? | Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?
How can I check that an object is a function?
I can do this I guess:
def is_function(x):
def tmp()
pass
return type(x) is type(tmp)
It doesn't seem n... | [
"in python2:\ncallable(fn)\n\nin python3:\nisinstance(fn, collections.Callable)\n\nas Callable is an Abstract Base Class, this is equivalent to:\nhasattr(fn, '__call__')\n\n",
"\nHow can I check that an object is a function?\n\nIsn't this same as checking for callables\nhasattr(object, '__call__')\n\nand also in ... | [
24,
5,
3
] | [
"try:\n magicVariable()\nexcept TypeError as e:\n print( 'was no function' )\n\n"
] | [
-4
] | [
"class",
"function",
"python",
"python_3.x"
] | stackoverflow_0004202301_class_function_python_python_3.x.txt |
Q:
xml file encryption with Python
i am making a mail client and i have made an option in which user can save his/her profile
and i saving all details in an xml file using SXML lib in python . now i want that file to be encrypted otherwise any one can see the details...How do i Do dat?
A:
I have been using a Recip... | xml file encryption with Python | i am making a mail client and i have made an option in which user can save his/her profile
and i saving all details in an xml file using SXML lib in python . now i want that file to be encrypted otherwise any one can see the details...How do i Do dat?
| [
"I have been using a Recipe from Active state for some time, you can find stronger algorithms but if you just need to keep away the curious it will be ok :)\nIf you really need a higher degree of confidence you can try pyDES and use a TripleDES for the encryptation.\nTripleDES\n",
"An easy way:\nAccept the passwo... | [
1,
0
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0004202577_encryption_python.txt |
Q:
Is there an include file for class statements in python?
I think this is almost certainly a very basic question but I'm struggling with it. I have 2 python files, one for the main content on my site and one for the admin area. You can see the two files here:
https://gist.github.com/670034
In both these files I def... | Is there an include file for class statements in python? | I think this is almost certainly a very basic question but I'm struggling with it. I have 2 python files, one for the main content on my site and one for the admin area. You can see the two files here:
https://gist.github.com/670034
In both these files I define the classes and import the necessary modules at the top an... | [
"Just create a file, like myimports.py:\nimport cgi\nimport os\n\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.a... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004202844_python.txt |
Q:
Extending Python with C++ no SWIG
OK so I have a C++ function with a header like this:
int myfunc(vector<int> a, vector<mystruct> b, vector<int> c)
I have written the wrapper code (using Python.h as I have done many times with C, which translates the Python data types into the vector datatypes and structs I use i... | Extending Python with C++ no SWIG | OK so I have a C++ function with a header like this:
int myfunc(vector<int> a, vector<mystruct> b, vector<int> c)
I have written the wrapper code (using Python.h as I have done many times with C, which translates the Python data types into the vector datatypes and structs I use in my program). The problem is I don't k... | [
"You should add language=\"c++\" to your Extension object:\nExtension(\"MyModule\", [\"myfunc.cpp\"], language=\"c++\")\n\n"
] | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004202627_c++_python.txt |
Q:
Is it worth learning C/C++ before learning Python?
I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
A:
In my opinion it's better to start learning Python.... | Is it worth learning C/C++ before learning Python? | I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
| [
"In my opinion it's better to start learning Python. \nI found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything.\nThe only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded ... | [
7,
4,
2,
1
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0004202455_c_c++_python.txt |
Q:
Python exception:"TypeError: main() got an unexpected keyword argument 'debug'" but IFF the module is run via scheduledTask on Windows XP SP2
Running Python 2.5 on Windows XP SP2.
When I run a Python script that calls a user-defined module called Zipper.py (basically a wrapper for a zipfile) using a Windows schedu... | Python exception:"TypeError: main() got an unexpected keyword argument 'debug'" but IFF the module is run via scheduledTask on Windows XP SP2 | Running Python 2.5 on Windows XP SP2.
When I run a Python script that calls a user-defined module called Zipper.py (basically a wrapper for a zipfile) using a Windows scheduledTask I get this exception:
Traceback (most recent call last):
File "C:\PythonScripts\ZipAndSendEOD-Reports.py", line 78, in main
... | [
"As Paul said, you're probably running a different version of Zipper.py - I would print out Zipper.__file__ and then if you need to debug, print out sys.path to see why it's finding a different file.\n"
] | [
3
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0004199535_exception_python.txt |
Q:
Using Elmer to execute Python in TCL; how do I handle keyword arguments?
I have a Python class that looks like this:
class Mine:
def __init__ (self, param1=None, param2=None, param3=None):
self.param1 = param1
self.param2 = param2
self.param3 = param3
What should my Elmer glue file loo... | Using Elmer to execute Python in TCL; how do I handle keyword arguments? | I have a Python class that looks like this:
class Mine:
def __init__ (self, param1=None, param2=None, param3=None):
self.param1 = param1
self.param2 = param2
self.param3 = param3
What should my Elmer glue file look like for this class? If they were all strings, I would guess this:
class Mi... | [
"Reading the elmer docs, I'd guess that you'd be best off using the guess type as it usually “does the right thing” (and you'll have to specify them all when doing the call).\nI don't know how it handles defaulted arguments or keyword lists; the documentation doesn't say at all (but looking at the code, I'd say tha... | [
0
] | [] | [] | [
"python",
"tcl"
] | stackoverflow_0004199053_python_tcl.txt |
Q:
CSS compilers in GAE Python
Are there any quick light python libraries to use compiled CSS that is converted to CSS on-the-fly?
A:
You can try CleverCSS:
http://sandbox.pocoo.org/clevercss/
Or the Python port of LessCSS: http://code.google.com/p/lesscss-python/
The Python version of LessCSS is quite new though, ... | CSS compilers in GAE Python | Are there any quick light python libraries to use compiled CSS that is converted to CSS on-the-fly?
| [
"You can try CleverCSS:\nhttp://sandbox.pocoo.org/clevercss/\nOr the Python port of LessCSS: http://code.google.com/p/lesscss-python/\nThe Python version of LessCSS is quite new though, it doesn't seem to be all that mature yet.\n"
] | [
1
] | [] | [] | [
"css",
"google_app_engine",
"python"
] | stackoverflow_0004203127_css_google_app_engine_python.txt |
Q:
django select widget doesnt update when i pass the choices into it
so im trying to update in my view a select widget as part of a form.
i'e seen tons of stuff on how to do it, i've followed it and got nearly there.
i've got a bit of code below which is called to populate the select with the choices and it does, bu... | django select widget doesnt update when i pass the choices into it | so im trying to update in my view a select widget as part of a form.
i'e seen tons of stuff on how to do it, i've followed it and got nearly there.
i've got a bit of code below which is called to populate the select with the choices and it does, but i think the formatting is out, as its passing back a unicode string an... | [
"What is this supposed to be doing? The format for a list of choices is a standard tuple:\nCHOICES = (\n ('x', 'choice x'),\n ('y', 'choice y'),\n)\n\nso I don't understand what you are trying to do with all that string formatting.\nSecondly, choices is not an element of the widget's attrs, it is an attribute... | [
1
] | [] | [] | [
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0004203347_django_forms_django_models_django_views_python.txt |
Q:
How to manage different distribution packages of the same Python package?
Is there a way (with distribute or another package) to manage different distributions (meaning different setup.py files) of the same Python package?
A:
You might have a look to buildout. With buildout you can have a single setup.py for a ... | How to manage different distribution packages of the same Python package? | Is there a way (with distribute or another package) to manage different distributions (meaning different setup.py files) of the same Python package?
| [
"You might have a look to buildout. With buildout you can have a single setup.py for a package and have multiple buildout configuration files that specify different ways of building that package with the other packages you want to have in the same distribution (including its version dependencies).\nI think with pip... | [
1
] | [] | [] | [
"distribution",
"packaging",
"python"
] | stackoverflow_0004204144_distribution_packaging_python.txt |
Q:
assignment in python
I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.
This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?
I guess there is no need for that in python:
Inmutable... | assignment in python | I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.
This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?
I guess there is no need for that in python:
Inmutable objects cannot be 'assign... | [
"I think you are right with your characterization of assignment in Python -- I just would like to add a different method of cloning and ways of assignment in special cases.\n\"Copy-constructing\" a mutable built-in Python object will yield a (shallow) copy of that object:\nl = [2, 3]\nm = list(l)\nl is m\n--> False... | [
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004204075_python.txt |
Q:
Real-time SQLite and PostgreSQL bi-directional synchronization using python
Is there any python library that can keep a client-side SQLite database in sync with a server-side PostgreSQL database?
There are solutions for Java, such as Daffodil or SymmetricDS. Is there something similar for python?
A:
SymmetricDS ... | Real-time SQLite and PostgreSQL bi-directional synchronization using python | Is there any python library that can keep a client-side SQLite database in sync with a server-side PostgreSQL database?
There are solutions for Java, such as Daffodil or SymmetricDS. Is there something similar for python?
| [
"SymmetricDS is a server-side solution for synchronization that gets triggered regardless of which language is being used to access the database. You should still be able to use that to synchronize the databases, while using Python libraries to actually query them. I would recommend sqlalchemy as a good database-in... | [
1
] | [] | [] | [
"database",
"python",
"synchronization"
] | stackoverflow_0002693002_database_python_synchronization.txt |
Q:
How to refresh/replace gtk.ToolItemGroup
I wrote this code, it's supposed to be a clipart browser (locked to "klip" folder under current directory).
When I start add signal at folder button (dbutton) I screw up: I don't know how to refresh the toolitemgroup content and icons keep appended, I can't remove manually ... | How to refresh/replace gtk.ToolItemGroup | I wrote this code, it's supposed to be a clipart browser (locked to "klip" folder under current directory).
When I start add signal at folder button (dbutton) I screw up: I don't know how to refresh the toolitemgroup content and icons keep appended, I can't remove manually since the button generated in loop.
And one mo... | [
"I solved this with:\nwhile browser.get_nth_item(0):\n browser.remove(browser.get_nth_item(0))\n\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004202919_gtk_pygtk_python.txt |
Q:
Overriding admin view methods - Django
I need to override the an add form within the admin panel.
I'm thinking of accomplishing this by writing a view which would then point to the admin view for the final result.
Something similar to this (where admin_basic_ass_user_view is the admin view)
@required_login
def add... | Overriding admin view methods - Django | I need to override the an add form within the admin panel.
I'm thinking of accomplishing this by writing a view which would then point to the admin view for the final result.
Something similar to this (where admin_basic_ass_user_view is the admin view)
@required_login
def add_user(request):
if condition:
re... | [
"Why not just override the relevant methods with your ModelAdmin subclass? That's why it's a class, after all.\n",
"Add something like this to your urls.py\n((r'^admin/auth/users/add/$', 'Project.SomeAPP.admin_views.add_user'),\n\nThe path needs to point to your new view. You should see the results of your new vi... | [
3,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004204504_django_django_admin_python.txt |
Q:
Locate "N Gram" substrings that are smallest distance away from a target string N character long
I am looking for an algorithm, preferably in Python that would help me locate substrings, N characters long, of exisiting strings that are closest to a target string N character long.
Consider the target string, that i... | Locate "N Gram" substrings that are smallest distance away from a target string N character long | I am looking for an algorithm, preferably in Python that would help me locate substrings, N characters long, of exisiting strings that are closest to a target string N character long.
Consider the target string, that is, say, 4 characters long, to be:
targetString -> '1111'
Assume this is the string I have available w... | [
"I believe you need Edit Distance. Peter Norvig's spelling corrector is an implementation example in python. Here's an implementation of Levenshtein Distance.\nSee also this question.\nEDIT:\nThis is fairly frequent in bioinformatics. See e.g. FASTA and BLAST. Bioinformatics has many flavors of this algorithm. See ... | [
3,
2,
1
] | [] | [] | [
"python",
"string",
"string_matching",
"substring"
] | stackoverflow_0004203142_python_string_string_matching_substring.txt |
Q:
Instant messenger streaming with libVLC python wrapper
I'm trying to develop an instant messenger client that supports video streaming. I am working with the libVLC wrapper for Python. Most basic functions of an IM client are already there, my problem comes with the video streaming. I've been able to do basic test... | Instant messenger streaming with libVLC python wrapper | I'm trying to develop an instant messenger client that supports video streaming. I am working with the libVLC wrapper for Python. Most basic functions of an IM client are already there, my problem comes with the video streaming. I've been able to do basic tests like streaming a video and playing it in a tkinter form wi... | [
"I don't think it will be easy.\nhttp://wiki.videolan.org/VideoLan_VideoConference#See_also might give you some clues as to directions to try...\n"
] | [
0
] | [] | [] | [
"instant_messaging",
"libvlc",
"python",
"streaming",
"vlc"
] | stackoverflow_0003824296_instant_messaging_libvlc_python_streaming_vlc.txt |
Q:
Python logging IndexError: list index out of range
I have an application the sets up the logging using:
logging.basicConfig(level=logging_level, format=format_string, filename=log_file, filemode='a')
then call
logging.debug("My Message")
etc. to log messeages. This work fine in most of my application, but then f... | Python logging IndexError: list index out of range | I have an application the sets up the logging using:
logging.basicConfig(level=logging_level, format=format_string, filename=log_file, filemode='a')
then call
logging.debug("My Message")
etc. to log messeages. This work fine in most of my application, but then for a particular module I get this error
File "C:\path\to... | [
"Doug Helmann's site has some guidance on using Python's logging module.\nThere are also some examples to be downloaded there, which I haven't tried.\n",
"Something seems very wrong with your installation - it's hard to see how a line like\nwhile logger:\n\nwould generate an IndexError.\nSo, delete all .pyc and .... | [
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004204764_logging_python.txt |
Q:
cgi scripts with no server
My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and t... | cgi scripts with no server | My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main progr... | [
"Well, there always has to be some kind of \"server\" involved to communicate over HTTP. You could have a python script listening on port 80 on your machine, that in turn runs the scripts specified with the form's action attribute.\nYou won't get away without some sort of server, I'm afraid.\nPS: There are already ... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004205697_python.txt |
Q:
How to properly encode image URL with equal sign for Facebook open graph tag
I have a page with an Open Graph image tag:
<meta property="og:image" content="http://childhumor2.homeip.net:9009/_ah/img/RYCF7Ty7wODp9R-N_QIWYA===s200"/>
The image is a GAE blob and the URL comes from calling get_serving_url. The URL w... | How to properly encode image URL with equal sign for Facebook open graph tag | I have a page with an Open Graph image tag:
<meta property="og:image" content="http://childhumor2.homeip.net:9009/_ah/img/RYCF7Ty7wODp9R-N_QIWYA===s200"/>
The image is a GAE blob and the URL comes from calling get_serving_url. The URL works fine normally.
Now, if someone likes this page, the thumbnail image that is... | [
"It is probably the case that Facebook should be unquoting the value so that it matches the original og:image you listed, and you should write a bug for that (as Nathan suggested).\nHowever, technically speaking %3D and = have the same meaning in the path section of a URL and should be treated equally so that might... | [
3,
1,
0
] | [] | [] | [
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0004179906_facebook_google_app_engine_python.txt |
Q:
How to force a ndarray show in normal way instead of scientific notation?
I'm trying to print a ndarray on the screen. But python always shows it in scientific notation, which I don't like. For a scalar we can use
>>> print '%2.4f' %(7.47212470e-01)
0.7472
But how to do that for a numpy.ndarray like this :
[[ 7... | How to force a ndarray show in normal way instead of scientific notation? | I'm trying to print a ndarray on the screen. But python always shows it in scientific notation, which I don't like. For a scalar we can use
>>> print '%2.4f' %(7.47212470e-01)
0.7472
But how to do that for a numpy.ndarray like this :
[[ 7.47212470e-01 3.71730070e-01 1.16736538e-01 1.22172891e-02]
[ 2.7927964... | [
"The numpy.set_string_function function can be used to change the string representation of arrays.\nYou can also use numpy.set_print_options to change the precision used by default and turn off reporting of small numbers in scientific notation.\nFrom the examples for set_print_options:\n>>> np.set_printoptions(prec... | [
10,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python",
"scientific_notation"
] | stackoverflow_0004205259_arrays_matrix_numpy_python_scientific_notation.txt |
Q:
How do you extend Django's sitemap module to create more complex sitemaps?
I have a supplier that wants a sitemap that contains much more meta data than what you would see in a normal search engine sitemap. As a result I would like find a tidy way of extending django's sitemap module. Has anyone done this? Or coul... | How do you extend Django's sitemap module to create more complex sitemaps? | I have a supplier that wants a sitemap that contains much more meta data than what you would see in a normal search engine sitemap. As a result I would like find a tidy way of extending django's sitemap module. Has anyone done this? Or could you provide this django Noob with the code to do it?
Mike
| [
"If you really wanted to do this you would need to extend django.contrib.sitemaps.Sitemap.get_urls to add the additional meta information to the url_info dictionary. The current get_urls is given below from django.contrib.sitemaps:\ndef get_urls(self, page=1, site=None):\n if site is None:\n if Site._meta... | [
2
] | [] | [] | [
"django",
"python",
"sitemap"
] | stackoverflow_0004204211_django_python_sitemap.txt |
Q:
Launch python into a mac application
I have a software written in python with a graphical user interface written in PyQt.
To create an executable of the software I ship with it a Python and a Qt precompiled version and the trick seems to work in windows and linux since I know How to create an istaller.
The problem... | Launch python into a mac application | I have a software written in python with a graphical user interface written in PyQt.
To create an executable of the software I ship with it a Python and a Qt precompiled version and the trick seems to work in windows and linux since I know How to create an istaller.
The problem is to embed evrything into a mac .app
To ... | [
"I just use py2app.\n"
] | [
3
] | [] | [] | [
"macos",
"python",
"shipping"
] | stackoverflow_0004206511_macos_python_shipping.txt |
Q:
Source Code in Bullet Lists with reStructuredText
I am trying to include source code in bullet lists with reStructuredText; like this:
- List item 1 ::
code sample...
code sample...
- List item 2 ::
code sample...
code sample...
However, I get the following warning:
System Message: WARNING/2
Literal b... | Source Code in Bullet Lists with reStructuredText | I am trying to include source code in bullet lists with reStructuredText; like this:
- List item 1 ::
code sample...
code sample...
- List item 2 ::
code sample...
code sample...
However, I get the following warning:
System Message: WARNING/2
Literal block expected; none found.
The empty lines in the list ... | [
"You haven't indented enough. Think of it this way.\n- List item 1 \n ::\n\n code sample...\n code sample...\n\n- List item 2 \n ::\n\n code sample...\n code sample...\n\n"
] | [
38
] | [] | [] | [
"documentation",
"python",
"restructuredtext"
] | stackoverflow_0004206393_documentation_python_restructuredtext.txt |
Q:
Django + apache & mod_wsgi: having to restart apache after changes
I configured my development server this way:
Ubuntu, Apache, mod_wsgi, Python 2.6
I work on the server from another computer connected to it.
Most of the times the changes don't affect the application unless I restart Apache.
In some cases the chan... | Django + apache & mod_wsgi: having to restart apache after changes | I configured my development server this way:
Ubuntu, Apache, mod_wsgi, Python 2.6
I work on the server from another computer connected to it.
Most of the times the changes don't affect the application unless I restart Apache.
In some cases the changes take effect without restarting the webserver, but after let's say 3 ... | [
"My suggestion is that you run the application in daemon mode. \nThis way you won't be required to restart apache,\njust touch my_handler.wsgi and the daemon will know to restart the app. The apache httpd will not be only yours (in production) so it is fair not to restart it on every update.\n",
"No changes requi... | [
22,
6,
0
] | [] | [] | [
"apache",
"django",
"django_wsgi",
"mod_wsgi",
"python"
] | stackoverflow_0004206000_apache_django_django_wsgi_mod_wsgi_python.txt |
Q:
How to generate several matplotlib charts at a time?
I would like to generate several charts and save them as .png files.
But it seems matplotlib is overlapping the next chart on the previous one :
def do_pie(fic,data):
import pylab
# make a square figure and axes
pylab.figure(1, figsize=(6,6))
... | How to generate several matplotlib charts at a time? | I would like to generate several charts and save them as .png files.
But it seems matplotlib is overlapping the next chart on the previous one :
def do_pie(fic,data):
import pylab
# make a square figure and axes
pylab.figure(1, figsize=(6,6))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(dat... | [
"Just close the figure object after you save it.\ndef do_pie(fic,data):\n import pylab \n # make a square figure and axes\n pylab.figure(1, figsize=(6,6))\n ax = pylab.axes([0.1, 0.1, 0.8, 0.8])\n pylab.pie(data,labels=data)\n pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})\n pylab.savef... | [
3,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004206175_matplotlib_python.txt |
Q:
How to create a datetime object with PyYAML
I'd like to be able to create a datetime object with datetime.datetime.now() PyYAML. It's easy to call some functions:
>>> y = """#YAML
... description: Something
... ts: !!python/object/apply:time.time []"""
>>> yaml.load(y)
{'description': 'Something', 'ts': 128995556... | How to create a datetime object with PyYAML | I'd like to be able to create a datetime object with datetime.datetime.now() PyYAML. It's easy to call some functions:
>>> y = """#YAML
... description: Something
... ts: !!python/object/apply:time.time []"""
>>> yaml.load(y)
{'description': 'Something', 'ts': 1289955567.940973}
>>>
However, I can't seem to figure o... | [
"I think this example achieves what you're looking for:\ndt = yaml.load(\"\"\"dt: !!python/object/apply:apply\n - !!python/object/apply:getattr\n - !!python/name:datetime.datetime\n - now\n - []\n\"\"\")\n\nHowever, I think it is too far-fetched because the !!python/object syntax supported by Py... | [
9
] | [] | [] | [
"python",
"pyyaml",
"yaml"
] | stackoverflow_0004200627_python_pyyaml_yaml.txt |
Q:
Scratch disks in Python?
I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I un... | Scratch disks in Python? | I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for t... | [
"Until you ACTUALLY run out of memory, thinking about this is a waste of time.\nWhen you finally do run out of memory, you'll need to use a temporary file to store objects that your process needs, but can't fit into memory.\nUse pickle or shelve (see Data Persistence) your objects in a file. If that file happens t... | [
4,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"memory_management",
"python",
"windows"
] | stackoverflow_0000737947_memory_management_python_windows.txt |
Q:
Determine "wiggliness" of set of data - Python
I'm working on a piece of software which needs to implement the wiggliness of a set of data. Here's a sample of the input I would receive, merged with the lightness plot of each vertical pixel strip:
It is easy to see that the left margin is really wiggly (i.e. has a... | Determine "wiggliness" of set of data - Python | I'm working on a piece of software which needs to implement the wiggliness of a set of data. Here's a sample of the input I would receive, merged with the lightness plot of each vertical pixel strip:
It is easy to see that the left margin is really wiggly (i.e. has a ton of minima/maxima), and I want to generate a set... | [
"Take a look at lowpass/highpass/notch/bandpass filters, fourier transforms, or wavelets. The basic idea is there's lots of different ways to figure out the frequency content of a signal quantized over different time-periods.\nIf we can figure out what wiggliness is, that would help. I would say the leftmost marg... | [
5,
1
] | [] | [] | [
"frequency_analysis",
"frequency_distribution",
"list",
"python",
"statistics"
] | stackoverflow_0004191674_frequency_analysis_frequency_distribution_list_python_statistics.txt |
Q:
Getting last (newest) element with lxml,python
Hey everyone, I have had some amazing help the past couple days in trying to solve my issue. I just have one last questions (I hope) :)
I am trying to get the last element from my xml and place it in a variable. I am using django,python and the lxml library.
What I ... | Getting last (newest) element with lxml,python | Hey everyone, I have had some amazing help the past couple days in trying to solve my issue. I just have one last questions (I hope) :)
I am trying to get the last element from my xml and place it in a variable. I am using django,python and the lxml library.
What I want to do is, go through the XML that I have got fr... | [
"Change [0] to [-1] to select the last element in the list:\napi_id = int(data.xpath('//project/id/text()')[-1])\n\nNote that this may not give you the largest id value if the largest is not at the end of the list.\nTo get the largest id, you could do this:\napi_id = max(map(int,data.xpath('//project/id/text()')))\... | [
5
] | [] | [] | [
"django",
"django_views",
"lxml",
"python"
] | stackoverflow_0004207012_django_django_views_lxml_python.txt |
Q:
Named entity recognition with preset list of names for Python / PHP
I'm trying to process a CSV file that has as in each row a text field with the name of organization and position of an individual within that organization as unstructured text. This field is usually a mess of text like this:
Assoc. Research Profe... | Named entity recognition with preset list of names for Python / PHP | I'm trying to process a CSV file that has as in each row a text field with the name of organization and position of an individual within that organization as unstructured text. This field is usually a mess of text like this:
Assoc. Research Professor Dept. Psychology Univ. California Santa Barbara
I need to pull o... | [
"This is within the domain of fuzzy logic. See if these are of any help:\nhttp://www.phpclasses.org/blog/post/119-Neural-Networks-in-PHP.html\nhttp://ann.thwien.de/index.php/Installation\n",
"You may be able to use difflib to calculate the similarity ratio between the CSV input and the canonical spelling, and con... | [
2,
1
] | [] | [] | [
"named_entity_recognition",
"nlp",
"php",
"python",
"text"
] | stackoverflow_0004206882_named_entity_recognition_nlp_php_python_text.txt |
Q:
How do I iterate through all possible values in a series of fixed lists?
(python)
so I have the following values & lists:
name = colour
size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768']
depth = ['8', '16', '32']
scalar = ['False', 'True']
alpha = ['False', 'True']
colour = app.Color(0.5)
and... | How do I iterate through all possible values in a series of fixed lists? | (python)
so I have the following values & lists:
name = colour
size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768']
depth = ['8', '16', '32']
scalar = ['False', 'True']
alpha = ['False', 'True']
colour = app.Color(0.5)
and I want to iterate over these to produce every possible combination with the f... | [
"import itertools\nfor iter in itertools.product(size, depth, scalar, alpha):\n print iter # prints 96 four-element tuples\n\n",
"from itertools import product\n\n# generates all the possible values\ncombinations = product(size, depth, scalar, alpha)\n# call the function for each combination\n# i guess `names`... | [
7,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004207122_python.txt |
Q:
taking log of very small values using numpy/scipy in Python
I have an Nx1 array that corresponds to a probability distribution, i.e. the sum of the elements sums to 1. This is represented as a regular numpy array. Since N might be relatively large, e.g. 10 or 20, many of the individual elements are pretty close ... | taking log of very small values using numpy/scipy in Python | I have an Nx1 array that corresponds to a probability distribution, i.e. the sum of the elements sums to 1. This is represented as a regular numpy array. Since N might be relatively large, e.g. 10 or 20, many of the individual elements are pretty close to 0. I find that when I take log(my_array), I get the error "Fl... | [
"You can just drop the tails according to the accuracy you need.\neps = 1e-50\narray[array<eps]=eps\nlog(array)\n\n",
"What's pretty close to zero ?\n>>> np.log(0)\n-inf\n>>> 0.*np.log(0)\nnan\n>>> np.log(1e-200)\n-460.51701859880916\n>>> 1e-200*np.log(1e-200)\n-4.6051701859880914e-198\n\nOne solution is to add a... | [
3,
2,
1,
0
] | [] | [] | [
"numerical_methods",
"numpy",
"python",
"scipy"
] | stackoverflow_0004206528_numerical_methods_numpy_python_scipy.txt |
Q:
how to set up environment variables for python
On WinXP sp2 I'd like to have a directory of modules that other python scripts will be using called "SharedPython" in the same directory as my python scripts. so, basically:
/pythonScripts
/pythonScripts/SharedPython
as well as other python scripts on the same l... | how to set up environment variables for python | On WinXP sp2 I'd like to have a directory of modules that other python scripts will be using called "SharedPython" in the same directory as my python scripts. so, basically:
/pythonScripts
/pythonScripts/SharedPython
as well as other python scripts on the same level as the SharedPython directory.
when I run
pr... | [
"You need the PYTHONPATH env var. The dirs listed in it are prepended to sys.path.\nThe correct way to setup PYTHONPATH in your case is:\nset PYTHONPATH=%PYTHONPATH%;C:\\PythonScripts\\SharedPython\n\nNote the semicolon between the second % and the C:\\\n",
"Those paths are added by the site module; do not chang... | [
5,
1
] | [] | [] | [
"environment_variables",
"python"
] | stackoverflow_0004207173_environment_variables_python.txt |
Q:
Parse WAV file header
I am writing a program to parse a WAV file header and print the information to the screen. Before writing the program i am doing some research
hexdump -n 48 sound_file_8000hz.wav
00000000 52 49 46 46 bc af 01 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 01 00... | Parse WAV file header | I am writing a program to parse a WAV file header and print the information to the screen. Before writing the program i am doing some research
hexdump -n 48 sound_file_8000hz.wav
00000000 52 49 46 46 bc af 01 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 01 00 >40 1f 00 00< 40 1f 00 00... | [
"The \"40 1F 00 00\" bytes equate to an integer whose hexadecimal value is 00001F40 (remember that the integers are stored in a WAVE file in the little endian format). A value of 00001F40 in hexadecimal equates to a decimal value of 8000.\nSimilarly, the \"44 AC 00 00\" bytes equate to an integer whose hexadecimal ... | [
8,
5
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0004207326_python_wav.txt |
Q:
Why do elements in Python for ... in ...: statements use byValue behavior?
I can't seem to find an explanation anywhere for this...
Suppose I have a vector y initialized to all zeroes:
from numpy import *
y = zeros(5)
It could also be a plain python array, I don't think it really matters.
I noticed that the behav... | Why do elements in Python for ... in ...: statements use byValue behavior? | I can't seem to find an explanation anywhere for this...
Suppose I have a vector y initialized to all zeroes:
from numpy import *
y = zeros(5)
It could also be a plain python array, I don't think it really matters.
I noticed that the behavior of the for x in y: statement is that it makes a copy of each element in y, t... | [
"You can replace this:\ny = np.zeros(5)\nfor i in range(len(y)):\n y[i] = 2*rand()-1\n\nwith:\ny=2*np.random.rand(5)-1\n\n\nIf y is a Python sequence (tuple, list, array, etc) or Numpy array,\nfor x in y:\niterates through y, setting x to each element in y.\nIf the elements are immutable objects like str, int, f... | [
8,
4,
1,
0
] | [] | [] | [
"iteration",
"numpy",
"python"
] | stackoverflow_0004207231_iteration_numpy_python.txt |
Q:
Why is aptitude not installing python-mysqldb properly? ( error: No module named MySQLdb )
username@servername Tue Nov 02 22:08:28 ~/public_html/IDM_app
$ sudo aptitude install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state... | Why is aptitude not installing python-mysqldb properly? ( error: No module named MySQLdb ) | username@servername Tue Nov 02 22:08:28 ~/public_html/IDM_app
$ sudo aptitude install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be in... | [
"The fix was:\nsudo aptitude install libmysqlclient-dev\n\nsudo easy_install MySQL-python \n\n",
"First, try dpkg -L python-mysqldb, then you'll see what's installed.\nSecond, you are obviously using a manully compiled Python 2.7, while Ubuntu installs its packages for Python 2.6, which is the current default. Yo... | [
2,
1
] | [] | [] | [
"aptitude",
"mysql",
"python"
] | stackoverflow_0004088397_aptitude_mysql_python.txt |
Q:
Use WTForms with webapp and Django templates on Google App Engine
I'm trying to use WTForms with webapp without much luck.
I would like to be able to use the form_field templatetag, as shown in the documentation:
{% form_field form.username class="big_text" onclick="do_something()" %}
I've got WTForms installed fi... | Use WTForms with webapp and Django templates on Google App Engine | I'm trying to use WTForms with webapp without much luck.
I would like to be able to use the form_field templatetag, as shown in the documentation:
{% form_field form.username class="big_text" onclick="do_something()" %}
I've got WTForms installed fine in my application, but its Django template tags isn't working for me... | [
"I recommend jinja2 templates over django: http://jinja.pocoo.org/ It's based on the django templates but more powerful and easy to use. I don't think it's a good idea to use Django templates without the django stack. Also, if you want a more structured framework, a VERY nice minimalist framework is Flask: http://w... | [
5
] | [] | [] | [
"django_templates",
"google_app_engine",
"python",
"wtforms"
] | stackoverflow_0004207590_django_templates_google_app_engine_python_wtforms.txt |
Q:
Parameterizing 'SELECT IN (...)' queries
I want to use MySQLdb to create a parameterized query such as:
serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))
But what ends up being send to the DBMS is:
select * from table where key in ("'0123456'", "'0123457'")
Is it p... | Parameterizing 'SELECT IN (...)' queries | I want to use MySQLdb to create a parameterized query such as:
serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))
But what ends up being send to the DBMS is:
select * from table where key in ("'0123456'", "'0123457'")
Is it possible to create a parameterized query like t... | [
"You want something like this, I think:\nquery = 'select * from table where key in (%s)' % ','.join('?' * len(serials))\nc.execute(query, serials)\n\n"
] | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004207787_mysql_python.txt |
Q:
Django settings based on IP or hostname
I'd like to have something in my settings like
if ip in DEV_IPS:
SOMESETTING = 'foo'
else:
SOMESETTING = 'bar'
Is there an easy way to get the ip or hostname - also - is this is a bad idea ?
A:
import socket
socket.gethostbyname(socket.gethostname())
However, I'd r... | Django settings based on IP or hostname | I'd like to have something in my settings like
if ip in DEV_IPS:
SOMESETTING = 'foo'
else:
SOMESETTING = 'bar'
Is there an easy way to get the ip or hostname - also - is this is a bad idea ?
| [
"import socket\nsocket.gethostbyname(socket.gethostname())\n\nHowever, I'd recommend against this and instead maintain multiple settings file for each environment you're working with.\nsettings/__init__.py\nsettings/qa.py \nsettings/production.py\n\n__init__.py has all of your defaults. At the top of qa.py, and an... | [
12,
3
] | [] | [] | [
"django",
"hostname",
"ip",
"python",
"settings"
] | stackoverflow_0004207762_django_hostname_ip_python_settings.txt |
Q:
Python - urllib2 timeout
I got something below is snippet of my code
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
fetch_timeout = 12
self.response = opener.open(url, timeout=fetch_timeout)
however, it code still waits 60~ seconds before ... | Python - urllib2 timeout | I got something below is snippet of my code
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
fetch_timeout = 12
self.response = opener.open(url, timeout=fetch_timeout)
however, it code still waits 60~ seconds before timing out...
Any clues?
| [
"At a guess you probably need to set the socket timeout\nimport socket\n\ndefault_timeout = 12\n\nsocket.setdefaulttimeout(default_timeout)\n\n",
"Which version are you using. It was added in 2.6\nAlso the method is \nurllib2.urlopen(url[, data][, timeout])\n\nCan you try providing \nself.response = opener.open(u... | [
3,
2,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004207983_python_urllib2.txt |
Q:
How can I send in-body images in a mail using python?
how can i send in-body attached images in a mail using python?
I found this: http://docs.python.org/library/email-examples.html but it has not an example with images.
Thanks!
A:
Take a look at the big example of "how to send the entire contents of a directory... | How can I send in-body images in a mail using python? | how can i send in-body attached images in a mail using python?
I found this: http://docs.python.org/library/email-examples.html but it has not an example with images.
Thanks!
| [
"Take a look at the big example of \"how to send the entire contents of a directory as an email message\". The image in the file fp is converted into the message part msg here:\nmsg = MIMEImage(fp.read(), _subtype=subtype)\n\nand then the message part is attached to the outer message here:\nmsg.add_header('Content-... | [
2,
0
] | [] | [] | [
"attachment",
"email",
"image",
"python"
] | stackoverflow_0004208007_attachment_email_image_python.txt |
Q:
How are Google App Engine model classes stored?
I'm in doubt how the objects are stored. Say I have a class defined like:
class SomeEntity(db.Model):
some_number = db.IntegerProperty(required=True)
def calculate_something(self):
return self.some_number * 2
My guess is that the only thing stored i... | How are Google App Engine model classes stored? | I'm in doubt how the objects are stored. Say I have a class defined like:
class SomeEntity(db.Model):
some_number = db.IntegerProperty(required=True)
def calculate_something(self):
return self.some_number * 2
My guess is that the only thing stored in the data store is the name/value/type of some_numbe... | [
"Entities are stored in the datastore in a protobuf representation (including its key - which includes your App ID and the entity's Kind). The Life of a Datastore Write article talks more about the representation of entities and how they are written to the datastore. Check out the rest of the articles in this ser... | [
10,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004208103_google_app_engine_google_cloud_datastore_python.txt |
Q:
Please help me understand the output of this assertMultiLineEqual failure
This is the output from a failed assertMultiLineEqual:
- </group></row></resultset>+ </group></row></resultset>
? +
I have no idea what this means and why its complaining about it being different. My script genera... | Please help me understand the output of this assertMultiLineEqual failure | This is the output from a failed assertMultiLineEqual:
- </group></row></resultset>+ </group></row></resultset>
? +
I have no idea what this means and why its complaining about it being different. My script generates an XML string and I want to compare it to the contents of an XML file. I t... | [
"It looks like one of the strings ends with a newline character, and the other doesn't.\n"
] | [
2
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0004208196_python_testing.txt |
Q:
Comparing sql values
I'm using sqlite with python. I'm implementing the POP3 protocol. I have a table
msg_id text
date text
from_sender text
subject text
body text
hashkey text
Now I need to check for duplicate messages by checking the message id of the message retrieved against the existing msg_id's in the tab... | Comparing sql values | I'm using sqlite with python. I'm implementing the POP3 protocol. I have a table
msg_id text
date text
from_sender text
subject text
body text
hashkey text
Now I need to check for duplicate messages by checking the message id of the message retrieved against the existing msg_id's in the table. I encrypted the msg_id... | [
"Well, if your only problem is with the comparison, then you could try:\nif m.hexdigest() == row[0]:\n\nsince row is a tuple and not a string, but your basic strategy seems wrong to me. You're retrieving the hashkey for every row from the database, and then doing your own search for the right one. Much better to ma... | [
4,
0,
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0004208146_python_sql_sqlite.txt |
Q:
What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files?
I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file... | What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files? | I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file:
[parameters]
# Host
host = stackoverflow.com
port = 22
To read these values into my code, I do
import ConfigParser
con... | [
"\nSo what do I gain from using the ConfigParser module?\n\nCompatibility with Windows .ini files. Makes some people happy.\n\nWhat are the pros and cons of each approach?\n\nConfigParser has limited syntax and some relatively simple things get very contrived. Look at logging for examples.\nPython syntax is simpl... | [
11,
6,
4
] | [] | [] | [
"configuration",
"configuration_files",
"module",
"python"
] | stackoverflow_0004208323_configuration_configuration_files_module_python.txt |
Q:
How to make python module installer for windows?
How to make python module installer for windows?
I have python (2.7 if that makes difference) module which wrapped functionality around C-lib and would like to make an installer with build lib to make installation easy.
A:
Using distutils, you can write a setup fi... | How to make python module installer for windows? | How to make python module installer for windows?
I have python (2.7 if that makes difference) module which wrapped functionality around C-lib and would like to make an installer with build lib to make installation easy.
| [
"Using distutils, you can write a setup file that would compile your libs and install them\n\nhttp://docs.python.org/library/distutils.html\nhttp://docs.python.org/distutils/index.html#distutils-index\n\nSee this example setup.py which also compiles \"c\" lib for different platforms.\n\nhttp://code.google.com/p/psu... | [
4
] | [] | [] | [
"installation",
"python",
"windows"
] | stackoverflow_0004208532_installation_python_windows.txt |
Q:
Alternative to singleton?
I'm a Python & App Engine (and server-side!) newbie, and I'm trying to create very simple CMS. Each deployment of the application would have one -and only one -company object, instantiated from something like:
class Company(db.Model):
name = db.StringPropery()
profile = db.TextPro... | Alternative to singleton? | I'm a Python & App Engine (and server-side!) newbie, and I'm trying to create very simple CMS. Each deployment of the application would have one -and only one -company object, instantiated from something like:
class Company(db.Model):
name = db.StringPropery()
profile = db.TextProperty()
addr = db.TextPrope... | [
"Global variables are \"app-cached.\" This means that each particular instance of your app will remember these variables' values between requests. However, when an instance is shutdown these values will be lost. Thus I do not think you really want to store these values in module-level variables (unless they are ... | [
2,
2,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004208390_google_app_engine_google_cloud_datastore_python.txt |
Q:
Executing several Python scripts at same time causes PHP/Apache to hang
I'm trying to execute a few python scripts in order to manipulate some images on my website. The external program/tool is written in python and is called PHATCH. I'm under Windows and using WAMP as my web server.
Executing only just one script... | Executing several Python scripts at same time causes PHP/Apache to hang | I'm trying to execute a few python scripts in order to manipulate some images on my website. The external program/tool is written in python and is called PHATCH. I'm under Windows and using WAMP as my web server.
Executing only just one script seems to work well, but I need to execute 4 scripts at the same time (to gen... | [
"Can multiple copies of phatch be executed simultaneously from the same account? Have you tried this without PHP and Apache?\nit is possible that multiple copies starting at the same time access the same files, perhaps use the same temporary files (even with unique names, if the name is based on time, they might ha... | [
0
] | [] | [] | [
"exec",
"php",
"python",
"system"
] | stackoverflow_0004208573_exec_php_python_system.txt |
Q:
Python: Write a program to find the time period(s) of the largest price drop(s)
i am suppose to solve this question but i am stuck.
Write a program to find the time period(s) of the largest price drop(s) when a list of price(s) is given. For instance, if the list is [300,301,303,299,300,298,301,305], then there is... | Python: Write a program to find the time period(s) of the largest price drop(s) | i am suppose to solve this question but i am stuck.
Write a program to find the time period(s) of the largest price drop(s) when a list of price(s) is given. For instance, if the list is [300,301,303,299,300,298,301,305], then there is one period of the largest price drop: from time 2 with price 303 to time 5 with pric... | [
"You want the maximum sum contiguous sequence, but inverted. This page has the best explanation of it I have seen.\nThe basic algorithm will look like this:\n>>> def min_sum_subsequence(seq):\n... minsofar = 0\n... minendinghere = 0\n... for s in seq:\n... # invariant: maxendinghere and maxsofar... | [
5,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004204807_python.txt |
Q:
Help needed to convert code from C# to Python
Can you please convert this code from C# to Python to be run on IronPython?
I don’t have any experience with Python.
using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
... | Help needed to convert code from C# to Python | Can you please convert this code from C# to Python to be run on IronPython?
I don’t have any experience with Python.
using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Conne... | [
"Instantiation doesn't require a type definition. Methods called the same, assign delegates directly. The previous answer is absolutely right, you'll need a lot more context in order to \"convert\" a C# application to Python; it's more than just syntax.\nfoo = Portal(\"Foo\")\n\nbar = Agent(\"bar\")\n\nfoo.Connect(... | [
5,
2,
2
] | [
"In case someone else has this question SharpDevelop has a conversion utility to convert between C# and IronPython, VB.NET or Boo\nhttp://community.sharpdevelop.net/blogs/mattward/archive/2009/05/11/ConvertingCSharpVBNetCodeToIronPython.aspx\n"
] | [
-1
] | [
".net",
"c#",
"ironpython",
"python"
] | stackoverflow_0000542908_.net_c#_ironpython_python.txt |
Q:
When to use sys.path.append and when modifying %PYTHONPATH% is enough
So, it turned out i was missing a semi-colon from my PYTHONPATH definition. But this only got me so far. for some reason, my script did NOT work as a scheduled task (on WinXP) until I explicitly added a directory from PYTHONPATH to the top of my... | When to use sys.path.append and when modifying %PYTHONPATH% is enough | So, it turned out i was missing a semi-colon from my PYTHONPATH definition. But this only got me so far. for some reason, my script did NOT work as a scheduled task (on WinXP) until I explicitly added a directory from PYTHONPATH to the top of my script.
Question is:
When do I need to explicitly append something to my p... | [
"Perhaps you're not running the scheduled task under the right credentials (log-in name). When you define environment variables in System Properties dialog, they can be either User-level or System-level. If you defined PYTHONPATH as User-level then your scheduled task must run as that user for it to be set properly... | [
4,
0
] | [] | [] | [
"environment_variables",
"python"
] | stackoverflow_0004208659_environment_variables_python.txt |
Q:
importing from higher directories in python
Possible Duplicate:
How to do relative imports in Python?
How do I import from a higher level directory in python.
For example:
I have project/lib/lib.py
project/stuff/main.py
i want to import lib.py in main.py
Thanks in advance
A:
You can do it like:
from ..lib impo... | importing from higher directories in python |
Possible Duplicate:
How to do relative imports in Python?
How do I import from a higher level directory in python.
For example:
I have project/lib/lib.py
project/stuff/main.py
i want to import lib.py in main.py
Thanks in advance
| [
"You can do it like:\nfrom ..lib import lib\n\n",
"standard method is to add project to your path and do\nimport lib.lib\n\nYou will need a file called __init__.py in the lib folder as well, which can be blank.\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004209214_python.txt |
Q:
Django: Having unique extension numbers associated with a client, but same extension number associated with another client
I'm working on a project where I have models: Client, User, and Extensions, just to make this simple.
A User has to be associated with one Client in order to have an Extension number.
A User c... | Django: Having unique extension numbers associated with a client, but same extension number associated with another client | I'm working on a project where I have models: Client, User, and Extensions, just to make this simple.
A User has to be associated with one Client in order to have an Extension number.
A User can have extensions, say, 100 and 101.
Another User, associated with another Client, can have the same extensions 100 and 101.
So... | [
"Use Meta.unique_together on user and number in Extension.\nclass Extension(...):\n ...\n class Meta:\n unique_together = (('user', 'number'),)\n\n"
] | [
5
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004209345_django_django_admin_django_models_python.txt |
Q:
How to raise a 410 error in Django
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message'), I would like to instead call raise Http410('some error message') shortcut.
I am confused because in django.http, the function... | How to raise a 410 error in Django | I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message'), I would like to instead call raise Http410('some error message') shortcut.
I am confused because in django.http, the function Http404 is simply:
class Http404(Except... | [
"from django.http import HttpResponse\nreturn HttpResponse(status=410)\n\n",
"Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a middleware.\nclass MyGoneMiddleware... | [
24,
16,
11
] | [] | [] | [
"django",
"error_handling",
"http_status_code_410",
"httpresponse",
"python"
] | stackoverflow_0004208572_django_error_handling_http_status_code_410_httpresponse_python.txt |
Q:
Why do I get PROCEDURE does not exist when using callproc() in Django?
So I'm trying to use a stored procedure via a cursor and callproc() but I always get the error:
OperationalError: (1305, 'PROCEDURE myapp.LatLonDistance does not exist')
Here's the chunk of code that throws the error in my app:
cursor = connec... | Why do I get PROCEDURE does not exist when using callproc() in Django? | So I'm trying to use a stored procedure via a cursor and callproc() but I always get the error:
OperationalError: (1305, 'PROCEDURE myapp.LatLonDistance does not exist')
Here's the chunk of code that throws the error in my app:
cursor = connection.cursor()
result = cursor.callproc("myapp.LatLonDistance", (lat1, lon1, ... | [
"Since that is a function, and not actually a stored procedure, you should be able to call it using cursor.execute:\ncursor = connection.cursor()\nresult = cursor.execute(\"SELECT id,myapp.LatLonDistance(%s, %s, %s, %s) AS distance FROM myapp.users_userprofile\", (lat1, lon1, lat2, lon2))\ncursor.close()\n\n"
] | [
3
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004208807_django_mysql_python.txt |
Q:
tkinter python: How do remove the input cursor from a ttk.Entry?
I have an instance of ttk.Entry.
The user clicks it.
I have the event bound.
Depending on some condition, I either want the input cursor to appear and allow typing or I essentially want to ignore the click and not have the input cursor appear in the... | tkinter python: How do remove the input cursor from a ttk.Entry? | I have an instance of ttk.Entry.
The user clicks it.
I have the event bound.
Depending on some condition, I either want the input cursor to appear and allow typing or I essentially want to ignore the click and not have the input cursor appear in the ttk.Entry. I don't want to have to use the readonly or disabled state... | [
"Here is a class that does what you ask.\nclass MyEntry(Entry):\n\n def disable(self):\n self.__old_insertontime = self.cget('insertontime')\n self.config(insertontime=0)\n self.bind('<Key>', lambda e: 'break')\n\n def enable(self):\n self.unbind('<Key>')\n if self.cget('ins... | [
1,
0
] | [] | [] | [
"python",
"tkinter",
"ttk"
] | stackoverflow_0004205996_python_tkinter_ttk.txt |
Q:
sage math software: using cli interface, is && operator(i.e. "background and control"?) functionality supported?
I'm new to sage math software. i've been looking though sage documentation to find if the sage cli supports any way to run multiple commands one after another, i.e. behave like bash when using the && o... | sage math software: using cli interface, is && operator(i.e. "background and control"?) functionality supported? | I'm new to sage math software. i've been looking though sage documentation to find if the sage cli supports any way to run multiple commands one after another, i.e. behave like bash when using the && operator. for example, on linux:
$ cp file1 file2 && rm file1
at the command line will copy file1 to file2 and after... | [
"so, the \";\" symbol(semicolon) used in place of where i'm used to using && using bash seems to do the trick. if there are any differences i'm not aware of, i'd appreciate the info.\n"
] | [
1
] | [] | [] | [
"python",
"sage"
] | stackoverflow_0004209732_python_sage.txt |
Q:
Python - Are class methods multiprocess safe?
I have a class that loops over some data files, processes them, and then writes new data back out. The analysis of each file is completely independent of the others. The class contains information needed by the analysis in its attributes, but the analysis does not ne... | Python - Are class methods multiprocess safe? | I have a class that loops over some data files, processes them, and then writes new data back out. The analysis of each file is completely independent of the others. The class contains information needed by the analysis in its attributes, but the analysis does not need to change any attributes of the class. Thus I c... | [
"Yes, if you are not updating data on the class itself that needs to be shared across the instances, multiprocessing is the tool for you in this case.\n",
"You're not mentioning your process using any external resources, so it should be fork()-safe. Fork duplicates the memory and file descriptors, program state i... | [
1,
0
] | [] | [] | [
"class",
"iterator",
"multiprocessing",
"python"
] | stackoverflow_0004209962_class_iterator_multiprocessing_python.txt |
Q:
Python Interpreter blocks Multithreaded DNS requests?
I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:
from threading import Thread
import socket
class Connection(Thread):
def __init__(self, name, u... | Python Interpreter blocks Multithreaded DNS requests? | I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:
from threading import Thread
import socket
class Connection(Thread):
def __init__(self, name, url):
Thread.__init__(self)
self._url = url
... | [
"On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends).\nSo if you can't switch operating systems, you'll have to use a different (thread-... | [
15,
2,
2
] | [] | [] | [
"multithreading",
"network_programming",
"python"
] | stackoverflow_0001212716_multithreading_network_programming_python.txt |
Q:
A hashable, flexible identifier in python
I'm trying to make some sort of hashable identifier in python; I need it to identify nodes in a graph. The trouble is that some nodes have different attributes. If the attributes of these nodes are portrayed by dictionaries of the attributes to values:
idA = {'type':'A', '... | A hashable, flexible identifier in python | I'm trying to make some sort of hashable identifier in python; I need it to identify nodes in a graph. The trouble is that some nodes have different attributes. If the attributes of these nodes are portrayed by dictionaries of the attributes to values:
idA = {'type':'A', 'name':'a_100'}
idB = {'type':'B', 'name':'b_3',... | [
"There is no frozendict. But a collections.namedtuple is an approximation to that behaviour which may suit you.\n",
"Don't inherit from dict, encapsulate it. That way you can make sure it won't be changed.\nAs for caching, you can remember to_frozenset or its hash. Depending on the use pattern, remember the hash,... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"hash",
"immutability",
"python"
] | stackoverflow_0004209753_dictionary_hash_immutability_python.txt |
Q:
Python: how to create a hash of nested containers
[Python 3.1]
I am trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?
Why I need it:
I am caching the result of some calcula... | Python: how to create a hash of nested containers | [Python 3.1]
I am trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?
Why I need it:
I am caching the result of some calculations in a pickle object (on disk). I would need to inv... | [
"If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.\n",
"You could just serialize the parameters into something like JSON, and use that for the hash.\n",
"I would do it with json serialization as a string [and then hash that string if it's s... | [
2,
1,
0
] | [] | [] | [
"containers",
"hash",
"nested",
"python",
"python_3.x"
] | stackoverflow_0004202017_containers_hash_nested_python_python_3.x.txt |
Q:
Caching online prices fetched via API unless they change
I'm currently working on a site that makes several calls to big name online sellers like eBay and Amazon to fetch prices for certain items. The issue is, currently it takes a few seconds (as far as I can tell, this time is from making the calls) to load the ... | Caching online prices fetched via API unless they change | I'm currently working on a site that makes several calls to big name online sellers like eBay and Amazon to fetch prices for certain items. The issue is, currently it takes a few seconds (as far as I can tell, this time is from making the calls) to load the results, which I'd like to be more instant (~10 seconds is too... | [
"You can use memcache to do the caching. The first request will be slow, but the remaining requests should be instant. You'll want a cron job to keep it up to date though. More caching info here: Good examples of python-memcache (memcached) being used in Python?\n",
"Have you thought about displaying the cached d... | [
3,
2,
2,
0
] | [] | [] | [
"caching",
"html",
"mysql",
"python"
] | stackoverflow_0004208989_caching_html_mysql_python.txt |
Q:
Using networkx with my own object
I have my own objects, say pepperoni. I have a list of edges to an from every pepperoni and a list of pepperonis. I then build a graph using networkx. I'm trying to find the weight of the shortest path from one pepperoni to another. However, I'm getting an error as follows, which ... | Using networkx with my own object | I have my own objects, say pepperoni. I have a list of edges to an from every pepperoni and a list of pepperonis. I then build a graph using networkx. I'm trying to find the weight of the shortest path from one pepperoni to another. However, I'm getting an error as follows, which traces internal things from networkx as... | [
"If you have edges and nodes each as a list, then building a graph in networkx is straightforward. Given that your problem occurs in building your graph object, perhaps the best diagnostic is to go through graph construction in networkx step by step:\nimport networkx as NX\nimport string\nimport random\n\nG = NX.Gr... | [
3
] | [] | [] | [
"graph_theory",
"networkx",
"python"
] | stackoverflow_0004210616_graph_theory_networkx_python.txt |
Q:
Eliminate this unneeded copy in list.extend
Given two normal python lists, newlist and oldlist, with an integer index < len(oldlist), I'd like to perform the following operation:
newlist.extend(oldlist[index:])
but without creating the intermediate list oldlist[index:], or equivalently,
newlist.extend(oldlist[i]... | Eliminate this unneeded copy in list.extend | Given two normal python lists, newlist and oldlist, with an integer index < len(oldlist), I'd like to perform the following operation:
newlist.extend(oldlist[index:])
but without creating the intermediate list oldlist[index:], or equivalently,
newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))
without t... | [
"Don't guess, measure\ncreate = \"\"\"\noldlist = range(5000)\nnewlist = range(5000, 10000)\nindex = 500\n\"\"\"\ntests = [\n \"newlist.extend(oldlist[index:])\",\n \"newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))\",\n \"newlist.extend(islice(oldlist, index, None))\",\n \"\"\"\\\nwhile ... | [
10,
0,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004210481_optimization_python.txt |
Q:
A question from code in python's graph theory essays
The code is to determine a path between two nodes for directed graphs. This is the code:
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
re... | A question from code in python's graph theory essays | The code is to determine a path between two nodes for directed graphs. This is the code:
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if... | [
"Q1: This checks whether the call of find_path actually returns something. See the language docs to find out what gets interpreted as true and what as false if the type of the term is not boolean to start with. (In this case, None evaluates to false).\nQ2: No: this function gives exactly one path from start to end.... | [
3
] | [] | [] | [
"delimiter",
"graph_theory",
"if_statement",
"python"
] | stackoverflow_0004210963_delimiter_graph_theory_if_statement_python.txt |
Q:
Reusing django re-usable apps
I was wondering if this would be possible to implement (as an app/middleware):
I install the django-registration app. I then create my site-base app for making some generic page views. I want to put a login form and a registration form on a the front page. So I go in and I modify the ... | Reusing django re-usable apps | I was wondering if this would be possible to implement (as an app/middleware):
I install the django-registration app. I then create my site-base app for making some generic page views. I want to put a login form and a registration form on a the front page. So I go in and I modify the /register/login.html and the regist... | [
"There's certainly the {% include %} tag, which allows you to include templates directly inside of another template. It also gets everything that the enclosed template gets, so if you are using the RequestContext that means it has access to everything in the request variable.\nHowever, it seems you're saying that y... | [
0,
0
] | [] | [] | [
"django",
"model_view_controller",
"python",
"web_applications"
] | stackoverflow_0004201948_django_model_view_controller_python_web_applications.txt |
Q:
Python: variable-length tuples
[Python 3.1]
I'm following up on the design concept that tuples should be of known length (see this comment), and unknown length tuples should be replaced with lists in most circumstances. My question is under what circumstances should I deviate from that rule?
For example, I underst... | Python: variable-length tuples | [Python 3.1]
I'm following up on the design concept that tuples should be of known length (see this comment), and unknown length tuples should be replaced with lists in most circumstances. My question is under what circumstances should I deviate from that rule?
For example, I understand that tuples are faster to create... | [
"In my mind, the only interesting distinction between tuples and lists is that lists are mutable and tuples are not. The other distinctions that people mention seem completely artificial to me: tuples are like structs and lists are like arrays (this is where the \"tuples should be a known length\" comes from). Bu... | [
18,
3,
2,
1
] | [] | [] | [
"list",
"performance",
"python",
"python_3.x",
"tuples"
] | stackoverflow_0004210981_list_performance_python_python_3.x_tuples.txt |
Q:
2 django sites on 1 apache virtual host with django login
I have 2 sites, both require login ( I'm using the django provided django.contrib.auth.views.login). When I enter http:// url /siteb , I am redirected to accounts/login and siteb is taken out of the URL creating http:// url /accounts/login. But then I get... | 2 django sites on 1 apache virtual host with django login | I have 2 sites, both require login ( I'm using the django provided django.contrib.auth.views.login). When I enter http:// url /siteb , I am redirected to accounts/login and siteb is taken out of the URL creating http:// url /accounts/login. But then I get an error "The requested URL /accounts/login was not found on s... | [
"All of the urls should be prefixed with /sitea/ or /siteb/\nDjango generally assumes that it is installed at the root of the website.\n"
] | [
0
] | [] | [] | [
"apache2",
"django",
"mod_python",
"python"
] | stackoverflow_0004209773_apache2_django_mod_python_python.txt |
Q:
How to make this Twisted Python Proxy faster?
The code below is an HTTP proxy for content filtering. It uses GET to send the URL of the current site to the server, where it processes it and responds. It runs VERY, VERY, VERY slow. Any ideas on how to make it faster?
Here is the code:
from twisted.internet import r... | How to make this Twisted Python Proxy faster? | The code below is an HTTP proxy for content filtering. It uses GET to send the URL of the current site to the server, where it processes it and responds. It runs VERY, VERY, VERY slow. Any ideas on how to make it faster?
Here is the code:
from twisted.internet import reactor
from twisted.web import http
from twisted.we... | [
"The main cause of slowness in this proxy is probably these three lines:\n req = urllib.urlopen(\"http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s\" % params, proxies=proxies)\n resp = req.read()\n req.close()\n\nA normal Twisted-based application is single threaded. You have to go out of your ... | [
11
] | [] | [] | [
"http",
"proxy",
"python",
"twisted"
] | stackoverflow_0004211454_http_proxy_python_twisted.txt |
Q:
python list element wise conditional increment
I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...
my code is following, but is there a better way to do it? list comprehension, map??
I think a element-wise operator like ~+= fro... | python list element wise conditional increment | I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...
my code is following, but is there a better way to do it? list comprehension, map??
I think a element-wise operator like ~+= from http://www.python.org/dev/peps/pep-0225/ would be ... | [
"Here is a quick version:\n# sample data\ns = [10, 5, 20]\np = [2,2,2]\n\n# As a one-liner. (You could factor out the lambda)\ns = map(lambda (si, pi): si + pi if si < s[0] else si, zip(s,p))\n\n# s is now [10, 7, 20]\n\nThis assumes that len(s) <= len(p)\nHope this helps. Let me know. Good luck. :-)\n",
"Check ... | [
2,
1,
1,
0
] | [] | [] | [
"increment",
"list",
"python"
] | stackoverflow_0004210938_increment_list_python.txt |
Q:
Python separating Ajax requests from normal page views
I'm wondering what are some strategies that you've come up when dealing with this. I'm new to the python/django framework and would like to separate the serving of view from the handling of ajax requests (xhr).
I'm thinking of having a separate file xhrHandler... | Python separating Ajax requests from normal page views | I'm wondering what are some strategies that you've come up when dealing with this. I'm new to the python/django framework and would like to separate the serving of view from the handling of ajax requests (xhr).
I'm thinking of having a separate file xhrHandler.py and route specific POST/GET requests to /xhr/methodname ... | [
"Check request.is_ajax() and delegate wherever you need. Sample handler:\ndef view_something(request):\n if request.is_ajax():\n # ajax\n else\n # not\n\nYou can now call different functions (in different files) for the two cases.\nIf you want to be fancier, use a decorator for the handler that wi... | [
3
] | [] | [] | [
"ajax",
"design_patterns",
"django",
"python",
"xmlhttprequest"
] | stackoverflow_0004211883_ajax_design_patterns_django_python_xmlhttprequest.txt |
Q:
How to speed up this Python code?
I've got the following tiny Python method that is by far the performance hotspot (according to my profiler, >95% of execution time is spent here) in a much larger program:
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logPr... | How to speed up this Python code? | I've got the following tiny Python method that is by far the performance hotspot (according to my profiler, >95% of execution time is spent here) in a much larger program:
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
for i in xrange(len(seq) - l +... | [
"The reason it is slow is because it is O(N*N)\nThe maximum subsequence algorithm may help you improve this\n",
"if topScore is called repeatedly for same seq you could memoize its value. \nE.g. http://code.activestate.com/recipes/52201/\n",
"i don't have any idea what i'm doing but maybe this can help speed up... | [
2,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"java",
"jvm",
"jython",
"performance",
"python"
] | stackoverflow_0004209781_java_jvm_jython_performance_python.txt |
Q:
Performance_Python get union of 2 lists of tuple according to 2 out of the 3 elements of the tuple
My program is not doing a great job. In a loop, data from each processor (list of tuple) are gathered into the master processor that needs to clean it by removing similar element.
I found a lot of interesting clue on... | Performance_Python get union of 2 lists of tuple according to 2 out of the 3 elements of the tuple | My program is not doing a great job. In a loop, data from each processor (list of tuple) are gathered into the master processor that needs to clean it by removing similar element.
I found a lot of interesting clue on internet and especially in this site about union of list. However, i have not managed to apply it to my... | [
"Below is our uniques function. It takes arguments l (list) and f (function), returns list with duplicates removed (in the same order). Duplicates are defined by: b is duplicate of a iff f(b) == f(a). \ndef uniques(l, f = lambda x: x):\n return [x for i, x in enumerate(l) if f(x) not in [f(y) for y in l[:i]]]... | [
1,
1
] | [] | [] | [
"list",
"python",
"tuples",
"union"
] | stackoverflow_0004211175_list_python_tuples_union.txt |
Q:
Python pickling error when using sessions
In my django app I was creating an extended user profile using session vars. But when registration form was saved and user was about to create, I got following error :
Traceback (most recent call last):
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py",... | Python pickling error when using sessions | In my django app I was creating an extended user profile using session vars. But when registration form was saved and user was about to create, I got following error :
Traceback (most recent call last):
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run
self.result = application... | [
"It appears you have a cStringIO object in your session (perhaps an uploaded file?), these cannot be pickled. Either write custom pickling code or make sure all your session data can be serialized.\n",
"Something weird going on here, because the error refers to cStringIO.StringO whereas the class is actually cStr... | [
4,
1,
1
] | [] | [] | [
"django",
"pickle",
"python",
"session_variables"
] | stackoverflow_0003642107_django_pickle_python_session_variables.txt |
Q:
ImportError: cannot import name tz (psycopg2)
I am using Windows XP, and using Python run time from http://www.python.org/ftp/python/2.7/python-2.7.msi
If I am running in standalone application, import psycopg2 doesn't cause me any trouble. However, when come to mod_wsgi + apache, I will get the following error
[T... | ImportError: cannot import name tz (psycopg2) | I am using Windows XP, and using Python run time from http://www.python.org/ftp/python/2.7/python-2.7.msi
If I am running in standalone application, import psycopg2 doesn't cause me any trouble. However, when come to mod_wsgi + apache, I will get the following error
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1]... | [
"My guess would be that Python doesn't know your egg cache location (or doesn't have privileges to it). You just need to set that. More information here. Try setting the WSGIPythonEggs directive.\n"
] | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0004212240_apache_mod_wsgi_postgresql_psycopg2_python.txt |
Q:
How to submit form on webpage in PYTHON?
I want to tick checkboxes, select radio buttons, write in text boxes and finally click on submit button to submit the form on a page. Programming in PYTHON only. How do i achieve this?
A:
There are quite some solution. You can explore them and come back with a program, if... | How to submit form on webpage in PYTHON? | I want to tick checkboxes, select radio buttons, write in text boxes and finally click on submit button to submit the form on a page. Programming in PYTHON only. How do i achieve this?
| [
"There are quite some solution. You can explore them and come back with a program, if it does not work.\n\nMechanize: http://wwwsearch.sourceforge.net/mechanize/\n\nPython Auto Fill with Mechanize\n\nTwill : - http://twill.idyll.org/\nPython Paste: http://pythonpaste.org/\nPAMIE: http://pamie.sourceforge.net/\n\n"
... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004212759_python.txt |
Q:
ValueError in Django when trying to edit and .save() IP addresses
Error received:
Exception Type: ValueError at /institutes_admin/
Exception Value: invalid literal for int() with base 10: ''
Full traceback at: http://www.pastie.org/1307821
A:
I would say that you updated an instance variable on your model whic... | ValueError in Django when trying to edit and .save() IP addresses | Error received:
Exception Type: ValueError at /institutes_admin/
Exception Value: invalid literal for int() with base 10: ''
Full traceback at: http://www.pastie.org/1307821
| [
"I would say that you updated an instance variable on your model which should be an integer but cannot be type cast to an integer correctly.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004212786_django_python.txt |
Q:
In which "real-use" cases item.__dict__.iteritems() is used?
Yesterday i was reading some questions here on SO and i came to know item.__dict__.iteritems().
I must admit that i do not know how, when or why use that, and i also admit it looks beautiful, pythonic.
So, what are some "real-world" uses of that?
A:
H... | In which "real-use" cases item.__dict__.iteritems() is used? | Yesterday i was reading some questions here on SO and i came to know item.__dict__.iteritems().
I must admit that i do not know how, when or why use that, and i also admit it looks beautiful, pythonic.
So, what are some "real-world" uses of that?
| [
"Honestly, it has almost no real life use cases aside from introspection. In most cases, inspect.getmembers will be better (though it's not a generator: if your classes have enough attributes for that to really be a problem than it's the least of them)\nThe difference is that inspect.gemembers will get both class a... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004213188_python.txt |
Q:
Detect if python script is run from console or by crontab
Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. -... | Detect if python script is run from console or by crontab | Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do t... | [
"Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:\nimport sys, os\nif os.isatty(sys.stdin.fileno()):\n # Debug mode.\n pass\nelse:\n # Cron mode.\n pass\n\n",
"You could add an environment variable to the crontab line and check, inside your python application, if the ... | [
37,
9,
4
] | [] | [] | [
"bash",
"crontab",
"environment_variables",
"python"
] | stackoverflow_0004213091_bash_crontab_environment_variables_python.txt |
Q:
Installing MySQLdb windows for Python 2.5
I have seen this issue come up a lot on these discussion boards but I am still having trouble finding an answer. I am trying to install MySQLdb for Python 2.5 on my Windows Vista machine. I grabbed the installation file from this link
http://sourceforge.net/projects/mysq... | Installing MySQLdb windows for Python 2.5 | I have seen this issue come up a lot on these discussion boards but I am still having trouble finding an answer. I am trying to install MySQLdb for Python 2.5 on my Windows Vista machine. I grabbed the installation file from this link
http://sourceforge.net/projects/mysql-python/reviews/
I then opened my Windows comm... | [
"You can install first the setuptools for python 2.5, you can find it here http://pypi.python.org/pypi/setuptools\nsearch for where it says:setuptools-0.6c11.win32-py2.3.exe (md5)\nAfter you install this, then try again installing mysqldb\n"
] | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004211062_mysql_python.txt |
Q:
termination of a twistd application in python
I am trying to write an application with twistd library written for Python. The application file ends like the following:
factory = protocol.ServerFactory()
factory.protocol = EchoServer
application = service.Application("Echo")
internet.TCPServer(8001, factory).setSer... | termination of a twistd application in python | I am trying to write an application with twistd library written for Python. The application file ends like the following:
factory = protocol.ServerFactory()
factory.protocol = EchoServer
application = service.Application("Echo")
internet.TCPServer(8001, factory).setServiceParent(application)
I want to run something bef... | [
"You need to add code to the startService and stopService methods of the Service.\nOne way would be something like this:\nfrom twisted.application import service\nfrom twisted.internet import protocol\n\nclass MyService(service.Service):\n def __init__(self,port=8001):\n self.port = port\n def startService(sel... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004211932_python.txt |
Q:
Python function parameter: tuple/list
My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the f... | Python function parameter: tuple/list | My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the function slightly, to process an additional ... | [
"If another_func just wants a iterable you can pass itertools.chain(x,'a') to it.\n",
"What about changing the other function to accept a list of params instead ?\ndef func(arg): # arg is tuple or list\n another_func('a', *x)\n\n",
"how about:\nl = ['a']\nl.extend(x)\n\nEdit:\nRe-reading question, I think this... | [
7,
4,
3,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"coding_style",
"list",
"python",
"tuples"
] | stackoverflow_0004208619_coding_style_list_python_tuples.txt |
Q:
what is wrong with my system, unable to unpack dict. having unicode objects?
In [1]: l1 = lambda *args, **kw: args
In [2]: l1(**{'name':'hello'})
Out[2]: ()
In [3]: l1(**{u'name':'hello'})
---------------------------------------------------------------------------
TypeError Traceb... | what is wrong with my system, unable to unpack dict. having unicode objects? | In [1]: l1 = lambda *args, **kw: args
In [2]: l1(**{'name':'hello'})
Out[2]: ()
In [3]: l1(**{u'name':'hello'})
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/sma/<ipython console> in <module>()
I've some ... | [
"Seems to be related with this (non-)bug (old), but there are even more bug reports and it really seems to be fixed from 2.6.5 on only.\nThat is all I found and I don't have more insight into Python to explain how or why ;)\n"
] | [
2
] | [] | [] | [
"argument_unpacking",
"dictionary",
"python",
"ubuntu"
] | stackoverflow_0004213245_argument_unpacking_dictionary_python_ubuntu.txt |
Q:
lxml build on Solaris 10
Please can you help and advise with a problem with python 2.6.6 and lxml Solaris 10 build?
Installation instructions:
www.sunfreeware.com/download.html
direct link to the file:
http://www.sunfreeware.com/ftp/pub/freeware/sparc/10/lxml-2.2.8-sol10-sparc-local.gz
[rainier]/usr/apps/openet/bm... | lxml build on Solaris 10 | Please can you help and advise with a problem with python 2.6.6 and lxml Solaris 10 build?
Installation instructions:
www.sunfreeware.com/download.html
direct link to the file:
http://www.sunfreeware.com/ftp/pub/freeware/sparc/10/lxml-2.2.8-sol10-sparc-local.gz
[rainier]/usr/apps/openet/bmsystest/relAuto/RAP_SW> python... | [
"I've seen this before. Think it was due to a mismatch between two versions of python. \nI think it was that python was calling /usr/local/bin/python, but lxml had compiled against a different version of python (found in /bin/python or something like that)\n"
] | [
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004211680_lxml_python.txt |
Q:
what do %(xyz)s representation mean in python
What are these representation in python and how to use. My guess is it is used for data validation but never able to use it.
%(name)s
%(levelno)s
%(levelname)s
%(pathname)s
%(process)d
etc..
A:
This is string formatting using keys:
>>> d = {"answer": 42}
>>> "the an... | what do %(xyz)s representation mean in python | What are these representation in python and how to use. My guess is it is used for data validation but never able to use it.
%(name)s
%(levelno)s
%(levelname)s
%(pathname)s
%(process)d
etc..
| [
"This is string formatting using keys:\n>>> d = {\"answer\": 42}\n>>> \"the answer is %(answer)d\" % d\n'the answer is 42'\n\n",
"It's formatting a string, by picking values from a dictionary:\ntest = { \"foo\": 48, \"bar\": 4711, \"hello\": \"yes\" }\nprint \"%(foo)d %(bar)d and %(hello)s\" % test\n\nprints:\n4... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0004213559_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.