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:
IOError: [Errno 13] Permission denied:
I have built this code to specifically identify a load of .XML files and to extract co-ordinates from those files. Here is my code:
from xml.etree import ElementTree as ET
import sys, string, os, arcgisscripting
gp = arcgisscripting.create(9.3)
workspace = "D:/J040083"
gp.wo... | IOError: [Errno 13] Permission denied: | I have built this code to specifically identify a load of .XML files and to extract co-ordinates from those files. Here is my code:
from xml.etree import ElementTree as ET
import sys, string, os, arcgisscripting
gp = arcgisscripting.create(9.3)
workspace = "D:/J040083"
gp.workspace = workspace
for root, dirs, filenam... | [
"You need to change the line\ntree = ET.parse(workspace)\n\nto \ntree = ET.parse(filename)\n\nbecause workspace is a directory and the parse method takes a filename.\n",
"Maybe you just need to write the file path with \\ instead of /:\nworkspace = \"D:\\\\J040083\"\n\nOr, without backslash escaping as a raw stri... | [
11,
0
] | [] | [] | [
"file_permissions",
"python"
] | stackoverflow_0004736616_file_permissions_python.txt |
Q:
Changing a graph by creating a new one
Im making a graph that represents all the moves in a maze. Thing is when copying i repeated movements, so the output of my dictionary is as follow:
{(1, 2): [(2, 2)],
(3, 2): [(4, 2), (3, 3), (2, 2)],
(3, 3): [(3, 2), (3, 4)],
(5, 2): [(5, 3), (4, 2)],
(4, 4): [(5, 4), (3,... | Changing a graph by creating a new one | Im making a graph that represents all the moves in a maze. Thing is when copying i repeated movements, so the output of my dictionary is as follow:
{(1, 2): [(2, 2)],
(3, 2): [(4, 2), (3, 3), (2, 2)],
(3, 3): [(3, 2), (3, 4)],
(5, 2): [(5, 3), (4, 2)],
(4, 4): [(5, 4), (3, 4)],
(5, 4): [(5, 3), (4, 4)],
(2, 2): [(... | [
"A way to do it would be:\n# Here's your node collection\ntoclean = {(1, 2): [(2, 2)],\n(3, 2): [(4, 2), (3, 3), (2, 2)],\n(3, 3): [(3, 2), (3, 4)],\n(5, 2): [(5, 3), (4, 2)],\n(4, 4): [(5, 4), (3, 4)],\n(5, 4): [(5, 3), (4, 4)],\n(2, 2): [(3, 2), (1, 2)],\n(4, 2): [(5, 2), (3, 2)],\n(3, 4): [(4, 4), (3, 3)],\n(5, ... | [
0
] | [] | [] | [
"dictionary",
"graph",
"logic",
"python"
] | stackoverflow_0004736475_dictionary_graph_logic_python.txt |
Q:
Python Object Oriented Programming
Am trying to understand object oriented programming with python. Am new to programming.
I have this class that is giving me an error I don't understand and I will be glad if anyone can throw more light on this for me:
class TimeIt(object):
def __init__(self, name):
s... | Python Object Oriented Programming | Am trying to understand object oriented programming with python. Am new to programming.
I have this class that is giving me an error I don't understand and I will be glad if anyone can throw more light on this for me:
class TimeIt(object):
def __init__(self, name):
self.name = name
def test_one(self):... | [
"You're overwriting i within loop. When you're \"preceding\" i with self, you're creating different variable, which is not overwritten.\n",
"@SilentGhost is right on the money with his answer. \nTo illustrate, try chaning the test_two method to this:\ndef test_two(self, word):\n self.word = word\n i = getat... | [
9,
2
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0004737088_python_variables.txt |
Q:
Django URL pattern with different roots
I have two URL patterns that both exist in the same application that I'm working on getting set up.
I need urls like the following to work.
http://www.domain.com/p/12345
http://www.domain.com/s/12345
However, both of these live in the same django application.
My main urls.... | Django URL pattern with different roots | I have two URL patterns that both exist in the same application that I'm working on getting set up.
I need urls like the following to work.
http://www.domain.com/p/12345
http://www.domain.com/s/12345
However, both of these live in the same django application.
My main urls.py looks something like this for handling the... | [
"You can include a URLs file with an empty pattern. You could do this:\nmain urls.py\nurlpatterns = patterns('',\n (r'foo/', 'foo_view'),\n (r'^', include('myproject.myapp.urls')),\n)\n\napp urls.py\nurlpatterns = patterns('puzzlequest.pq.views',\n (r'^p/(?P<object_id>\\d+)/$', 'some_view'),\n (r'^s/(?P... | [
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0004737050_django_django_urls_python.txt |
Q:
generate xml with sax2 in python
I have a data model or an object from a class, and I need to initialize it by reading from an xml file, or create this object from scratch and output it to an xml file. Previously, I simply use string operations from python to read xml (file.read + string.find) and write xml (file.... | generate xml with sax2 in python | I have a data model or an object from a class, and I need to initialize it by reading from an xml file, or create this object from scratch and output it to an xml file. Previously, I simply use string operations from python to read xml (file.read + string.find) and write xml (file.write), without error checking.
Now I... | [
"Try the pythonic XML processing way: ElementTree.\nGenerating XML output is easy with`xml.etree.ElementTree.ElementTree.write().\n\nwrite(file, encoding=\"us-ascii\", xml_declaration=None, method=\"xml\")\nWrites the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding... | [
2
] | [] | [] | [
"file_io",
"python",
"sax",
"xml"
] | stackoverflow_0004737244_file_io_python_sax_xml.txt |
Q:
Getting Java to talk to Python, C, C++, and Ruby
I have succeeded in getting ProcessBuilder to run external scripts, but I still have to get Java to communicate with the external scripts. I figure that I should get the input/output streams from the process, and use those to send and receive data. I'm having a the ... | Getting Java to talk to Python, C, C++, and Ruby | I have succeeded in getting ProcessBuilder to run external scripts, but I still have to get Java to communicate with the external scripts. I figure that I should get the input/output streams from the process, and use those to send and receive data. I'm having a the most trouble with giving input to the scripts. It seem... | [
"The method getOutputStream() on the Process class returns a stream you can write to in Java that connects to the stdin stream of the process. You should be able to read this as you would normally read stdin for each language (e.g., cin for C++, scanf for C, STDIN.read for Ruby, don't know Python!)\nIf this is what... | [
2,
1,
0
] | [] | [] | [
"c",
"c++",
"java",
"python",
"ruby"
] | stackoverflow_0004736698_c_c++_java_python_ruby.txt |
Q:
Creating a dictionary from two iterables and consuming both of them
Suppose I have two lists and I want to make a dictionary from them. Like:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
This works as I'd want it to and since the lists are not of equal length, the e... | Creating a dictionary from two iterables and consuming both of them | Suppose I have two lists and I want to make a dictionary from them. Like:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
This works as I'd want it to and since the lists are not of equal length, the elements 4 and 5 are left out and there is no corresponding value for them... | [
"Use\ndict(itertools.izip_longest(l, x))\n# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}\n\n"
] | [
12
] | [] | [] | [
"dictionary",
"iterable",
"python"
] | stackoverflow_0004737901_dictionary_iterable_python.txt |
Q:
Split from a specific delimiter
How to rip a URL like http://www.facebook.com/pages/create.php to have a result like this: www.facebook.com?
I tried this way, but doesn't work:
line.split('/', 2)[2]
My problem is probably with that two forward slashes // and some of the URLs start from the www strings.
Thanks fo... | Split from a specific delimiter | How to rip a URL like http://www.facebook.com/pages/create.php to have a result like this: www.facebook.com?
I tried this way, but doesn't work:
line.split('/', 2)[2]
My problem is probably with that two forward slashes // and some of the URLs start from the www strings.
Thanks for your help, Adia
| [
"You might want to look at Python's urlparse module.\n>>> from urlparse import urlparse\n>>> o = urlparse('http://www.facebook.com/pages/create.php')\n>>> o.netloc\n'www.facebook.com'\n\n",
"Probably the best bet would be returning the server part from a regex, ie,\n\\/[a-z0-9\\-\\.]*[a-zA-Z0-9\\-]+\\.[a-z]{2,3}\... | [
8,
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"url"
] | stackoverflow_0004736195_parsing_python_url.txt |
Q:
Two calendars synchronization
Question is rather conceptual, then direct.
What's the best solution to keep two different calendars synchronised? I can run a cron job for example every minute, I can keep additional information in database. How to avoid events conflicts?
As far I was thinking about these two solutio... | Two calendars synchronization | Question is rather conceptual, then direct.
What's the best solution to keep two different calendars synchronised? I can run a cron job for example every minute, I can keep additional information in database. How to avoid events conflicts?
As far I was thinking about these two solutions. First one is keeping a database... | [
"Most calendars, including the Google calendar, has ways to import and synchronize data. You can use these ways. Just import the gdata information (perhaps you need to make it into ics first, I don't know) into the Google calendar.\n"
] | [
0
] | [] | [] | [
"calendar",
"python",
"synchronization"
] | stackoverflow_0004737852_calendar_python_synchronization.txt |
Q:
How do I make my wxpython top frame show in the middle of my desktop?
I want to make my GUI program top frame both vertically and horizontally aligned.
wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BO... | How do I make my wxpython top frame show in the middle of my desktop? | I want to make my GUI program top frame both vertically and horizontally aligned.
wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
What should I do(except do the calculation to find the absolute positio... | [
"Simply use\nself.Center()\n\nin the class __init__() instead of pos=(-1,-1).\n",
"w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)\nh = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)\n\npos=(w/2, h/2)\n\nThis gives you the centre of the screen.\nNow, assuming you have an 800x600 sized application:\nAPPWIDTH = 800\... | [
20,
6
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004734390_python_user_interface_wxpython.txt |
Q:
python libxml2 reader and XML_PARSE_RECOVER
I'm trying to get a reader to recover from broken XML. Using the libxml2.XML_PARSE_RECOVER option with the DOM api (libxml2.readDoc) works and it recovers from entity problems.
However using the option with the reader API (which is essential due to the size of documents ... | python libxml2 reader and XML_PARSE_RECOVER | I'm trying to get a reader to recover from broken XML. Using the libxml2.XML_PARSE_RECOVER option with the DOM api (libxml2.readDoc) works and it recovers from entity problems.
However using the option with the reader API (which is essential due to the size of documents we are parsing) does not work. It just gets stuck... | [
"I'm not too sure about the current state of the libxml2 bindings. Even the libxml2 site suggests using lxml instead. To parse this tree and ignore the & is nice and clean in lxml:\nfrom cStringIO import StringIO\nfrom lxml import etree\n\nDOC = \"<a>some broken & xml</a>\"\n\nreader = etree.XMLParser(recover=True)... | [
1,
0,
0,
0
] | [] | [] | [
"libxml2",
"python"
] | stackoverflow_0003871651_libxml2_python.txt |
Q:
Framework Choice / Recommendations for Google App Engine
i want to develop a big web application in Google App engine, but I don't know which framework to use in order to obtain the MVC Model. I prefer to use Spring MVC, but I read that several problems with GAE. Another option would be to use django with python b... | Framework Choice / Recommendations for Google App Engine | i want to develop a big web application in Google App engine, but I don't know which framework to use in order to obtain the MVC Model. I prefer to use Spring MVC, but I read that several problems with GAE. Another option would be to use django with python but I have never used that. What framework or option do you rec... | [
"You should check out web2py -- it's a full-stack Python MVC framework that's very easy to set up, learn, and use. It was designed to run on Google App Engine out of the box, and there's a whole section in the online book dedicated to GAE (there are also other references throughout the book discussing a few special... | [
4,
1,
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"java",
"python",
"spring"
] | stackoverflow_0004692280_django_google_app_engine_java_python_spring.txt |
Q:
Python __getattr__ behavior? IN ECLIPSE/PyDev console?
The following:
class A(object):
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except KeyError:
self.__dict__[attr] = 'Attribute set to string'
print 'Assigned attribute'
return ... | Python __getattr__ behavior? IN ECLIPSE/PyDev console? | The following:
class A(object):
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except KeyError:
self.__dict__[attr] = 'Attribute set to string'
print 'Assigned attribute'
return self.__dict__[attr]
returns:
obj = A()
obj.foo
Assigned att... | [
"I have a slightly different version of your code that might help.\nclass A(object):\n def __getattr__(self, attr):\n try:\n return self.__dict__[attr]\n except KeyError:\n self.__dict__[attr] = 'Attribute set to string'\n print 'Assigned attribute', attr\n ... | [
3,
1
] | [] | [] | [
"getattr",
"pydev",
"python"
] | stackoverflow_0004738221_getattr_pydev_python.txt |
Q:
public private key solution for javascript and python
I'm looking for a public private key solution that I can use with a javascript client and python backend. The aim is to send data encrypted from the client to the server... Are the any solutions? Thanks for hints.
A:
Use SSL for your connections to the server... | public private key solution for javascript and python | I'm looking for a public private key solution that I can use with a javascript client and python backend. The aim is to send data encrypted from the client to the server... Are the any solutions? Thanks for hints.
| [
"Use SSL for your connections to the server. Probably the easiest way to do that is to use HTTP for communication and also to run a proxy (say, Apache) on the server that can do HTTPS and forwards requests to the actual server application.\n"
] | [
0
] | [] | [] | [
"encryption",
"javascript",
"pgp",
"python"
] | stackoverflow_0004737721_encryption_javascript_pgp_python.txt |
Q:
Explain the float - int problem in factorization
I am missing here the technical word but the problem here is either to change int to float or float to int.
def factorize(n):
def isPrime(n):
return not [x for x in range(2,int(math.sqrt(n)))
if n%x == 0]
primes = []
candidate... | Explain the float - int problem in factorization | I am missing here the technical word but the problem here is either to change int to float or float to int.
def factorize(n):
def isPrime(n):
return not [x for x in range(2,int(math.sqrt(n)))
if n%x == 0]
primes = []
candidates = range(2,n+1)
candidate = 2
while not prime... | [
"This expression is your immediate problem:\nfloat(factorize(n/candidate))\n\nfactorize returns a list, but float needs its argument to be a string or a number.\n(Your code has many, many other problems but perhaps it would be best for you to discover them for yourself...)\n",
"Notice that you return a list and i... | [
2,
0,
0
] | [] | [] | [
"factorization",
"floating_point",
"int",
"python"
] | stackoverflow_0004738044_factorization_floating_point_int_python.txt |
Q:
Python: Clever ways at string manipulation
I'm new to Python and am currently reading a chapter on String manipulation in "Dive into Python."
I was wondering what are some of the best (or most clever/creative) ways to do the following:
1) Extract from this string: "stackoverflow.com/questions/ask" the word 'ques... | Python: Clever ways at string manipulation | I'm new to Python and am currently reading a chapter on String manipulation in "Dive into Python."
I was wondering what are some of the best (or most clever/creative) ways to do the following:
1) Extract from this string: "stackoverflow.com/questions/ask" the word 'questions.' I did string.split(/)[0]-- but that isn... | [
"As personal exercise, here's to you, (hopefully) well commented code with some hints.\n#!/usr/bin/env python2\n\n# Let's take this string:\na = \"palindnilddafa\"\n# I surround with a try/catch block, explanation following\ntry:\n # In this loop I go from length of a minus 1 to 0.\n # range can take 3 params: st... | [
2,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004737814_python_string.txt |
Q:
Jython script implementing a class isn't initialized correctly from Java
I'm trying to do something similar to Question 4617364 but for Python - load a class from python script file, where said class implements a Java interface and hand it over to some Java code that can use its methods - but calls to the object m... | Jython script implementing a class isn't initialized correctly from Java | I'm trying to do something similar to Question 4617364 but for Python - load a class from python script file, where said class implements a Java interface and hand it over to some Java code that can use its methods - but calls to the object method return invalid values and printing from the initializer doesn't seem to ... | [
"What version of jython are you using? You might have run into the JSR223 Jython bug : http://bugs.jython.org/issue1681\nFrom the bug description:\n\nCalling methods from an embedded Jython script does nothing when\n using JSR-223 and Jython 2.5.2rc2, while Jython 2.2.1 just works fine.\n\n"
] | [
2
] | [] | [] | [
"class",
"java",
"jsr233",
"jython",
"python"
] | stackoverflow_0004618710_class_java_jsr233_jython_python.txt |
Q:
What (pure) Python library to use for AES 256 encryption?
I am looking for a (preferably pure) python library to do AES 256 encryption and decryption.
This library should support the CBC cipher mode and use PKCS7 padding according to the answer to an earlier question of mine.
The library should at least work on Ma... | What (pure) Python library to use for AES 256 encryption? | I am looking for a (preferably pure) python library to do AES 256 encryption and decryption.
This library should support the CBC cipher mode and use PKCS7 padding according to the answer to an earlier question of mine.
The library should at least work on Mac OS X (10.4) and Windows XP. Ideally just by dropping it into ... | [
"PyCrypto should be the one for you.\nEdit 02/10/2020: unfortunately I cannot delete this post, since it's the accepted answer. As people pointed out in the comments, this library is not mantained anymore and probably also vulnerable from a security point of view. So please, take a look to the below answers instead... | [
13,
13,
5,
4,
1
] | [] | [] | [
"aes",
"encryption",
"python"
] | stackoverflow_0000172486_aes_encryption_python.txt |
Q:
how to correctly compare unicode string from psycopg2 in Python?
I have a problem with comparing a UTF-8 string obtained from PostgreSQL database:
>>> db_conn = psycopg2.connect("dbname='foo' user='foo' host='localhost' password='xxx'")
>>> db_cursor = db_conn.cursor()
>>> sql_com = ("""SELECT my_text FROM table W... | how to correctly compare unicode string from psycopg2 in Python? | I have a problem with comparing a UTF-8 string obtained from PostgreSQL database:
>>> db_conn = psycopg2.connect("dbname='foo' user='foo' host='localhost' password='xxx'")
>>> db_cursor = db_conn.cursor()
>>> sql_com = ("""SELECT my_text FROM table WHERE id = 1""")
>>> db_cursor.execute(sql_com)
>>> sql_result = db_cur... | [
"This is clearly a problem with locale of your console.\nu\"München\" is u'M\\xfcnchen' in Unicode and 'M\\xc3\\xbcnchen' in UTF-8. That latter is your München if taken as ISO8859-1 or CP1252.\nPsycopg2 seems to supply you with correct Unicode values, as it should. \n",
"If you type\nb = 'München'\n\nWhat do you... | [
3,
1
] | [] | [] | [
"psycopg2",
"python",
"string",
"unicode",
"utf_8"
] | stackoverflow_0004738642_psycopg2_python_string_unicode_utf_8.txt |
Q:
Inversion of Control: Have you ever had to decide what Dependency Injection framework is best for a project? Which one did you pick and why?
Rather than triggering a flamewar on what DI framework is "best" (I don't think there's a definitive general solution), this question is meant to discuss good alternatives fo... | Inversion of Control: Have you ever had to decide what Dependency Injection framework is best for a project? Which one did you pick and why? | Rather than triggering a flamewar on what DI framework is "best" (I don't think there's a definitive general solution), this question is meant to discuss good alternatives for projects of different kinds, no matter the programming language, based on professional experience.
Some issues I'd like to lean about:
What wer... | [
"I usually choose frameworks, whether DI or otherwise, using the following criteria:\n\nPick a framework that has the required functionality for the job at hand\nPrefer frameworks that are simple - The less \"extra\" stuff not required for 1., the better.\nPrefer frameworks \"built-in\" to the language/framework yo... | [
2,
2
] | [] | [] | [
"dependency_injection",
"frameworks",
"php",
"python"
] | stackoverflow_0004738980_dependency_injection_frameworks_php_python.txt |
Q:
How can I selectively suppress certain error messages that follow a certain pattern?
I have a Python program running a thread that consistently outputs the following:
(my_program.py:12313): GLib-GIO-CRITICAL **: g_output_stream_write: assertion `buffer != NULL' failed
This prints continuously, with no obvious det... | How can I selectively suppress certain error messages that follow a certain pattern? | I have a Python program running a thread that consistently outputs the following:
(my_program.py:12313): GLib-GIO-CRITICAL **: g_output_stream_write: assertion `buffer != NULL' failed
This prints continuously, with no obvious detrimental effect on my program. For debugging purposes, I would like to suppress this parti... | [
"This works:\n python my_program.py 2>&1| grep -v \"GLib-GIO-CRITICAL\"\n\n",
"That looks like a warning from GTK, are you using it? I don't think you can suppress them from Python.\n"
] | [
2,
0
] | [] | [] | [
"console",
"messages",
"python"
] | stackoverflow_0004739436_console_messages_python.txt |
Q:
Setting up Kerberos in python in Ubuntu machine
I need to setup a kerberos server on my Ubuntu machine for the authentication of users. I tried using pykpass for the same, but was facing some problems in installing the python module. Is there some other way to do the same?
A:
sudo apt-get install python-kerberos... | Setting up Kerberos in python in Ubuntu machine | I need to setup a kerberos server on my Ubuntu machine for the authentication of users. I tried using pykpass for the same, but was facing some problems in installing the python module. Is there some other way to do the same?
| [
"sudo apt-get install python-kerberos\n\n"
] | [
3
] | [] | [] | [
"authentication",
"kerberos",
"python"
] | stackoverflow_0004739487_authentication_kerberos_python.txt |
Q:
Error while install installing pykpass
I am encountering following error on installing pykpass module from http://www.huque.com/software/pykpass/ . Following is the error :
wrap_kpass.c:1:20: error: Python.h: No such file or directory
wrap_kpass.c:7: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘... | Error while install installing pykpass | I am encountering following error on installing pykpass module from http://www.huque.com/software/pykpass/ . Following is the error :
wrap_kpass.c:1:20: error: Python.h: No such file or directory
wrap_kpass.c:7: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
wrap_kpass.c:9: error: expected ‘=’... | [
"\nPython.h: No such file or directory\n\nProbably you forgot to install package python-dev or any other form of Python development headers.\n"
] | [
1
] | [] | [] | [
"installation",
"kerberos",
"python"
] | stackoverflow_0004739410_installation_kerberos_python.txt |
Q:
Should I learn/use MapReduce, or some other type of parallelization for this task?
After talking with a friend of mine from Google, I'd like to implement some kind of Job/Worker model for updating my dataset.
This dataset mirrors a 3rd party service's data, so, to do the update, I need to make several remote call... | Should I learn/use MapReduce, or some other type of parallelization for this task? | After talking with a friend of mine from Google, I'd like to implement some kind of Job/Worker model for updating my dataset.
This dataset mirrors a 3rd party service's data, so, to do the update, I need to make several remote calls to their API. I think a lot of time will be spent waiting for responses from this 3rd ... | [
"The work you describe is probably a good fit for either a queue, or a combination of a queue and job server. It certainly could work as a set of MapReduce steps as well.\nFor a job server, I recommend looking at Gearman. The documentation isn't awesome, but the presentations do a great job documenting it, and th... | [
5,
1,
0
] | [] | [] | [
"amazon_web_services",
"mapreduce",
"parallel_processing",
"python"
] | stackoverflow_0004236279_amazon_web_services_mapreduce_parallel_processing_python.txt |
Q:
Spawn of a multiprocess.Process is not filling Queue correctly in Python
I am currently writing a connection manager for a stress test in Python it seems my queue is never filling up. This pseudoesque-code will explain it better than I can:
def wget(processQueue)
currProcess = subprocess.Popen(./wget)
pro... | Spawn of a multiprocess.Process is not filling Queue correctly in Python | I am currently writing a connection manager for a stress test in Python it seems my queue is never filling up. This pseudoesque-code will explain it better than I can:
def wget(processQueue)
currProcess = subprocess.Popen(./wget)
processQueue.put(currProcess)
def connection(processQueue)
process = multipr... | [
"Regarding processQueue.qsize, note that the docs say :\nDefinition: processQueue.qsize(self)\nDocstring:\n Return the approximate size of the queue (not reliable!).\n\nso you shouldn't rely on qsize to tell you if the queue is empty.\nAlso, since you may be reaching the line processQueue.qsize before the proces... | [
3
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0004739494_multiprocessing_python.txt |
Q:
How to set the icon-size in a QTreeWidget?
How does one set the icon size for items within a Qtreewidget? So far I have tried
QTreeWidget.setIconSize(QSize(32,32))
But all that does is increase the width, not the height.
However, a
print QTreeWidget.iconSize()
shows the correct result :
PyQt4.QtCore.QSize(32, 32)... | How to set the icon-size in a QTreeWidget? | How does one set the icon size for items within a Qtreewidget? So far I have tried
QTreeWidget.setIconSize(QSize(32,32))
But all that does is increase the width, not the height.
However, a
print QTreeWidget.iconSize()
shows the correct result :
PyQt4.QtCore.QSize(32, 32)
Does anyone have a better understanding of how ... | [
"Jason had some of the solution. The height of the treeview's rows needs to be resized as well:\nclass MyDelegate(QItemDelegate): \n def __init__(self): \n QItemDelegate.__init__(self) \n\n def sizeHint(self, option, index): \n return QSize(32,32)\n\nThen, elsewhere:\ndelegate = MyDele... | [
6,
1
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0004729791_pyqt_python_qt.txt |
Q:
Any easy way to plot a 3d scatter in Python that I can rotate around?
Currently I'm using matplotlib to plot a 3d scatter and while it gets the job done, I can't seem to find a way to rotate it to see my data better.
Here's an example:
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
#data is an ndarray... | Any easy way to plot a 3d scatter in Python that I can rotate around? | Currently I'm using matplotlib to plot a 3d scatter and while it gets the job done, I can't seem to find a way to rotate it to see my data better.
Here's an example:
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
#data is an ndarray with the necessary data and colors is an ndarray with
#'b', 'g' and 'r' to... | [
"Well, first you need to define what you mean by \"see my data better\"... \nYou can rotate and zoom in on the plot using the mouse, if you're wanting to work interactively.\nIf you're just wanting to rotate the axes programatically, then use ax.view_init(elev, azim) where elev and azim are the elevation and azimut... | [
30,
14
] | [] | [] | [
"charts",
"matplotlib",
"python",
"scatter_plot"
] | stackoverflow_0004739360_charts_matplotlib_python_scatter_plot.txt |
Q:
How should I create my object so it works with networkx pretty well?
I'm trying to design a project that takes global positioning data, like city and state names along with latitudes and locations. I'll also have distances between every pair of cities. I want to make a graph with all of this information, and manip... | How should I create my object so it works with networkx pretty well? | I'm trying to design a project that takes global positioning data, like city and state names along with latitudes and locations. I'll also have distances between every pair of cities. I want to make a graph with all of this information, and manipulate it to perform some graph algorithms. I've decided to have city objec... | [
"Depending on what version of networkx you have installed, there is a built-in implementation of min_cut available.\nI had the 1.0RC1 package installed and that was not available.. but I upgraded to 1.4 and min_cut is there.\nHere's a (silly) example:\nimport networkx as nx\ng = nx.DiGraph()\ng.add_nodes_from(['Lon... | [
1,
0,
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0004739238_networkx_python.txt |
Q:
Need an input control program in python
I want to create a program that catches mouse clicks, no matter in which application it is sent to. Then it has to simulate twenty mouse clicks in one second. I am quite new to Python, and I am not really understanding much, but I've searched in several sites and I assembled... | Need an input control program in python | I want to create a program that catches mouse clicks, no matter in which application it is sent to. Then it has to simulate twenty mouse clicks in one second. I am quite new to Python, and I am not really understanding much, but I've searched in several sites and I assembled this code:
import time
import ctypes
import ... | [
"Use eventghost: http://www.eventghost.org/\n\nOpen source\nYou can write plugins in Python\nYou can catch lots of different events (you can even capture raw HID devices)\nYou can make it run/do anything you could normally do with Python\n\n"
] | [
1
] | [] | [] | [
"input",
"mouse",
"python",
"windows"
] | stackoverflow_0004354011_input_mouse_python_windows.txt |
Q:
Python: Build a dictionary from a file's contents
Say that I have a file of names and values with entries like this:
lasker:22,45,77,101
kramnik:45,22,15,105
What's the most Pythonic way to get them into a dictionary with the name as the key and the values as a list like this:
{ 'lasker': (22,45,77,101), 'kramnik... | Python: Build a dictionary from a file's contents | Say that I have a file of names and values with entries like this:
lasker:22,45,77,101
kramnik:45,22,15,105
What's the most Pythonic way to get them into a dictionary with the name as the key and the values as a list like this:
{ 'lasker': (22,45,77,101), 'kramnik': (45,22,15,105) }
EDIT
And is there anyway to iterat... | [
"I think it is pretty clear how this code works:\ndef get_entries( infile ):\n with open( infile, 'rt') as file:\n for line in file:\n name, nums = line.split(':', 1)\n yield name, tuple(int(x) for x in nums.split(','))\n\n# dict takes a sequence of `(key, value)` pairs and turns in... | [
13,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004736563_dictionary_list_python.txt |
Q:
what does <> mean in Python
What is the meaning of <> in Python?
I have tried searching for it on Google but I cannot seem to get inside the search term...
I have not seen this in any other language also otherwise I would have tried to find it.
A:
<> is an alternate spelling of !=, the inequality test operator. ... | what does <> mean in Python | What is the meaning of <> in Python?
I have tried searching for it on Google but I cannot seem to get inside the search term...
I have not seen this in any other language also otherwise I would have tried to find it.
| [
"<> is an alternate spelling of !=, the inequality test operator. IIRC, it has been removed in Python3.\n>>> \"foo\" <> \"bar\"\nTrue\n>>> \"foo\" <> \"foo\"\nFalse\n\n",
"It is an obsolete inequality operator. See the Python documentation.\n\n!= can also be written <>, but this is\n an obsolete usage kept for b... | [
15,
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004738285_python.txt |
Q:
"%" character cause Error in strings substitution with locals()
I try to substitue strings with variables using locals() in python but I can find a way to use the % character inside the string without error. Here is a concrete example :
color = colors_generator() #the function return a color
html = """<html><hea... | "%" character cause Error in strings substitution with locals() | I try to substitue strings with variables using locals() in python but I can find a way to use the % character inside the string without error. Here is a concrete example :
color = colors_generator() #the function return a color
html = """<html><head>
<style>#square{color:%(color)s;width:100%;height:100%;}</style> ... | [
"escape % with %\nhtml = \"\"\"<html><head>\n<style>#square{color:%(color)s;width:100%%;height:100%%;}</style> \n</head> <body> <div id=\"square\"> </div>\n</body></html>\"\"\" % locals()\n\n",
"Virhilo has already answered your direct question, but if you find you are building quite big/complicated templ... | [
4,
1
] | [] | [] | [
"locals",
"python",
"string_substitution"
] | stackoverflow_0004740484_locals_python_string_substitution.txt |
Q:
How to list all artists in a rhythmbox plugin
I'm trying to list all artists in the rhythmbox database from within a rhythmbox python plugin. The only solution I have found is to make the UI select all artists and all songs, loop through every song and add that song's artist name to a set.
The problem with this is... | How to list all artists in a rhythmbox plugin | I'm trying to list all artists in the rhythmbox database from within a rhythmbox python plugin. The only solution I have found is to make the UI select all artists and all songs, loop through every song and add that song's artist name to a set.
The problem with this is (beside from the fact it's painfully inefficient) ... | [
"I found it! It was the property base_query_model I should use if I want to list all entries regardless of what is selected in the UI.\nThe code now looks like:\nimport rb\nimport rhythmdb\nimport gtk\n\nclass DblisterPlugin (rb.Plugin):\n def __init__(self):\n rb.Plugin.__init__(self)\n def activate(s... | [
1
] | [] | [] | [
"python",
"rhythmbox"
] | stackoverflow_0004740225_python_rhythmbox.txt |
Q:
Python program that repeatadly counts odd and even digits and sums them up
Given a number, how can we count the number of odd and even digits and then sum them up in Python? Apparently if you do this repeat this process, you will always end up with 123 for any number. I would like to do this in Python.
Example:
5... | Python program that repeatadly counts odd and even digits and sums them up | Given a number, how can we count the number of odd and even digits and then sum them up in Python? Apparently if you do this repeat this process, you will always end up with 123 for any number. I would like to do this in Python.
Example:
5683474
4 3 = 7 (4 even and 3 odd) 4, 3 and 7 now make up a new number.
1 2 = 3
... | [
"Since this is probably homework, here are a few hints:\n\nYou can convert an integer into a string using the str() function\nYou can convert a string into a list of characters using the list() function.\nYou can convert a character to an integer (assuming it's a number) using the int() function\nAn even number has... | [
4,
4
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0004740633_loops_python.txt |
Q:
Python & Django plugins for Vim
Any recommendations for specific Python and/or Django plugins for Vim?
Thanks.
A:
http://code.djangoproject.com/wiki/UsingVimWithDjango
A:
python.vim http://www.vim.org/scripts/script.php?script_id=30
| Python & Django plugins for Vim | Any recommendations for specific Python and/or Django plugins for Vim?
Thanks.
| [
"http://code.djangoproject.com/wiki/UsingVimWithDjango\n",
"python.vim http://www.vim.org/scripts/script.php?script_id=30\n"
] | [
3,
1
] | [] | [] | [
"django",
"plugins",
"python",
"vim"
] | stackoverflow_0004740601_django_plugins_python_vim.txt |
Q:
Caching files for later rebuilds with distutils
I'm building a set of Python extensions with distutils. The extensions depend on external libraries (unrelated to Python) which are normally built from source using Makefiles. Those external libs are unlikely to change often.
To ease the users' pain, my setup.py scri... | Caching files for later rebuilds with distutils | I'm building a set of Python extensions with distutils. The extensions depend on external libraries (unrelated to Python) which are normally built from source using Makefiles. Those external libs are unlikely to change often.
To ease the users' pain, my setup.py scripts fetch the libraries from the web using urllib.url... | [
"It should be possible to use those folders, here's how to get those names from distutils. \nHowever, those folders are pretty volatile. I'd suggest having an empty directory on the source distribution for receiving these downloads, with a README file explaining its role as a build cache.\n"
] | [
1
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0004519898_distutils_python.txt |
Q:
The best way to connect users in closed proximity ? (latitude, longitude)
I create an android app which connect runners in closed proximity. I used a Tornado ServerWeb (Python) and a No-SQL database.
My solution:
Store all the {lon,lat} (regularly updated) of users in a DataLocation.
When a user want to see users ... | The best way to connect users in closed proximity ? (latitude, longitude) | I create an android app which connect runners in closed proximity. I used a Tornado ServerWeb (Python) and a No-SQL database.
My solution:
Store all the {lon,lat} (regularly updated) of users in a DataLocation.
When a user want to see users around him, it calls specific function to my server which make a bounding box f... | [
"If you don't have a library and want to do it yourself, you can calculate distance using the Great Circle Distance. The formula is not too complex. To find a group of points that are within a certain radius, you will need to query the database for points whose distance(as calculated by great circle distance) is ... | [
0
] | [] | [] | [
"android",
"bounding_box",
"geojson",
"geolocation",
"python"
] | stackoverflow_0004740582_android_bounding_box_geojson_geolocation_python.txt |
Q:
How can I run a python script for a certain amount of time, pause it, determine where in the code it is at, and then continue it?
I've looked into the code module, but I don't see the kind of functionality I need there. Any suggestions?
A:
http://docs.python.org/library/pdb.html
| How can I run a python script for a certain amount of time, pause it, determine where in the code it is at, and then continue it? | I've looked into the code module, but I don't see the kind of functionality I need there. Any suggestions?
| [
"http://docs.python.org/library/pdb.html\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004741057_python.txt |
Q:
How can I schedule an email to be sent at some point in the future in django?
I want to schedule an email to be sent to a user upon a specific action.
However, if the user takes another action I want to cancel that email and have it not send.
How would I do that in django or python?
A:
Beanstalkd
If you can inst... | How can I schedule an email to be sent at some point in the future in django? | I want to schedule an email to be sent to a user upon a specific action.
However, if the user takes another action I want to cancel that email and have it not send.
How would I do that in django or python?
| [
"Beanstalkd\nIf you can install beanstalkd and run python script from command line I would use that to schedule emails. With beanstalkc client you can easily accomplish this. On ubuntu you might first need to install:\n\nsudo apt-get install python-yaml python-setuptools \n\nconsumer.py:\nimport beanstalkc\ndef mai... | [
4,
3,
2,
0,
0
] | [] | [] | [
"django",
"email",
"python",
"schedule"
] | stackoverflow_0004731419_django_email_python_schedule.txt |
Q:
Help in designing layout with qtdesigner for python
I am working on Qtdesigner for generating a GUI for my python app.
The problem is that I had manually made the widgets and then compiled it to py. But then I found out that the components did not resize when maximised.
So I opened the .ui file in designer and sel... | Help in designing layout with qtdesigner for python | I am working on Qtdesigner for generating a GUI for my python app.
The problem is that I had manually made the widgets and then compiled it to py. But then I found out that the components did not resize when maximised.
So I opened the .ui file in designer and selected the group box for my widgets and chose layout in gr... | [
"To have the widgets resized with the window, you must apply a layout to your top-level object (usually QMainWindow), and then place your new widgets where you want in the layout (and maybe other layouts for a more complicated window).\nNOTE: the menu items allowing to apply a layout on the main window will be avai... | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt",
"qt_designer"
] | stackoverflow_0004737324_pyqt4_python_qt_qt_designer.txt |
Q:
Append elements of a set to a list in Python
How do you append the elements of a set to a list in Python in the most succinct way?
>>> a = [1,2]
>>> b = set([3,4])
>>> a.append(list(b))
>>> a
[1, 2, [3, 4]]
But what I want is:
[1, 2, 3, 4]
A:
Use
a.extend(list(b))
or even easier
a.extend(b)
instead.
A:
You ... | Append elements of a set to a list in Python | How do you append the elements of a set to a list in Python in the most succinct way?
>>> a = [1,2]
>>> b = set([3,4])
>>> a.append(list(b))
>>> a
[1, 2, [3, 4]]
But what I want is:
[1, 2, 3, 4]
| [
"Use\na.extend(list(b))\n\nor even easier\na.extend(b)\n\ninstead.\n",
"You could use extend as already pointed out, but there's also a more concise approach:\n>>> a += b\n>>> a\n[1, 2, 3, 4]\n\n",
"If you want to update the list, this works for me:\na += b\n\nIf you want a non-mutating expression:\na + list(b)... | [
36,
7,
2
] | [] | [] | [
"list",
"python",
"set"
] | stackoverflow_0004741537_list_python_set.txt |
Q:
My for loop doesn't get the values
Here's what I have:
result = defaultdict(<type 'list'>,
{'USA': [{'username': 'user123', 'first-name': 'John', 'last-name': 'Doe'}],
'Europe': [{'username': 'myname654', 'first-name': 'Peter', 'last-name': 'Johnson'}]
})
Here's the output I want to get
<html>
<body>
<h1> ... | My for loop doesn't get the values | Here's what I have:
result = defaultdict(<type 'list'>,
{'USA': [{'username': 'user123', 'first-name': 'John', 'last-name': 'Doe'}],
'Europe': [{'username': 'myname654', 'first-name': 'Peter', 'last-name': 'Johnson'}]
})
Here's the output I want to get
<html>
<body>
<h1> USA </h1>
<p> user123, John Doe</p>
... | [
"Result is a dictionary. Iterating through a dictionary with for x in mydict just gives the keys, not the values. So you need to do {% for item, value in mydict.items %}.\nSecondly, {{ result.item.username }} makes no sense at all. item is a the value of a key into the result dict, but you can't do that sort of ind... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004740312_django_python.txt |
Q:
Python: What date/time is it in NYC? (without pytz)
In Python, I want a Python program to be able to determine the current date and time in NYC . Is that practical? While datetime.datetime.now() can tell me the local time, and datetime.utcnow() can tell me the UTC (GMT). However just looking at the difference wi... | Python: What date/time is it in NYC? (without pytz) | In Python, I want a Python program to be able to determine the current date and time in NYC . Is that practical? While datetime.datetime.now() can tell me the local time, and datetime.utcnow() can tell me the UTC (GMT). However just looking at the difference will not help me as DST changes.
I try things like "dt=date... | [
"I suspect some sort of problems in your use of the datetime, time, etc. modules, but without knowing more, not much help can be provided.\nThe following suggestion has some definite drawbacks, and I really recommend more pursuit to solving the problems with datetime, etc. However, if you're sure to have a web con... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004740961_python.txt |
Q:
Logical argument checking in python
I am not sure my question has a concrete answer, but anyway. I am writing a function with a lot of parameters, each one can be either None or have a limited range of values. Since I don't trust the user to give me good input, I have to check each parameter for its type, and if i... | Logical argument checking in python | I am not sure my question has a concrete answer, but anyway. I am writing a function with a lot of parameters, each one can be either None or have a limited range of values. Since I don't trust the user to give me good input, I have to check each parameter for its type, and if it's in the right type (or None), then I w... | [
"I would agree with the above: assume the size is of the right type, let an exception be raised (or an error be returned) if it isn't.\nThere is a useful pattern, though, when you're dealing with input that might raise an exception: wrapping any exceptions raised by the input so they include the input. For example,... | [
1,
1,
1,
0
] | [] | [] | [
"parameters",
"parsing",
"python",
"typechecking"
] | stackoverflow_0004741305_parameters_parsing_python_typechecking.txt |
Q:
Statically linking OpenSSL with M2Crypto
M2Crypto uses the standard
python setup.py [build|install]
step to build and install the module. distutils/setuptools allows for some tweaking, but I can't seem to find a way to statically link OpenSSL into the module - there doesn't appear to be any facility to make this... | Statically linking OpenSSL with M2Crypto | M2Crypto uses the standard
python setup.py [build|install]
step to build and install the module. distutils/setuptools allows for some tweaking, but I can't seem to find a way to statically link OpenSSL into the module - there doesn't appear to be any facility to make this change.
Is there any way to build M2Crypto wi... | [
"You need the static link libraries for OpenSSL (ssleay32, libeay32), which you might have to build yourself. On Windows you'll have to change setup.py to include some more libraries, e.g.:\n-self.libraries = ['ssleay32', 'libeay32']\n+self.libraries = ['ssleay32', 'libeay32', 'crypt32', 'user32', 'gdi32', 'kernel3... | [
1
] | [] | [] | [
"m2crypto",
"openssl",
"python"
] | stackoverflow_0004741327_m2crypto_openssl_python.txt |
Q:
Design ideas for a webapp in Django
I'm working on a user based, social networking type of web application in Django. It's my first one so I would like to make sure I'm using some good practices.
Currently the web app supports two kinds of users. This is represented by two different Groups. When I register a us... | Design ideas for a webapp in Django | I'm working on a user based, social networking type of web application in Django. It's my first one so I would like to make sure I'm using some good practices.
Currently the web app supports two kinds of users. This is represented by two different Groups. When I register a user I assign them to one of these two grou... | [
"Easy part first, with 2) you're spot on. That would be the simplest and most effective way of doing that. It makes sense instead of replicating functionality across both applications to have one app that handles things that are common to both user types.\nBack to 1)\nWith both profiles extending from UserProfile, ... | [
2
] | [] | [] | [
"django",
"python",
"web_applications"
] | stackoverflow_0004740924_django_python_web_applications.txt |
Q:
Is there a Python library for service discovery using SSDP or UPnP?
Is there a library for implementing Simple Service Discovery Protocol(SSDP) via UPnP in Python? Basically, I want to make protocols for SSDP using python.
A:
http://brisa.garage.maemo.org/doc/html/upnp/ssdp.html
| Is there a Python library for service discovery using SSDP or UPnP? | Is there a library for implementing Simple Service Discovery Protocol(SSDP) via UPnP in Python? Basically, I want to make protocols for SSDP using python.
| [
"http://brisa.garage.maemo.org/doc/html/upnp/ssdp.html\n"
] | [
3
] | [] | [] | [
"python",
"service_discovery",
"upnp"
] | stackoverflow_0004742001_python_service_discovery_upnp.txt |
Q:
Python: Code string to shorter meaningless string in reversible way
I'm sorry for the generic question (I don't have any past knowledge about compression and I don't know if it has a possible solution).
I have some codes of always 19 characters.
These characters can be only: A-Z, a-z, 0-9, ., :, -
An example can b... | Python: Code string to shorter meaningless string in reversible way | I'm sorry for the generic question (I don't have any past knowledge about compression and I don't know if it has a possible solution).
I have some codes of always 19 characters.
These characters can be only: A-Z, a-z, 0-9, ., :, -
An example can be something like 1995AbC...123..456Z
What I want to do is to find a way t... | [
"You can try to compress the string and the encode the result to for example base64. This of course assumes that your original strings are compressible. For strings of 19 characters this seems unlikely.\nIf you are allowed to persist some data you can compress the first string to 1, the second to 2, etc... and you ... | [
5,
4,
2
] | [] | [] | [
"compression",
"python",
"translation"
] | stackoverflow_0004741223_compression_python_translation.txt |
Q:
Difference Between Satchmo's local_settings.py and settings.py
Can someone explain the difference between local_settings.py and settings.py in Satchmo?
I understand that the settings.py module imports the local_settings.py module as it's final step. So any settings in local_settings.py takes precedence. But what i... | Difference Between Satchmo's local_settings.py and settings.py | Can someone explain the difference between local_settings.py and settings.py in Satchmo?
I understand that the settings.py module imports the local_settings.py module as it's final step. So any settings in local_settings.py takes precedence. But what is the point of doing this? Isn't settings.py supposed to be the conf... | [
"The local_settings.py is only for on your local development system where it extends settings.py. On your deployment server, settings.py is used only without local_settings.py.\nOne recommendation is that local_settings.py is not included in your repository, so that each developer can have their own and so that it ... | [
5,
0
] | [] | [] | [
"django",
"python",
"satchmo"
] | stackoverflow_0004740528_django_python_satchmo.txt |
Q:
Why doesn't this Python work? Simple Oop
class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
I created a file "abc.py" and put above in it.
>>> import abc
>>> d = abc.UserDict()
Traceback (most recent call ... | Why doesn't this Python work? Simple Oop | class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
I created a file "abc.py" and put above in it.
>>> import abc
>>> d = abc.UserDict()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
A... | [
"Most certainly you are importing the Python abc module for abstract base classes instead of your own abc.py. Better choose a different name for your module.\nEdit: Of course it is possible to have your own module with the same name as a built-in module and to import it. You have to make sure that your module is ... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004742145_python.txt |
Q:
How can I store and query 50 million simple Python dicts?
Question
Each dict has a unique numeric id field but the rest are variable (all text or numeric values though). Some simple query functionality would be nice e.g. get where name contains 'abc' or where a < 123.
What are my options?
Setup
Python 2.6
32-bit ... | How can I store and query 50 million simple Python dicts? | Question
Each dict has a unique numeric id field but the rest are variable (all text or numeric values though). Some simple query functionality would be nice e.g. get where name contains 'abc' or where a < 123.
What are my options?
Setup
Python 2.6
32-bit Ubuntu-server 256MB
single machine
no swap
example dict:
{'id'... | [
"You can try using CouchDB. It's a document-oriented database. There are examples (e.g. here) of storing millions and more documents.\nThere is a good guide to CouchDB.\nYour numeric id field can be used as a document id.\nYou can try writing a python script that fills the database using bulk APIs (to make insertio... | [
2,
1,
1,
1,
0
] | [] | [] | [
"nosql",
"python",
"ubuntu"
] | stackoverflow_0004725114_nosql_python_ubuntu.txt |
Q:
python multiline regex
I'm having an issue compiling the correct regular expression for a multiline match. Can someone point out what I'm doing wrong. I'm looping through a basic dhcpd.conf file with hundreds of entries such as:
host node20007 ... | python multiline regex | I'm having an issue compiling the correct regular expression for a multiline match. Can someone point out what I'm doing wrong. I'm looping through a basic dhcpd.conf file with hundreds of entries such as:
host node20007 ... | [
"Update I've just noticed the real reason that you are getting the results that you got; in your code:\nfor host in f:\n match = re_hostinfo.search(host)\n if match:\n print match.groups()\n\nhost refers to a single line, but your pattern needs to work over two lines.\nTry this:\ndata = f.read()\nfor x... | [
12,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004740739_python_regex.txt |
Q:
How much do imports slow down Django?
What if I'm importing 100 things ?
(In the top of my views.py)
And then inside each of them, I'm importing 30 things.
Will that slow things down?
A:
It will slow down startup (actually, whatever loads the file containing those imports the first time will be slowed down).
Ass... | How much do imports slow down Django? | What if I'm importing 100 things ?
(In the top of my views.py)
And then inside each of them, I'm importing 30 things.
Will that slow things down?
| [
"It will slow down startup (actually, whatever loads the file containing those imports the first time will be slowed down).\nAssuming django does not do that for every request but only once, it is not an issue at all.\n",
"Only the first time they're imported in the process. After that, all that happens is that a... | [
4,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004742338_django_python.txt |
Q:
Help with error handling for Python
For the simple snippet below
a = raw_input("Enter a number: ")
How can I write an exception such that if a string is entered, the user is re-prompted to try again and again until an integer is entered.
In other words, keep doing this until an integer is entered.:
if a.isdigit =... | Help with error handling for Python | For the simple snippet below
a = raw_input("Enter a number: ")
How can I write an exception such that if a string is entered, the user is re-prompted to try again and again until an integer is entered.
In other words, keep doing this until an integer is entered.:
if a.isdigit == False:
raw_input("Try again: ")
| [
"The usual way to achieve this is to use int() with exception handling:\n>>> n = None\n>>> while n is None:\n... a = raw_input(\"Enter a number: \")\n... try:\n... n = int(a)\n... except ValueError:\n... print \"Not a number.\"\n...\nEnter a number: abc\nNot a number.\nEnter a number: cauliflower... | [
2,
1,
1,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0004742483_error_handling_python.txt |
Q:
Adding permissions to django users which have add-on models
I will be creating an intranet site with multiple roles (client-employee, client-admin, staff team member). Each role will have a model that attaches (via One-to-One or ForeignKey field) to a user with custom fields. I want each role to have it's own set ... | Adding permissions to django users which have add-on models | I will be creating an intranet site with multiple roles (client-employee, client-admin, staff team member). Each role will have a model that attaches (via One-to-One or ForeignKey field) to a user with custom fields. I want each role to have it's own set of permissions (like a group).
How can I store this permissions ... | [
"Access control lists are tricky (some say dead), but Django comes with a good default implementation in contrib.auth equipped with:\n\nUsers\nPermissions: Binary (yes/no) flags designating whether a user may perform a certain task.\nGroups: A generic way of applying labels and permissions to more than one user.\n\... | [
1
] | [] | [] | [
"django",
"django_authentication",
"django_models",
"python"
] | stackoverflow_0004742572_django_django_authentication_django_models_python.txt |
Q:
how to test for a regex match
I have a string. Let's call it 'test'.
I want to test a match for this string, but only using the backref of a regex.
Can I do something like this:
import re
for line in f.readlines():
if '<a href' in line:
if re.match('<a href="(.*)">', line) == 'test':
print 'matc... | how to test for a regex match | I have a string. Let's call it 'test'.
I want to test a match for this string, but only using the backref of a regex.
Can I do something like this:
import re
for line in f.readlines():
if '<a href' in line:
if re.match('<a href="(.*)">', line) == 'test':
print 'matched!'
?
This of course, doesn't se... | [
"re.match matches only at the beginning of the string.\ndef url_match(line, url):\n match = re.match(r'<a href=\"(?P<url>[^\"]*?)\"', line)\n return match and match.groupdict()['url'] == url:\n\nexample usage:\n>>> url_match('<a href=\"test\">', 'test')\nTrue\n>>> url_match('<a href=\"test\">', 'te')\nFalse\n... | [
38
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004742662_python_regex.txt |
Q:
upgrading python
Hi
I just want to install mercurial but for all versions it needs python 2.6, I tried to use .rpm file but the only thing I got is lots of lines full of error which tells: need old versions before 2.6 and after 2.5 which is installed on my linux. any help would be appreciated.
Bests
A:
Go to Act... | upgrading python | Hi
I just want to install mercurial but for all versions it needs python 2.6, I tried to use .rpm file but the only thing I got is lots of lines full of error which tells: need old versions before 2.6 and after 2.5 which is installed on my linux. any help would be appreciated.
Bests
| [
"Go to ActiveState and download their versions: https://www.activestate.com/activepython/downloads\nIt's much easier than using the .rpms.\n",
"Which distribution are you using? I would recommend you to upgrade your system to a newer version of your linux distro, whatever it is. Modern Linux distros are using at ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004739268_python.txt |
Q:
creating a python rpm to install
I have created a dead simple gtk python app (just a pycairo animation) for gnome.
I am trying to make an rpm so that it is easy for others to install it. I was hoping to make my app appear in the gnome application menu. I am running into trouble when I try to install it on Fedora ... | creating a python rpm to install | I have created a dead simple gtk python app (just a pycairo animation) for gnome.
I am trying to make an rpm so that it is easy for others to install it. I was hoping to make my app appear in the gnome application menu. I am running into trouble when I try to install it on Fedora 13 (my own box).
I follow the instruct... | [
"Extract the spec from the generated SRPM and then clean it up as per the Fedora Packaging guidelines.\n\"Packaging:Guidelines\"\n\"Packaging:Python\"\n"
] | [
3
] | [] | [] | [
"gnome",
"packaging",
"python",
"rpm"
] | stackoverflow_0004743002_gnome_packaging_python_rpm.txt |
Q:
Is nested recursion possible or should we avoid recursion ?
I came across a question like this
F(1) = 1
F(2n) = F(n)
F(2n+1) = F(n) + F(n+1)
Develop a recursive program to compute F
Some user mentioned using two recursive function calls:
def calc(n):
if n=1 :
return 1
else if(n%2)==0:
return calc(n/2... | Is nested recursion possible or should we avoid recursion ? | I came across a question like this
F(1) = 1
F(2n) = F(n)
F(2n+1) = F(n) + F(n+1)
Develop a recursive program to compute F
Some user mentioned using two recursive function calls:
def calc(n):
if n=1 :
return 1
else if(n%2)==0:
return calc(n/2)
else :
return calc(n/2)+calc(n/2+1) **NESTED RECURSION**... | [
"Both of these approaches are correct. It is indeed legal to have multiple recursive calls from a function, and the meaning is what you'd think - just do one call, then the next, then the next, etc.\nInterestingly, I don't think that the recursive version does make exponentially many calls. It makes at most two r... | [
9,
3,
3,
3
] | [] | [] | [
"algorithm",
"big_o",
"python",
"recursion"
] | stackoverflow_0004741307_algorithm_big_o_python_recursion.txt |
Q:
Lambda function to simplify unittest?
I have an Sport class defined as:
Sport:
- name
- other fields
I have a test where I want to verify that adding the sport 'rugby' is contained in the list of sport_objects.
Currently, the test is brittle, checking the name of the object at the index I know it's at:
self.ass... | Lambda function to simplify unittest? | I have an Sport class defined as:
Sport:
- name
- other fields
I have a test where I want to verify that adding the sport 'rugby' is contained in the list of sport_objects.
Currently, the test is brittle, checking the name of the object at the index I know it's at:
self.assertEquals('rugby', sports_objects[3].name)
... | [
"self.assertIn('rugby', [sport_object.name for sport_object in sports_objects])\n\n",
"You can always do:\nself.assertIn('rugby', (x.name for x in sports_objects))\n\nor something like\nimport operator\nop = operator.attrgetter(\"name\")\nself.assertIn('rugby', map(op, sport_objects))\n\n"
] | [
2,
1
] | [] | [] | [
"nose",
"python",
"unit_testing"
] | stackoverflow_0004743199_nose_python_unit_testing.txt |
Q:
Python 3.1.3 Win 7: csv writerow Error "must be bytes or buffer, not str"
Got a simple script which worked perfectly under Python 2.7.1 at my Win xp machine.
Now got a win 7 machine with python 3.1.3.
The code is:
owriter.writerow(dtime[1][1])
dtime[1][1]=['30-Aug-10 16:00:00', '2.5', '15']
Got this error messag... | Python 3.1.3 Win 7: csv writerow Error "must be bytes or buffer, not str" | Got a simple script which worked perfectly under Python 2.7.1 at my Win xp machine.
Now got a win 7 machine with python 3.1.3.
The code is:
owriter.writerow(dtime[1][1])
dtime[1][1]=['30-Aug-10 16:00:00', '2.5', '15']
Got this error message: TypeError: must be bytes or buffer, not str
What changes should I make?
than... | [
"In Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.\nIn Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:\noutpu... | [
16,
6,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004739066_python_python_3.x.txt |
Q:
Finding character position from a RegEx'd string
Say, I have 'ABBACDA', and I want to find the index of where each A is.
Using Regex in Python,
match = re.findall('A', 'ABBACDA')
only returns a list.
Any way I can tweak this? Or should I go an entirely different route? I wanted to avoid using a for x in enumerate... | Finding character position from a RegEx'd string | Say, I have 'ABBACDA', and I want to find the index of where each A is.
Using Regex in Python,
match = re.findall('A', 'ABBACDA')
only returns a list.
Any way I can tweak this? Or should I go an entirely different route? I wanted to avoid using a for x in enumerate(str) because I also would like to check for where, sa... | [
"Use re.finditer() \nexample 1:\nmatch = re.finditer('A', 'ABBACDA')\nfor m in match:\n print m.start(), m.end(), m.group(0)\n\noutput:\n0 1 A\n3 4 A\n6 7 A\n\nexample 2:\nmatch = re.finditer('BB', 'ABBACDA')\nfor m in match:\n print m.start(), m.end(), m.group(0)\n\noutput :\n1 3 BB\n\n",
"To John Machin\n... | [
5,
2,
0,
0,
0
] | [
"I likes regexes but I searched another solution :\nch = 'ABBACDABBmmrteyBBgfrewBBBBBioBBytA BBB ggdAdbBB BBbGtBBABGtbBbGT'\ntof = 'A'\n\nli, prec = [], 0\nx = ch[prec:].find(tof)\n\nwhile x+1:\n li.append(prec+x)\n prec += x+1\n x = ch[prec:].find(tof)\n\nprint li\n\nresult\n[0, 3, 6, 33, 42, 55]\n\nI mea... | [
-1
] | [
"python",
"regex"
] | stackoverflow_0004742287_python_regex.txt |
Q:
Python Difflib Deltas and Compare Ndiff
I was looking to do something like what I believe change control systems do, they compare two files, and save a small diff each time the file changes.
I've been reading this page: http://docs.python.org/library/difflib.html and it's not sinking in to my head apparently.
I ... | Python Difflib Deltas and Compare Ndiff | I was looking to do something like what I believe change control systems do, they compare two files, and save a small diff each time the file changes.
I've been reading this page: http://docs.python.org/library/difflib.html and it's not sinking in to my head apparently.
I was trying to recreate this in a somewhat sim... | [
"\nI'm also still trying to figure out\n why many difflib functions return a\n generator instead of a list, what's\n the advantage there?\n\nWell, think about it for a second - if you compare files, those files can in theory (and will be in practice) be quite large - returning the delta as a list, for exampe, me... | [
5,
4,
1
] | [] | [] | [
"delta",
"difflib",
"python"
] | stackoverflow_0004743359_delta_difflib_python.txt |
Q:
Python: TypeError: takes exactly 1 argument (2 given)
I'm currently using singpath.com to practice my python, but I face an issue with a problem:
The expected result is:
>>>CurryPuff(3)
3.60
>>>CurryPuff(3,'Fish')
4.2
This is something I tried:
def CurryPuff(x,typePuff):
if(typePuff==''):
return x*1... | Python: TypeError: takes exactly 1 argument (2 given) | I'm currently using singpath.com to practice my python, but I face an issue with a problem:
The expected result is:
>>>CurryPuff(3)
3.60
>>>CurryPuff(3,'Fish')
4.2
This is something I tried:
def CurryPuff(x,typePuff):
if(typePuff==''):
return x*1.2
if(typePuff=='Fish'):
return x*1.4
But it gi... | [
"You can't call a function with 1 argument if it expects 2, as CurryPuff() does. However, you can define a default argument that is used if no argument is passed:\ndef CurryPuff(x, typePuff=None):\n if typePuff is None:\n # and so on...\n\nYou can do this with any value for any argument. You may only omit ... | [
16
] | [] | [] | [
"python"
] | stackoverflow_0004743673_python.txt |
Q:
Can't connect to server through SSH in Django application
I'm writing fairly simple application which connects to server through SSH (using paramiko), does something and writes output to web page. I wrote a script which works well when I run it from command line. However, if I run it in Django application, it can'... | Can't connect to server through SSH in Django application | I'm writing fairly simple application which connects to server through SSH (using paramiko), does something and writes output to web page. I wrote a script which works well when I run it from command line. However, if I run it in Django application, it can't get through connect part.
SSH connect part:
transport = param... | [
"I'm guessing your Django app may be running under a different user than the user you're running your command line script under. Also, I'm guessing it might be the first time the Django app user is trying to ssh to the host, so it may be hanging on some sort of 'is it OK to update ~/.ssh/known_hosts' question.\nIt... | [
3
] | [] | [] | [
"django",
"paramiko",
"python"
] | stackoverflow_0004721963_django_paramiko_python.txt |
Q:
How do I connect a Python and a C program?
I have a python-based program that reads serial data off an a port connected to an rs232 cable. I want to pass the data I get here to a C-program that will handle the computation-intensive side of things. I have been checking up the net and all I've found are linux-based.... | How do I connect a Python and a C program? | I have a python-based program that reads serial data off an a port connected to an rs232 cable. I want to pass the data I get here to a C-program that will handle the computation-intensive side of things. I have been checking up the net and all I've found are linux-based.
| [
"My suggestion would be the inline function from the instant module, though that only works if you can do everything you need to in a single c function. You just pass it a c function and it compiles a c extension at runtime.\n from instant import inline\n sieve_code = \"\"\"\n PyObject* prime_list(int max)... | [
9,
6,
5,
2,
1,
0,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0004743748_c_python.txt |
Q:
Fill Django Form Field Data with Db Data
I am trying pre-fill a form field with data from a Db object. How do you set up the form,view, and model to fill a field with this data?
The goal is to let the user only select data that is queried from the object. Ex. An event has bands playing, the user selects their fav... | Fill Django Form Field Data with Db Data | I am trying pre-fill a form field with data from a Db object. How do you set up the form,view, and model to fill a field with this data?
The goal is to let the user only select data that is queried from the object. Ex. An event has bands playing, the user selects their favorite band from those at the event.
I tried lo... | [
"Supposing your Events model has bands as Many-2-Many key, the layout of the forms and views would be as follows:\nforms.py:\nclass EditEventForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(EditEventForm, self).__init__(*args, **kwargs)\n self.fields['bands'].queryset= \\\n ... | [
4,
1
] | [] | [] | [
"django",
"django_forms",
"django_views",
"python"
] | stackoverflow_0004743910_django_django_forms_django_views_python.txt |
Q:
When should a Python script be split into multiple files/modules?
In Java, this question is easy (if a little tedious) - every class requires its own file. So the number of .java files in a project is the number of classes (not counting anonymous/nested classes).
In Python, though, I can define multiple classes in... | When should a Python script be split into multiple files/modules? | In Java, this question is easy (if a little tedious) - every class requires its own file. So the number of .java files in a project is the number of classes (not counting anonymous/nested classes).
In Python, though, I can define multiple classes in the same file, and I'm not quite sure how to find the point at which I... | [
"Remember that in Python, a file is a module that you will most likely import in order to use the classes contained therein. Also remember one of the basic principles of software development \"the unit of packaging is the unit of reuse\", which basically means:\nIf classes are most likely used together, or if using... | [
20,
3,
2,
0
] | [] | [] | [
"coding_style",
"conventions",
"python"
] | stackoverflow_0004743497_coding_style_conventions_python.txt |
Q:
How do you handle options that can't be used together (using OptionParser)?
My Python script (for todo lists) is started from the command line like this:
todo [options] <command> [command-options]
Some options can not be used together, for example
todo add --pos=3 --end "Ask Stackoverflow"
would specify both th... | How do you handle options that can't be used together (using OptionParser)? | My Python script (for todo lists) is started from the command line like this:
todo [options] <command> [command-options]
Some options can not be used together, for example
todo add --pos=3 --end "Ask Stackoverflow"
would specify both the third position and the end of the list. Likewise
todo list --brief --informati... | [
"Possibly by extending optparse.OptionParser:\nclass Conflict(object):\n __slots__ = (\"combination\", \"message\", \"parser\")\n\n def __init__(self, combination, message, parser):\n self.combination = combination\n self.message = str(message)\n self.parser = parser\n\n def accepts(se... | [
6,
3
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0002729426_optparse_python.txt |
Q:
django ModelForm save() method issue
I have a model form:
class SnippetForm(ModelForm):
class Meta:
model = Snippet
exclude = ['author', 'slug']
and I want to be able to edit a particular instance by using this:
def edit_snippet(request, snippet_id):
#look up for that snippet
snippet... | django ModelForm save() method issue | I have a model form:
class SnippetForm(ModelForm):
class Meta:
model = Snippet
exclude = ['author', 'slug']
and I want to be able to edit a particular instance by using this:
def edit_snippet(request, snippet_id):
#look up for that snippet
snippet = get_object_or_404(Snippet, pk=snippet_i... | [
"I don't see why it would happen. What version of django is it?\nIn any case, you can manually force update passing the corresponding argument.\nform = SnippetForm(data=request.POST, instance=snippet, force_update=True)\n\n"
] | [
1
] | [] | [] | [
"django",
"modelform",
"python",
"save"
] | stackoverflow_0004743967_django_modelform_python_save.txt |
Q:
Dynamically customize django form widgets
Specifically I want to add an error class if the field is invalid. So it would render out like this:
<input type="text" name="email" class="error" />
The example blow seems hacky and I have not seen any other examples of how to achieve this.
http://jj.isgeek.net/2010/10/2... | Dynamically customize django form widgets | Specifically I want to add an error class if the field is invalid. So it would render out like this:
<input type="text" name="email" class="error" />
The example blow seems hacky and I have not seen any other examples of how to achieve this.
http://jj.isgeek.net/2010/10/27/add-error-class-to-widgets-with-errors-in-dja... | [
"Unfortunately, there is no simple way beyond the hack you have already identified using the standard django.\n\nIs it possible to globally override the default widget templates?\n\nHow to solve this is being debated by the django developers.\nFor now, the solution that should appeal to you the most should be using... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004743946_django_django_forms_python.txt |
Q:
Google App Engine is not creating table (python)
I have this model
class SiteUser(db.Model):
site_user = db.UserProperty()
total_votes = db.IntegerProperty(default=1)
liked_items = db.StringProperty()
class Item(db.Model):
user_who_liked_this_item = db.UserProperty()
title = db.StringProperty(... | Google App Engine is not creating table (python) | I have this model
class SiteUser(db.Model):
site_user = db.UserProperty()
total_votes = db.IntegerProperty(default=1)
liked_items = db.StringProperty()
class Item(db.Model):
user_who_liked_this_item = db.UserProperty()
title = db.StringProperty()
url = db.StringProperty()
date = db.DateTime... | [
"There are no 'tables' on App Engine. A kind will show up in the datastore viewer if you have inserted at least one record with that kind; my guess is that you haven't inserted any SiteUser entities into the datastore.\n",
"When you use this the first time it will \"create a table\"\nnew_user = SiteUser()\nnew_us... | [
6,
2,
2
] | [] | [] | [
"google_app_engine",
"models",
"python"
] | stackoverflow_0004731657_google_app_engine_models_python.txt |
Q:
No path in sys.path with Python and tcsh
I don't have much experience with tcsh, but I am interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?
EDIT:
[dmcdonal@tg-steel... | No path in sys.path with Python and tcsh | I don't have much experience with tcsh, but I am interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?
EDIT:
[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dmcdona... | [
"How are you setting PYTHONPATH? You might be confusing tcsh's set vs. setenv. Use \"set\" to set what tcsh calls shell variables and use \"setenv\" to set environment variables. So, you need to use setenv in order for Python to see it. For example:\n$ set FOO='bar'\n$ echo $FOO\nbar\n$ python -c 'import os; pr... | [
10,
1,
0,
0
] | [] | [] | [
"python",
"tcsh"
] | stackoverflow_0000616440_python_tcsh.txt |
Q:
Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails
import Image
image = Image.open('images/original.jpg')
width = image.size[0]
height = image.size[1]
if width > height:
difference = width - height
offset = difference / 2
resize = (offset, 0, w... | Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails | import Image
image = Image.open('images/original.jpg')
width = image.size[0]
height = image.size[1]
if width > height:
difference = width - height
offset = difference / 2
resize = (offset, 0, width - offset, height)
else:
difference = height - width
offset = difference / 2
resiz... | [
"You just need to compare the aspect ratios - depending on which is larger, that will tell you whether to chop off the sides or the top and bottom. e.g. how about:\nimport Image\n\nimage = Image.open('images/original.jpg')\nwidth = image.size[0]\nheight = image.size[1]\n\naspect = width / float(height)\n\nideal_... | [
27
] | [] | [] | [
"aspect_ratio",
"image",
"python",
"resize",
"thumbnails"
] | stackoverflow_0004744372_aspect_ratio_image_python_resize_thumbnails.txt |
Q:
python threading with global variables
i encountered a problem when write python threading code, that i wrote some workers threading classes, they all import a global file like sharevar.py, i need a variable like regdevid to keep
tracking the register device id, then when one thread change it's value, then other t... | python threading with global variables | i encountered a problem when write python threading code, that i wrote some workers threading classes, they all import a global file like sharevar.py, i need a variable like regdevid to keep
tracking the register device id, then when one thread change it's value, then other threads can
get it fresh, but the result is ... | [
"My guess is you are trying to access the shared variable without a lock. If you do not acquire a lock and attempt to read a shared variable in one thread, while another thread is writing to it, the value could be indeterminate.\nTo remedy, make sure you acquire a lock in the thread before reading or writing to it.... | [
6,
3
] | [] | [] | [
"global",
"multithreading",
"python",
"variables"
] | stackoverflow_0004744426_global_multithreading_python_variables.txt |
Q:
AppDailySales: Works, but the downloaded gzip file is corrupted
I am trying to use the appdailysales.py module to download daily our iPhone apps. I am a .NET developer, so I tried running this using IronPython in a C# solution using the following code:
using IronPython.Hosting;
var ipy = Python.CreateRuntime();
d... | AppDailySales: Works, but the downloaded gzip file is corrupted | I am trying to use the appdailysales.py module to download daily our iPhone apps. I am a .NET developer, so I tried running this using IronPython in a C# solution using the following code:
using IronPython.Hosting;
var ipy = Python.CreateRuntime();
dynamic appSales = ipy.UseFile("appdailysales.py");
appSal... | [
"Looks like line 444 is the problem. Here are lines 444-446:\ndownloadFile = open(filename, 'w')\ndownloadFile.write(filebuffer)\ndownloadFile.close()\n\nAt this stage, IF you have deleted lines 429-435 OR selected not to unzip, then filebuffer refers to the raw gzipped stream that you got from the web. The output ... | [
1
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0004725222_ironpython_python.txt |
Q:
Is the official client for the YouTube API thread-safe?
I'm using the official Python client for the YouTube API (called gdata.youtube.service.) My question: Is it thread-safe?
For example, I want to do both GetUserFavoritesFeed and GetYouTubeUserFeed at the same time in two parallel threads. Possible?
A:
It's p... | Is the official client for the YouTube API thread-safe? | I'm using the official Python client for the YouTube API (called gdata.youtube.service.) My question: Is it thread-safe?
For example, I want to do both GetUserFavoritesFeed and GetYouTubeUserFeed at the same time in two parallel threads. Possible?
| [
"It's probably safe if you create a separate API instance for each thread.\n"
] | [
0
] | [] | [] | [
"gdata_api",
"gdata_python_client",
"python",
"youtube",
"youtube_api"
] | stackoverflow_0004291392_gdata_api_gdata_python_client_python_youtube_youtube_api.txt |
Q:
YouTube API: How do I specify latest protocol version when using `gdata` in Python?
I'm using the Python gdata package to interface with YouTube. I want it to use the latest protocol version. How do I do that?
A:
gdata.youtube.client uses a hard-coded api_version of 2, so you really have no choice to use any dif... | YouTube API: How do I specify latest protocol version when using `gdata` in Python? | I'm using the Python gdata package to interface with YouTube. I want it to use the latest protocol version. How do I do that?
| [
"gdata.youtube.client uses a hard-coded api_version of 2, so you really have no choice to use any different version. However, version 2 is the latest version.\n",
"Apparently gdata currently doesn't support YouTube protocol 2 yet.\n"
] | [
1,
0
] | [] | [] | [
"api",
"python",
"youtube"
] | stackoverflow_0004246048_api_python_youtube.txt |
Q:
Never use reflection in production code! What about Python?
I've written C# and the mantra coming from on high seems to be "never use reflection in production code". I have used it for test code, but never anything that runs in the wild. All the arguments seem reasonable, and there's always a way to do it by addin... | Never use reflection in production code! What about Python? | I've written C# and the mantra coming from on high seems to be "never use reflection in production code". I have used it for test code, but never anything that runs in the wild. All the arguments seem reasonable, and there's always a way to do it by adding another layer of abstraction or design pattern or whatever.
Now... | [
"As a dynamic language Python is fundamentally different than statically typed languages, so everything is reflection in it :-) Also never use reflection in production code (for static languages) seems a bit extreme to me.\n",
"I think that the \"no reflection in production code\" is not correct in c#.\nReflectio... | [
18,
6,
2,
0,
0
] | [] | [] | [
"c#",
"java",
"python",
"reflection"
] | stackoverflow_0004745071_c#_java_python_reflection.txt |
Q:
Django equivalent of PHP's form value array/associative array
In PHP, I would do this to get name as an array.
<input type"text" name="name[]" />
<input type"text" name="name[]" />
Or if I wanted to get name as an associative array:
<input type"text" name="name[first]" />
<input type"text" name="name[last]" />
W... | Django equivalent of PHP's form value array/associative array | In PHP, I would do this to get name as an array.
<input type"text" name="name[]" />
<input type"text" name="name[]" />
Or if I wanted to get name as an associative array:
<input type"text" name="name[first]" />
<input type"text" name="name[last]" />
What is the Django equivalent for such things?
| [
"Check out the QueryDict documentation, particularly the usage of QueryDict.getlist(key).\nSince request.POST and request.GET in the view are instances of QueryDict, you could do this:\n<form action='/my/path/' method='POST'>\n<input type='text' name='hi' value='heya1'>\n<input type='text' name='hi' value='heya2'>\... | [
64,
18,
5
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0000801354_django_forms_python.txt |
Q:
Does code written in IronPython work in IDLE
I am trying to choose an IDE for Python. I like IronPython and want to inquire if the code written in IronPython can run in a normal Python shell like IDLE
A:
Most Python code should work cross-platform, cross-IDE as at heart they all use the same interpreter (althoug... | Does code written in IronPython work in IDLE | I am trying to choose an IDE for Python. I like IronPython and want to inquire if the code written in IronPython can run in a normal Python shell like IDLE
| [
"Most Python code should work cross-platform, cross-IDE as at heart they all use the same interpreter (although versions may differ). Your IDE should only edit and run programs and will not affect the code you write.\n"
] | [
0
] | [] | [] | [
"ironpython",
"python",
"python_idle"
] | stackoverflow_0004745359_ironpython_python_python_idle.txt |
Q:
How can I suppress the output to console when importing packages in RPy2 in Python?
Whenever I run a script importing packages with import in RPy2 in Python, there are always some extra lines popping up in the console. I pasted in an example below. How can I suppress that behavior?
CookieJar:r cookies$ python scri... | How can I suppress the output to console when importing packages in RPy2 in Python? | Whenever I run a script importing packages with import in RPy2 in Python, there are always some extra lines popping up in the console. I pasted in an example below. How can I suppress that behavior?
CookieJar:r cookies$ python script.py
‘tseries’ version: 0.10-24
‘tseries’ is a package for time series analys... | [
"Besides require(tseries, quietly = TRUE) and using sink(), or its Python equivalent, there is also the simple\nsuppressMessages( library( tseries ))\n\nwhich I prefer.\n",
"You could temporarily redirect the output stream to a blackhole just before the spammy peice of code.\nimport sys\n\nclass Blackhole(object)... | [
7,
6,
2
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0004745388_python_r_rpy2.txt |
Q:
Automation of excel 2010 5 times slower than before
We have several programs generating excel documents via com automation, some written in VB6, some in python. Regardless of the programming language those programs run 5 times slower than with older excel versions. Profiling the python version shows that the addit... | Automation of excel 2010 5 times slower than before | We have several programs generating excel documents via com automation, some written in VB6, some in python. Regardless of the programming language those programs run 5 times slower than with older excel versions. Profiling the python version shows that the additional run time is spent mostly in low level com functiona... | [
"I cannot answer for Python, but for VBA/VB6 a significant number of changes were made in XL 2010 to improve performance rather than make it slower, see:http://blogs.office.com/b/microsoft-excel/archive/2009/09/03/performance-improvements-in-excel-2010.aspx Could you give a VB example of something that is 5 times s... | [
3
] | [] | [] | [
"automation",
"com",
"excel",
"performance",
"python"
] | stackoverflow_0004746115_automation_com_excel_performance_python.txt |
Q:
I need help with an lxml statement in python that extracts a meta-tag value
I need help fixing this lxml statement to extract the:
http://www.etc../1tru.jpg link in the head section of
http://www.yfrog.com/9d1truj
#This doesn't work!
# <link rel="image_src" href="http://img337.yfrog.com/img337/5023/1tru.jpg" />
d... | I need help with an lxml statement in python that extracts a meta-tag value | I need help fixing this lxml statement to extract the:
http://www.etc../1tru.jpg link in the head section of
http://www.yfrog.com/9d1truj
#This doesn't work!
# <link rel="image_src" href="http://img337.yfrog.com/img337/5023/1tru.jpg" />
def extract_imageurl(self, doc):
try:
self.url, = doc.xpath('//head//l... | [
"In [32]: doc.xpath('//head/link[@rel=\"image_src\"]/@href')[0]\nOut[32]: 'http://img337.yfrog.com/img337/5023/1tru.jpg'\n\nNotice xpath returns a list of nodes:\nIn [25]: doc.xpath('//head/link')\nOut[25]: [<Element link at 9c94c5c>, <Element link at 9c94b6c>]\n\nOnce you've specified [@rel=\"image_src\"] there is... | [
1
] | [] | [] | [
"html_parsing",
"lxml",
"python"
] | stackoverflow_0004747537_html_parsing_lxml_python.txt |
Q:
Should I bundle C libraries with my Python application?
If I have a Python package that depends on some C libraries (like say the Gnu Scientific Library (GSL) for numerical computations), is it a good idea to bundle the library with my code?
I'd like to make my package as easy to install as possible for users and ... | Should I bundle C libraries with my Python application? | If I have a Python package that depends on some C libraries (like say the Gnu Scientific Library (GSL) for numerical computations), is it a good idea to bundle the library with my code?
I'd like to make my package as easy to install as possible for users and I don't want them to have to download C libraries by hand and... | [
"Distribution is one of the hard parts for any software project. Java and .NET lift part of this burden by defining a standard runtime and then just saying \"just distribute everything else.\" Of course there's a drawback: everything must be rewritten in a language supported by the runtime - as soon as you want to ... | [
5,
0,
0
] | [] | [] | [
"c",
"distutils",
"python"
] | stackoverflow_0004700178_c_distutils_python.txt |
Q:
Count the multiple occurrences in a set
if group not in g:
g[group] = set()
g[group].add(name)
goes through a list of groups with this structure:
Group: A
Name: Bob
and adds to the set the names of persons belonging to a specific group. The names in the set are unique and we don't know how many similar names... | Count the multiple occurrences in a set | if group not in g:
g[group] = set()
g[group].add(name)
goes through a list of groups with this structure:
Group: A
Name: Bob
and adds to the set the names of persons belonging to a specific group. The names in the set are unique and we don't know how many similar names there are in a group. So e.g. if there are t... | [
"Looks like you might be better off with a Counter:\n>>> from collections import Counter\n>>> mylist = [\"Bob\", \"Mike\", \"Bob\", \"Mike\", \"Mike\", \"Mike\", \"Bob\"]\n>>> Counter(mylist)\nCounter({'Mike': 4, 'Bob': 3})\n\n",
"use a dict of dicts to count, e.g. as follows:\ntralala = dict()\n\nfor group, name... | [
50,
5
] | [
"\nfrom collections import Counter, defaultdict\nlst = [('B', 'Bob'), ('A', 'Andy'), ('C', 'Charles'), ('A', 'Adam'), ('B', 'Abraham')]\n# assumes people can appear in more than one group\ndef groups(lst):\n counter = Counter(lst)\n result = defaultdict(dict)\n for (group, name), value in counter.iteritems... | [
-3
] | [
"python"
] | stackoverflow_0004746812_python.txt |
Q:
Django DB best practices
I am building an online roleplaying game with Django. I am wondering what the best way to write the models in such a way as to not cause me pain in the future, Here is what I have so far:
class Equipment(models.Model):
head = models.ForeignKey("InvSlot",null=True,blank=True,related_nam... | Django DB best practices | I am building an online roleplaying game with Django. I am wondering what the best way to write the models in such a way as to not cause me pain in the future, Here is what I have so far:
class Equipment(models.Model):
head = models.ForeignKey("InvSlot",null=True,blank=True,related_name="head")
chest = models.F... | [
"You might want to look into a database migration tool like South. This will help keep down the pain of database updates later once app is deployed and a new version requires a change to the models.\n"
] | [
1
] | [] | [] | [
"database_design",
"django",
"python"
] | stackoverflow_0004720338_database_design_django_python.txt |
Q:
Is there anything static about python function / method invocations?
In asking a question about reflection I asked:
Nice answer. But there is a difference between saying myobject.foo() and x = getattr(myobject, "foo"); x();. Even if it is only cosmetic. In the first the foo() is compiled in statically. In the sec... | Is there anything static about python function / method invocations? | In asking a question about reflection I asked:
Nice answer. But there is a difference between saying myobject.foo() and x = getattr(myobject, "foo"); x();. Even if it is only cosmetic. In the first the foo() is compiled in statically. In the second, the string could be produced any number of ways. – Joe 1 hour ago
W... | [
"They're not entirely identical, but they are both dictionary lookups, as can be shown with the disassembler dis.dis.\nIn particular, note the LOAD_ATTR instruction with dynamically looks up the attribute by name. According to the docs, it \"replaces TOS [top of stack] with getattr(TOS, co_names[namei])\".\n>>> fro... | [
7,
3,
2,
1,
1
] | [] | [] | [
"binding",
"cpython",
"dynamic_binding",
"python"
] | stackoverflow_0004747093_binding_cpython_dynamic_binding_python.txt |
Q:
Cannot find svn-python Win32 installer since Tigris->Apache migration
I'm using the svn-python bindings (libsvn) to power Trac on Windows.
Previous to the Tigris->Apache migration of Subversion, I was able to download the Python bindings (svn-python-*.exe) here:
http://subversion.tigris.org/servlets/ProjectDocumen... | Cannot find svn-python Win32 installer since Tigris->Apache migration | I'm using the svn-python bindings (libsvn) to power Trac on Windows.
Previous to the Tigris->Apache migration of Subversion, I was able to download the Python bindings (svn-python-*.exe) here:
http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=11151&expandFolder=11151&folderID=260
What happened to those... | [
"I think they're maintained externally, like at http://sourceforge.net/projects/win32svn/files/1.6.15/.\nYup:\n\nThe Apache Subversion project does not\n officially endorse or maintain any\n binary packages of the Subversion\n software. However, volunteers have\n created binary packages for different\n distrib... | [
0,
0
] | [] | [] | [
"python",
"svn"
] | stackoverflow_0004706971_python_svn.txt |
Q:
Optimizing python code
Any tips on optimizing this python code for finding next palindrome:
Input number can be of 1000000 digits
COMMENTS ADDED
#! /usr/bin/python
def inc(lst,lng):#this function first extract the left half of the string then
#convert it to int then increment it then recon... | Optimizing python code | Any tips on optimizing this python code for finding next palindrome:
Input number can be of 1000000 digits
COMMENTS ADDED
#! /usr/bin/python
def inc(lst,lng):#this function first extract the left half of the string then
#convert it to int then increment it then reconvert it to string
... | [
"I think most of the time in this code is spent converting strings to integers and back. The rest is slicing strings and bouncing around in the Python interpreter. What can be done about these three things? There are a few unnecessary conversions in the code, which we can remove. I see no way to avoid the string sl... | [
2,
0,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004747666_optimization_python.txt |
Q:
I need help understanding some pythonic "dictify" / "jsonify" code fragments
I need help understanding this python jsonify/dictify code so I can replicate it:
TYPES = {}
# auto-register all already defined subclasses of CustomObject to the types map
# so they will become seriazible/deseriazible
for N,T in locals... | I need help understanding some pythonic "dictify" / "jsonify" code fragments | I need help understanding this python jsonify/dictify code so I can replicate it:
TYPES = {}
# auto-register all already defined subclasses of CustomObject to the types map
# so they will become seriazible/deseriazible
for N,T in locals().items():
if isinstance(T, type) and issubclass(T, CustomObject):
TY... | [
"The code that does the hard work is in the class itself. Lines 15 and 27 use the class functionality to convert the class from and to dicts, which are JSON-serializable; the rest is all administrivia code.\n"
] | [
1
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0004747931_dictionary_json_python.txt |
Q:
Python loop using the index number as part of a key name
I'm new to Python - getting my feet wet.
I want to create a loop that looks for ip addresses and uses the loop count as part of a key name.
i.e.
i = 0
while i < 5:
ip1= re.search(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\... | Python loop using the index number as part of a key name | I'm new to Python - getting my feet wet.
I want to create a loop that looks for ip addresses and uses the loop count as part of a key name.
i.e.
i = 0
while i < 5:
ip1= re.search(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}', commandslist)
if ip1:
myip1 = ip1.group()
... | [
"No loop is necessary, you can simply write:\nmyip = re.findall(r'(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:[.](?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}', commandslist)\n\n\nWhen you really need loops, avoid this:\ni = 0\nwhile i < 5:\n # do something with i\n i = i + 1\n\nand use this instead:\nfor i... | [
6,
2,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0004747846_loops_python.txt |
Q:
I've installed xapian via macports, so why does this python app tell me that xapian needs to be installed?
I'm trying to run a python application on my system. When I try to execute it I get a traceback which ends with something saying I need to install Xapian. So I went ahead an installed xapian-core and xapian-b... | I've installed xapian via macports, so why does this python app tell me that xapian needs to be installed? | I'm trying to run a python application on my system. When I try to execute it I get a traceback which ends with something saying I need to install Xapian. So I went ahead an installed xapian-core and xapian-bindings using macports. Then I tried to run the python application again, but got the same traceback. Any ideas ... | [
"The following worked for me after having the same issue on OS X 10.5:\n\nmake a macports selfupdate:\nsudo port selfupdate\ninstall python 2.6 over macports\nsudo port install python26\ninstall python_select\nsudo port install python_select\nselect python 2.6 as system default\nsudo python_select python26\ninstall... | [
2
] | [] | [] | [
"django_haystack",
"macos",
"python",
"xapian"
] | stackoverflow_0003057374_django_haystack_macos_python_xapian.txt |
Q:
python OOP, accessing attributes
Why do i get an "AttributeError: 'NewOne' object has no attribute 'self.b'" error message when i try to access the attribute 'self.b' from the NewOne class. I mean it's right there.
class NewOne(object):
def __init__(self):
self.b = 'Cat' # this is what i want to acc... | python OOP, accessing attributes | Why do i get an "AttributeError: 'NewOne' object has no attribute 'self.b'" error message when i try to access the attribute 'self.b' from the NewOne class. I mean it's right there.
class NewOne(object):
def __init__(self):
self.b = 'Cat' # this is what i want to access
def child(self):
self.... | [
"replace this:\nk = getattr(u, 'self.b')\n\nby this:\nk = getattr(u, 'b')\n\nor even better just do:\nk = u.b\n\n",
"Youe should write\nk = getattr(u, 'b')\n\nor better\nk = u.b\n\ninstead.\nThe name of the attribute is b, not self.b. And usually you access attributes via obj.attr -- the getattr() form is only n... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0004748486_python.txt |
Q:
By having a list with mazes houses(2 dimensions), how do i create a directed graph with a dictionary
I can only make an undirected graph. no idea on how i can make a directed one.
Any idea?
A:
Apologies for the rather long winded post. I had time to kill on the train.
I'm guessing what you're after is a directed... | By having a list with mazes houses(2 dimensions), how do i create a directed graph with a dictionary | I can only make an undirected graph. no idea on how i can make a directed one.
Any idea?
| [
"Apologies for the rather long winded post. I had time to kill on the train.\nI'm guessing what you're after is a directed graph representing all paths leading away from your starting position (as opposed to a graph representation of the maze which once can use to solve arbitrary start/end positions).\n(No offence ... | [
1,
0,
0
] | [] | [] | [
"directed_graph",
"graph",
"python"
] | stackoverflow_0004738092_directed_graph_graph_python.txt |
Q:
Python threading and GIL
I was reading about the GIL and it never really specified if this includes the main thread or not (i assume so). Reason I ask is because I have a program with threads setup that modify a dictionary. The main thread adds/deletes based on player input while a thread loops the data updating a... | Python threading and GIL | I was reading about the GIL and it never really specified if this includes the main thread or not (i assume so). Reason I ask is because I have a program with threads setup that modify a dictionary. The main thread adds/deletes based on player input while a thread loops the data updating and changing data.
However in ... | [
"They are running at the same time, they just don't execute at the same time. The iterations might be interleaved. Quote Python:\n\nThe mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time.\n\nSo two for loops might run at the same time, there will just be no (... | [
11,
6,
3,
1
] | [] | [] | [
"gil",
"locking",
"multithreading",
"python"
] | stackoverflow_0004748787_gil_locking_multithreading_python.txt |
Q:
python module giving boost::program_option like functionality
Is there any boost::program_options like module for python
A:
For command-line options, you can use argparse or (deprecated) optparse or (even older) getopt. For config files, there's ConfigParser.
| python module giving boost::program_option like functionality | Is there any boost::program_options like module for python
| [
"For command-line options, you can use argparse or (deprecated) optparse or (even older) getopt. For config files, there's ConfigParser.\n"
] | [
6
] | [] | [] | [
"boost_program_options",
"module",
"python"
] | stackoverflow_0004748931_boost_program_options_module_python.txt |
Q:
Any idea how this can be read as a CSV? - Python
I have a CSV formatted in the following way:
ID=123[DLE]KEY=test[DLE]KEY2=VAL123
where [DLE] is the "Data link escape" control character
Any idea how I could use this with the csv standard library?
Do I need to edit each row in order to make it compatible?
Edit: ... | Any idea how this can be read as a CSV? - Python | I have a CSV formatted in the following way:
ID=123[DLE]KEY=test[DLE]KEY2=VAL123
where [DLE] is the "Data link escape" control character
Any idea how I could use this with the csv standard library?
Do I need to edit each row in order to make it compatible?
Edit: my main problem is the "KEY=VALUE" formatting
Thanks g... | [
"Your data is not actually in CSV format, so I'd give up on trying to use it. What I'd do is write a generator that took each line, did .split('\\x10'), and then did .split('=', 1) on each piece, and then yielded the whole thing as a dict.\ndef dgen(fin):\n for line in fin:\n yield dict(((k, v) for chunk in lin... | [
5,
2,
0,
0,
0
] | [] | [] | [
"csv",
"excel",
"python",
"sqlite"
] | stackoverflow_0004748634_csv_excel_python_sqlite.txt |
Q:
Problem setting lattice plot options using rpy2
I'm trying to create a heatmap or color-intensity plot using data from a numpy array, using rpy2 and lattice. I'm using python 2.6.2, R 2.10.1, rpy2 2.1.9, not sure which version of lattice. I've gotten it working perfectly, except that I need to modify the default l... | Problem setting lattice plot options using rpy2 | I'm trying to create a heatmap or color-intensity plot using data from a numpy array, using rpy2 and lattice. I'm using python 2.6.2, R 2.10.1, rpy2 2.1.9, not sure which version of lattice. I've gotten it working perfectly, except that I need to modify the default lattice setting for the color ramp used to plot the le... | [
"You need to specify the argument mapping manually:\nfrom rpy2.robjects.functions import SignatureTranslatedFunction\nlattice = importr(\"lattice\")\nlattice.levelplot = SignatureTranslatedFunction(lattice.levelplot,\n init_prm_translate={'col_regions': 'col.regions'})... | [
4
] | [] | [] | [
"lattice",
"python",
"r",
"rpy2"
] | stackoverflow_0004748872_lattice_python_r_rpy2.txt |
Q:
Django: get table engine from model
I'm writing a unit test to make sure my legacy database tables are using InnoDB instead if MyISAM. Is there a way to get which engine a table is using through the model?
A:
No, the model has no idea. You'll need to query the database directly:
>>> from django.db import connect... | Django: get table engine from model | I'm writing a unit test to make sure my legacy database tables are using InnoDB instead if MyISAM. Is there a way to get which engine a table is using through the model?
| [
"No, the model has no idea. You'll need to query the database directly:\n>>> from django.db import connection\n>>> cursor = connection.cursor()\n>>> cursor.execute(\"SHOW TABLE STATUS WHERE name='appname_modelname'\")\n>>> print cursor.fetchone()\n\n('appname_modelname',\n u'InnoDB',\n 10L,\n u'Compact',\n 29L,\n 6... | [
4
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004748627_django_mysql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.