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:
Incorrect data_files location using distutils
The distutils documentation specifies that when the target directory for data_files is a relative path, the files will be installed relative to sys.prefix. On my system (Linux Mint), this is /usr; however, the data_files are instead installing to /usr/local.
How can I ... | Incorrect data_files location using distutils | The distutils documentation specifies that when the target directory for data_files is a relative path, the files will be installed relative to sys.prefix. On my system (Linux Mint), this is /usr; however, the data_files are instead installing to /usr/local.
How can I correct this without losing cross-platform support?... | [
"This is an Ubuntu / Linux mint related issue, they default to /usr/local instead of /usr.\n[1] http://ubuntuforums.org/showthread.php?t=1121501\n",
"Are you trying to 1) install someone else's program or 2) write a setup.py yourself?\nIf 1), are you appending --prefix=/usr/local when invoking python setup.py? If... | [
2,
0,
0
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0003306711_distutils_python.txt |
Q:
Check Idle Time when running as a Windows Service
Using win32api.GetLastInputInfo() is an easy way to determine a USERS's idle time. However when running as a SERVICE this does not apply (always returns 0).
Does anyone know a simple way for a WINDOWS SERVICE to determine last keypress/mouse activity? (or some oth... | Check Idle Time when running as a Windows Service | Using win32api.GetLastInputInfo() is an easy way to determine a USERS's idle time. However when running as a SERVICE this does not apply (always returns 0).
Does anyone know a simple way for a WINDOWS SERVICE to determine last keypress/mouse activity? (or some other effective way to determine idle time)
| [
"Not in Python, but the approach proposed in http://www.codeproject.com/KB/DLL/trackuseridle.aspx looks interesting. \n[edit]\nThe code it is a standard C DLL, so you should be able to use it with ctypes. The way the C code is written using SetWindowsHookEx means you could maybe rewrite it directly Python + pywin3... | [
1
] | [] | [] | [
"python",
"python_idle",
"winapi",
"windows_services"
] | stackoverflow_0008208816_python_python_idle_winapi_windows_services.txt |
Q:
Tools to extract glyph data from bitmap font image
I have all the characters of a font rendered in a PNG. I want to use the PNG for texture-mapped font rendering in OpenGL, but I need to extract the glyph information - character position and size, etc.
Are there any tools out there to assist in that process? Most ... | Tools to extract glyph data from bitmap font image | I have all the characters of a font rendered in a PNG. I want to use the PNG for texture-mapped font rendering in OpenGL, but I need to extract the glyph information - character position and size, etc.
Are there any tools out there to assist in that process? Most tools I see generate the image file and glyph data toget... | [
"Generally, the way this works is you use a tool to generate the glyph images. That tool will also generate metric information for those glyphs (how big they are, etc). You shouldn't be analyzing the image to find the glyphs; you should have additional information alongside your glyphs that tell where they are, how... | [
1,
0
] | [] | [] | [
"bitmap",
"fonts",
"gimp",
"opengl",
"python"
] | stackoverflow_0006481333_bitmap_fonts_gimp_opengl_python.txt |
Q:
Django & twill - session cookies not being set
I'm testing a django application with twill, and django-test-utils, and it's not logging me in.
I think it's not setting the django session cookie. I go to a webpage (in twill) that calls request.session.set_test_cookie(), and after that call returns, twill.show_cooki... | Django & twill - session cookies not being set | I'm testing a django application with twill, and django-test-utils, and it's not logging me in.
I think it's not setting the django session cookie. I go to a webpage (in twill) that calls request.session.set_test_cookie(), and after that call returns, twill.show_cookies() (which should print out the cookies), shows no ... | [
"As F.C. said, if the client and server are different machines with non-matching times (or even possibly timezones), you may end up with cookie expiration problems.\nI just double-checked the code for set_test_cookie(), and it looks like it sets that value pretty normally. Are you certain that the page you are havi... | [
0
] | [] | [] | [
"cookies",
"django",
"python",
"testing",
"twill"
] | stackoverflow_0005274938_cookies_django_python_testing_twill.txt |
Q:
Sending lots of data with pyportmidi stops working unless I add delay
I'm trying to talk to a Novation Launchpad with pyportmidi. I have noticed that if I just keep sending it instructions using midiOut.WriteShort() it will process the first 100 or so, then loose the rest.
I guess that there is a buffer somewhere ... | Sending lots of data with pyportmidi stops working unless I add delay | I'm trying to talk to a Novation Launchpad with pyportmidi. I have noticed that if I just keep sending it instructions using midiOut.WriteShort() it will process the first 100 or so, then loose the rest.
I guess that there is a buffer somewhere that is getting full, and once it's full, instructions are lost. I can work... | [
"When I took a look at the SVN repo, I ran across this in the wrapper code, note the 'Why is bufferSize 0 here?' comment..\ndef __init__(self, OutputDevice, latency=0):\n...stuff...\n # Why is bufferSize 0 here?\n err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency)\n\nThe API documentatio... | [
4
] | [] | [] | [
"midi",
"pyportmidi",
"python"
] | stackoverflow_0008198145_midi_pyportmidi_python.txt |
Q:
Python, easyGUI and sqlite3: Using python to read files in one folder or multiple folder, then adding the folder names and filenames to database
I am new in python and am trying to add folder names and text files in those folders to the database. The problem is that i don't know how to add the "textfiles" and "ope... | Python, easyGUI and sqlite3: Using python to read files in one folder or multiple folder, then adding the folder names and filenames to database | I am new in python and am trying to add folder names and text files in those folders to the database. The problem is that i don't know how to add the "textfiles" and "opendirectory" to the database. Please look at this code and help me. Thanks
#!/usr/bin/python
from easygui import *
import sys, glob, os, sqlite3
msg... | [
"Assuming that you want to add all the filenames to the database (without considering their relative path inside opendirectory), here is a way to correct your queries.\ncur.execute (\"INSERT INTO folder (foldername) VALUES (?);\", (opendirectory))\ncur.execute(\"INSERT INTO file (dataname) VALUES(?);\", (textfiles)... | [
2
] | [] | [] | [
"easygui",
"python",
"sqlite"
] | stackoverflow_0008208275_easygui_python_sqlite.txt |
Q:
Python : Singleton class object to persist list between imports ? (Like django admin register)
I want to have dict / list to which I can add values, just like models can be added to the admin register in django !
My attempt : (package -> __init__.py)
# Singleton object
# __init__.py (Package: pack)
class remember... | Python : Singleton class object to persist list between imports ? (Like django admin register) | I want to have dict / list to which I can add values, just like models can be added to the admin register in django !
My attempt : (package -> __init__.py)
# Singleton object
# __init__.py (Package: pack)
class remember:
a = []
def add(data):
a.append[data]
def get():
return a
obj = remember()
# mode... | [
"If it's a singleton you're after, have a look at this old blog post. It contains a link to a well documented implementation (here).\n"
] | [
0
] | [
"\nDon't. If you think you need a global you don't and you should reevaluate how you are approaching the problem because 99% of the time you're doing it wrong. \nIf you have a really good reason to do it perhaps thread_locals() will really solve the problem you're trying to solve. This allows you to set up threa... | [
-1
] | [
"django",
"function",
"methods",
"python",
"singleton"
] | stackoverflow_0008207100_django_function_methods_python_singleton.txt |
Q:
Python database Session (meta.Session)
I have a ton of code that is editing a database, but what I want to do is load all of the data I need to edit or add into a session, return a webpage and once the user has looked over the data, then commit to the database. Something like this:
def index(self):
empsTbl = m... | Python database Session (meta.Session) | I have a ton of code that is editing a database, but what I want to do is load all of the data I need to edit or add into a session, return a webpage and once the user has looked over the data, then commit to the database. Something like this:
def index(self):
empsTbl = meta.Session.query(model.Person).all();
n... | [
"i hope it isn't so, but it seems that you not yet understand the lifecycles in what your web-app lives.\nin your case you have 2 lifecycles, because you have 2 actions. 2 request/response-scenarios. you have to understand, that (mostly) all the stuff you do in an action, it stays in there.\nyour database-session o... | [
1
] | [] | [] | [
"pylons",
"python",
"session",
"sqlalchemy"
] | stackoverflow_0008186282_pylons_python_session_sqlalchemy.txt |
Q:
Regex how to use 'or' for string matching
I want to parse a web page and find specific patterns using regex on Python.
My Example page have:
<input type="checkbox" name="some name....">
<input type="text", name="somemore name...">
<input type="radio" name="other name...">
And i want to find all matcihng name valu... | Regex how to use 'or' for string matching | I want to parse a web page and find specific patterns using regex on Python.
My Example page have:
<input type="checkbox" name="some name....">
<input type="text", name="somemore name...">
<input type="radio" name="other name...">
And i want to find all matcihng name values of radio and checkbox inputs.
<input type="c... | [
"<input type=\"(checkbox|radio)\" name=\"(?P<name>.*?)\".*?>\n\nI've also put a capture group name in there for ease of extraction.\nBut the old rule applies, don't use regex for parsing html. It's very fragile. What if the code you are parsing changed to be <input class=\"aha\" type=\"checkbox\" name=\"some name..... | [
4,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008210314_python_regex.txt |
Q:
Points left out when nearby in scipy.spatial.Delaunay
I am noticing an unexplained behaviour when comparing scipy's (0.9.0) and matplotlib's (1.0.1) Delaunay triangulation routines. My points are UTM coordinates stored in numpy.array([[easting, northing], [easting, northing], [easting, northing]]). Scipy's edges a... | Points left out when nearby in scipy.spatial.Delaunay | I am noticing an unexplained behaviour when comparing scipy's (0.9.0) and matplotlib's (1.0.1) Delaunay triangulation routines. My points are UTM coordinates stored in numpy.array([[easting, northing], [easting, northing], [easting, northing]]). Scipy's edges are missing some of my points, while matplotlib's are all th... | [
"This behavior of scipy.spatial.Delaunay might be connected with the impresicion of the floating point arithmetic. \nAs you may know, scipy.spatial.Delaunay uses C qhull library to calculate Delaunay triangulation. Qhull, in its turn, is the implementation of Quickhull algorithm, which is in details described by th... | [
6
] | [] | [] | [
"delaunay",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0008071382_delaunay_matplotlib_numpy_python_scipy.txt |
Q:
Handle sys.exit() in cherrypy service
When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a sys.exit() call (from my error handler), cherrypy quits, but the service remains hanging.
Code:
import cherrypy
import win32serviceutil
import win32service
import sys
SERVICE =... | Handle sys.exit() in cherrypy service | When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a sys.exit() call (from my error handler), cherrypy quits, but the service remains hanging.
Code:
import cherrypy
import win32serviceutil
import win32service
import sys
SERVICE = None
class HelloWorld:
""" Sample req... | [
"I'm not entirely sure where the sys.exit call is coming from or what your preferred behavior is. When sys.exit is called, however, it raises a SystemExit exception. You can intercept this and continue on your way:\nimport sys\ntry:\n sys.exit()\nexcept SystemExit:\n print \"Somebody called sys.exit().\"\npri... | [
2,
1
] | [] | [] | [
"cherrypy",
"python",
"windows_services"
] | stackoverflow_0001002072_cherrypy_python_windows_services.txt |
Q:
How can I get send() to block with UDP?
I am writing a simple UDP-based client/server app and testing with both the client/server on localhost, and I would like for the sender to know when send() would have blocked. I am using Python, so I think I can do:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.set... | How can I get send() to block with UDP? | I am writing a simple UDP-based client/server app and testing with both the client/server on localhost, and I would like for the sender to know when send() would have blocked. I am using Python, so I think I can do:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(0)
s.connect(('127.0.0.1', 12345))
d... | [
"UDP doesn't normally block. If the receiver has a full buffer, the packet gets silently discarded. This is by design. If you want reliable transport and blocking semantics, use TCP instead.\nComment: The reason TCP blocks is because the sender gets confirmation for every packet it sends. The sender only allows... | [
5
] | [] | [] | [
"networking",
"python",
"sockets"
] | stackoverflow_0008210320_networking_python_sockets.txt |
Q:
print formatting in python
I have a question: How can I print a character on a specific stdout column?
I know that:
print '{0} and {1}'.format('spam', 'eggs')
prints spam on the first column and eggs on the second one.
But I want to do this:
column = 3
...
print '{column}'.format('spam')
cheers.
A:
You have tw... | print formatting in python | I have a question: How can I print a character on a specific stdout column?
I know that:
print '{0} and {1}'.format('spam', 'eggs')
prints spam on the first column and eggs on the second one.
But I want to do this:
column = 3
...
print '{column}'.format('spam')
cheers.
| [
"You have two options to do it.\nFirst option - pass it in parameter:\n>>> print '{column}'.format(column='spam')\nspam\n\nSecond option - unpack a dictionary (using **):\n>>> print '{column}'.format(**{'column':'spam'})\nspam\n\n",
"You can do something like this but it's quite ugly.\ncolumn = 3\nmessage = '{'+s... | [
4,
0
] | [] | [] | [
"format",
"pretty_print",
"python"
] | stackoverflow_0008210800_format_pretty_print_python.txt |
Q:
Copying over the fields from a ModelForm into a Form
I have a dummy Form that looks like:
class MyForm(forms.Form):
class __init__(self, *args, **kwargs):
pass
Here's are the ModelForms and their respective Models:
class Person(models.Model):
fname = models.CharField(max_length = 255)
lname =... | Copying over the fields from a ModelForm into a Form | I have a dummy Form that looks like:
class MyForm(forms.Form):
class __init__(self, *args, **kwargs):
pass
Here's are the ModelForms and their respective Models:
class Person(models.Model):
fname = models.CharField(max_length = 255)
lname = models.CharField(max_length = 255)
class Address(models.... | [
"Just adding a field is not correct, considering the models above.\nAddress has a ManyToOne relation to Person - A user can have multiple addresses. In that case better take a look at django's inline form sets:\nhttps://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view\nCumber... | [
2,
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0008208699_django_django_forms_django_models_python.txt |
Q:
Using lettuce, how can I verify that an email sent from a Django web application has the correct contents?
I have a Django-based web application that is required to send a confirmation email to the user on an attempt to change the registered email address. The functionality has been implemented, but the lettuce te... | Using lettuce, how can I verify that an email sent from a Django web application has the correct contents? | I have a Django-based web application that is required to send a confirmation email to the user on an attempt to change the registered email address. The functionality has been implemented, but the lettuce test intended to verify the contents of the email is failing.
To verify the operation, my plan was to use the file... | [
"You can use django.core.mail.outbox as described in django docs https://docs.djangoproject.com/en/dev/topics/testing/#email-services\nfrom django.core import mail\n\nassert len(mail.outbox) == 1\nassert mail.outbox[0].subject == 'Subject here'\n\nLettuse uses django.test.utils.setup_test_environment that overrides... | [
4
] | [] | [] | [
"django",
"lettuce",
"python"
] | stackoverflow_0007795529_django_lettuce_python.txt |
Q:
Decide if direct children of element are certain tags
Is there a way to write this in BeautifulSoup?
for node in soup:
if node is in ["a", "b", "i", ...]: # node is tag of type `a` or `b` ...
# we are probably on the text level
textLevelFlag = true
else:
# "we are higher"
A:
If you want to test i... | Decide if direct children of element are certain tags | Is there a way to write this in BeautifulSoup?
for node in soup:
if node is in ["a", "b", "i", ...]: # node is tag of type `a` or `b` ...
# we are probably on the text level
textLevelFlag = true
else:
# "we are higher"
| [
"If you want to test if your tag has only text elements you can try this:\nif hasattr(node, contents) and len(node.contents) == 1 and isinstance(node.contents[0], NavigableString):\n textLevelFlag = true\nelse:\n something else\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0008204349_beautifulsoup_html_parsing_python.txt |
Q:
Cassandra and Django
I'd like to use Cassandra from within django, and after some research I've noticed that there are some libraries that enable you to access cassandra from a higher level than pycassa does: For django there's alexandra & django-cassandra-backed, for plain python you'll find tragedy & lazyboy...
... | Cassandra and Django | I'd like to use Cassandra from within django, and after some research I've noticed that there are some libraries that enable you to access cassandra from a higher level than pycassa does: For django there's alexandra & django-cassandra-backed, for plain python you'll find tragedy & lazyboy...
I know there's a similar q... | [
"https://github.com/twissandra/twissandra is using Apache Cassandra and Django.\nIt's also a good entry point if you are curios about the Cassandra data model\n"
] | [
2
] | [] | [] | [
"cassandra",
"django",
"python"
] | stackoverflow_0008210469_cassandra_django_python.txt |
Q:
ImportError: No module named numeric
I get the following error
ImportError: No module named numeric if I have the following import
from numeric import *
in my python source code. How do I get this running on my Windows box against a python 2.7.x compiler?
A:
There is a module called numeric, but it's been de... | ImportError: No module named numeric | I get the following error
ImportError: No module named numeric if I have the following import
from numeric import *
in my python source code. How do I get this running on my Windows box against a python 2.7.x compiler?
| [
"There is a module called numeric, but it's been deprecated for years in favour of numpy. You probably want to update your code to use numpy instead.\nIf you really need numeric, you can get it here, but you'll have to compile it from source for Python 2.7, because the latest binaries are for 2.4.\n",
"You will p... | [
7,
2,
2
] | [] | [] | [
"importerror",
"python",
"python_import"
] | stackoverflow_0008210344_importerror_python_python_import.txt |
Q:
Python naming conventions for functions that do modify the object or return a modified copy
What would be the naming conventions in Python for functions that can return a modified object or that just modifies the instance.
Let's assume you want to implement both, how you should name the functions?
Example: Let's a... | Python naming conventions for functions that do modify the object or return a modified copy | What would be the naming conventions in Python for functions that can return a modified object or that just modifies the instance.
Let's assume you want to implement both, how you should name the functions?
Example: Let's assume that you want a crop() function for an Image object. I Ruby it was simple because you shoul... | [
"Not sure if there is a precise guideline in some PEP, but looking at how certain functions/method work in python core I personally use verb conjugation. For example, inspired by:\n>>> l = list('hello world')\n>>> l\n['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']\n>>> sorted(l)\n[' ', 'd', 'e', 'h', 'l', '... | [
5,
2,
1,
0
] | [] | [] | [
"command_query_separation",
"naming_conventions",
"python"
] | stackoverflow_0008211890_command_query_separation_naming_conventions_python.txt |
Q:
Python list value intersection
I have a list of uneven lengths of values now I want to convert them to a list from 1 to 100.
Thus if a list has 100 values then at location 10 will be list[10]
Now when I have a list of 248 values I want to make a line graph of this and have the x-axis ranging from 1-100% so I can a... | Python list value intersection | I have a list of uneven lengths of values now I want to convert them to a list from 1 to 100.
Thus if a list has 100 values then at location 10 will be list[10]
Now when I have a list of 248 values I want to make a line graph of this and have the x-axis ranging from 1-100% so I can ask/intersect what the value is at lo... | [
"Easy! Just use numpy.linspace to generate the x-locations at which to plot the values:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvals=np.random.random(248)\nx=np.linspace(1,100,len(vals))\n\nplt.plot(x,vals)\nplt.show()\n\n\nTo subsample your list of values, you could use numpy \"advanced\" indexing:... | [
2,
0
] | [] | [] | [
"graph",
"list",
"python"
] | stackoverflow_0008211193_graph_list_python.txt |
Q:
The installation of Python and Selenium is not working
I am using:
Python 2.5
OS: Windows Vista
There was an error when I tried to install Selenium 2.13 using
pip install -U Selenium
Output:
Downloading/unpacking Selenium
Downloading selenium-2.13.1.tar.gz (3.3Mb): 3.3Mb downloaded
Running setup.py egg_info for... | The installation of Python and Selenium is not working | I am using:
Python 2.5
OS: Windows Vista
There was an error when I tried to install Selenium 2.13 using
pip install -U Selenium
Output:
Downloading/unpacking Selenium
Downloading selenium-2.13.1.tar.gz (3.3Mb): 3.3Mb downloaded
Running setup.py egg_info for package Selenium
warning: no files found matching 'docs\api... | [
"That installation manual seems a bit awkward to me. First, remove all files (try pip uninstall Selenium, or if that doesn't work just remove the selenium folder from your site-packages folder). Also, delete the single selenium.py file you copied.\nThen, try again by running pip install -U selenium. If you can then... | [
3,
3
] | [] | [] | [
"python",
"selenium_webdriver"
] | stackoverflow_0008210736_python_selenium_webdriver.txt |
Q:
Float arithmetics
Im writing a program which uses simple neural network perception algorithm, I have problem with doing negative float arithmetic, when I do this
summ = x1*w1+x2*w2-t
summ gets the value of -2.77555756156e-17
this happens only when
x1 = 1.0
w1 = 0.2
x2 = 0.0
w2 = 0.1
t=0.2
If i do this in the py... | Float arithmetics | Im writing a program which uses simple neural network perception algorithm, I have problem with doing negative float arithmetic, when I do this
summ = x1*w1+x2*w2-t
summ gets the value of -2.77555756156e-17
this happens only when
x1 = 1.0
w1 = 0.2
x2 = 0.0
w2 = 0.1
t=0.2
If i do this in the python console everything... | [
"From The Floating-Point Guide:\n\nWhy don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and\n instead I get a weird result like 0.30000000000000004?\nBecause internally, computers use a format (binary floating-point)\n that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.\nWhen the co... | [
3,
3,
2
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0008212237_floating_point_python.txt |
Q:
Can a Django View delegate to a function who returns a response object?
def process_event(request, eventID, eventData):
return HttpResponse("process event!")
@csrf_exempt
@slip_protect
def catch_event(request,eventID):
if request.POST:
process_event(request,eventID, request.... | Can a Django View delegate to a function who returns a response object? | def process_event(request, eventID, eventData):
return HttpResponse("process event!")
@csrf_exempt
@slip_protect
def catch_event(request,eventID):
if request.POST:
process_event(request,eventID, request.POST['eventData'])
return HttpResponse("safe return!")
That code ret... | [
"i guess you want return process_event(), so that your view returns whatever it gets back\nas it currently reads, your view executes process_event but throws away the returned HttpResponse\n"
] | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008212307_django_python.txt |
Q:
How to prepare text data for orange SVM train?
I used NLTK classifiers 2 years ago. Now I want to learn to use orange SVM for text classification. The example for SVM in orange tutorial is iris.tab:
sepal length sepal width petal length petal width iris
c c c c d
class
5.1 3.5 1.4 0.... | How to prepare text data for orange SVM train? | I used NLTK classifiers 2 years ago. Now I want to learn to use orange SVM for text classification. The example for SVM in orange tutorial is iris.tab:
sepal length sepal width petal length petal width iris
c c c c d
class
5.1 3.5 1.4 0.2 Iris-setosa
4.9 3.0 1.4 0.2 Iris-setosa
If I want... | [
"Short answer: No.\nLong answer: The label refers to the category of documents you want to process. For example if you are trying to categorize documents into two categories, such as SPAM and HAM, then the labels should be SPAM and HAM. For data representation you may use tecnhiques such as Bag of Words (http://en.... | [
1
] | [] | [] | [
"nlp",
"orange",
"python",
"svm"
] | stackoverflow_0008168858_nlp_orange_python_svm.txt |
Q:
Django non-rel createsuperuser fails due to non-ascii characters
I am tring to create a new superuser on my django app engine project, In order to gain access to the built in admin functions. Every time
when I run
python manage.py createsuperuser
I get an error saying " "'NoneType' object has no attribute 'mk... | Django non-rel createsuperuser fails due to non-ascii characters | I am tring to create a new superuser on my django app engine project, In order to gain access to the built in admin functions. Every time
when I run
python manage.py createsuperuser
I get an error saying " "'NoneType' object has no attribute 'mkstemp'" "
I tried to reinstall django python and the app engine sdk, w... | [
"Since you haven't passed any arguments to it, createsuperuser.py uses the Python getpass module to get a default user name. (Line 59, createsuperuser.py):\n # Try to determine the current system user's username to use as a default.\n try:\n default_username = getpass.getuser().replace(' ', '').low... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0008210653_django_django_admin_django_nonrel_google_app_engine_python.txt |
Q:
Python search and replace in StringIO buffer?
I'm using telnetlib to get a few lines of text (tn = telnetlib).
o = cStringIO.StringIO(tn.read_all())
# this prints the entire text as it should (a few lines)
print o.getvalue()
o.close()
Now, is there a way to search based on a string and replace an entire line in ... | Python search and replace in StringIO buffer? | I'm using telnetlib to get a few lines of text (tn = telnetlib).
o = cStringIO.StringIO(tn.read_all())
# this prints the entire text as it should (a few lines)
print o.getvalue()
o.close()
Now, is there a way to search based on a string and replace an entire line in the cStringIO buffer if the string is found?
I did ... | [
"Do the search and replace on the string, then put the result into the StringIO buffer if you need:\nlines = tn.read_all().splitlines()\nfor i, line in enumerate(lines):\n if search_string in line:\n lines[i] = replacement_string\no = cStringIO.StringIO(\"\\n\".join(lines))\n\n",
"small variant on @Sven... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008212670_python.txt |
Q:
error with curses tigetstr in Python 2.6.6
After I upgraded Ubuntu my Python was changed to 2.6.6 and my app.py stopped working
when calling
sys.stdout.write(curses.tigetstr('civis'))
it writes:
Traceback (most recent call last):
File "app.py", line 60, in <module>
sys.stdout.write(curses.tigetstr('civis'))
... | error with curses tigetstr in Python 2.6.6 | After I upgraded Ubuntu my Python was changed to 2.6.6 and my app.py stopped working
when calling
sys.stdout.write(curses.tigetstr('civis'))
it writes:
Traceback (most recent call last):
File "app.py", line 60, in <module>
sys.stdout.write(curses.tigetstr('civis'))
TypeError: argument 1 must be string or read-onl... | [
"Reading the documentation:\n\ncurses.tigetstr(capname)\nReturn the value of the string capability corresponding to the terminfo capability name capname. None is\nreturned if capname is not a string capability, or is canceled or\nabsent from the terminal description.\n\nI take it the problem might be with the termi... | [
2
] | [] | [] | [
"curses",
"ncurses",
"python"
] | stackoverflow_0008213142_curses_ncurses_python.txt |
Q:
wxPython StopWatch constant display of counting time?
I'm trying to create a GUI timer using wxPython. A Start button is clicked, the timer starts and a label displays the timer counting the seconds up to minutes and maybe to hours. A Stop button stops the timer. I don't know how to have the timer constantly di... | wxPython StopWatch constant display of counting time? | I'm trying to create a GUI timer using wxPython. A Start button is clicked, the timer starts and a label displays the timer counting the seconds up to minutes and maybe to hours. A Stop button stops the timer. I don't know how to have the timer constantly displayed in the label. I tried a while True loop but it see... | [
"You never return from OnStart, so the event loop is hung waiting for the event handler to finish. All event handlers need to return immediately so that other events can be processed. Use a wx.Timer handler to update the stopwatch label.\n",
"It sounds like you want to start from 00:00:00 and count up, right? ... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008198906_python_wxpython.txt |
Q:
Set default value for xsd:element in the xsd file
I'm useing generation data structures from XML Schema. There is a part of xsd file, which descibe TCPInterface class:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsd:schema targetNamespace="tcpinterface_xsd.xsd"
xmlns:cext="tcpinterface_xsd.xsd"
... | Set default value for xsd:element in the xsd file | I'm useing generation data structures from XML Schema. There is a part of xsd file, which descibe TCPInterface class:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsd:schema targetNamespace="tcpinterface_xsd.xsd"
xmlns:cext="tcpinterface_xsd.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
... | [
"Just add the attribute default=\"{yourInteger}\" to the element. See an example below :\n <xsd:element name=\"port\" type=\"xsd:integer\" default=\"2\"/>\n\nNote that, in this case, if your port element is empty before validation, the XML Infoset change after validation and become the post schema validation inf... | [
3,
2
] | [] | [] | [
"python",
"xsd"
] | stackoverflow_0008213394_python_xsd.txt |
Q:
changing the contents of a file applying different conditions
I am trying to do some changes in the contents of an input file. The input file I have looks like the following:
18800000 20400000 pau
20400000 21300000 aa
21300000 22500000 p
22500000 23200000 l
23200000 24000000 ay
24000000 25000000 k
25000000 2650000... | changing the contents of a file applying different conditions | I am trying to do some changes in the contents of an input file. The input file I have looks like the following:
18800000 20400000 pau
20400000 21300000 aa
21300000 22500000 p
22500000 23200000 l
23200000 24000000 ay
24000000 25000000 k
25000000 26500000 pau
This file is a transcription of an audio file. The first num... | [
"Editing a text file in-place is pretty hard. Your best options are:\n\nWrite the program as a Unix filter, i.e. produce the new file on sys.stdout and put it in place with external tools\nRead in the whole file, then construct the new file in memory and write it out.\n\nA program following the second line of thoug... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008211737_python.txt |
Q:
Library to Tidy Up Python Code using pep8 conventions
Is there any library that takes in your python file as input and does tidy-up (modifies it based on the PEP 8 conventions).
To understand what I am talking about, a JavaScript analogy is as follows:
Go to this link
Press the button TidyUp
Any online editor or... | Library to Tidy Up Python Code using pep8 conventions | Is there any library that takes in your python file as input and does tidy-up (modifies it based on the PEP 8 conventions).
To understand what I am talking about, a JavaScript analogy is as follows:
Go to this link
Press the button TidyUp
Any online editor or library or script would be appreciated.
| [
"You can take a look to PythonTidy which is officially working till python2.5 (and seems to be supported in python2.6) : \n\nCleans up, regularizes, and reformats the text of Python scripts.\nThis script reads Python code from standard input and writes a revised\n version to standard output.\n\n",
"pep8.py gives... | [
2,
1
] | [] | [] | [
"code_formatting",
"pep8",
"python"
] | stackoverflow_0008213845_code_formatting_pep8_python.txt |
Q:
Trouble creating a model and it's children from an inlineformset_factory
I have a model for file uploads defined like this:
class UploadedFile(models.Model):
fpath = models.FileField(...)
sig = models.CharField(max_length=32) # for md5 of data, computed with post_save
and I have another model, named MTest... | Trouble creating a model and it's children from an inlineformset_factory | I have a model for file uploads defined like this:
class UploadedFile(models.Model):
fpath = models.FileField(...)
sig = models.CharField(max_length=32) # for md5 of data, computed with post_save
and I have another model, named MTest, that has this:
class MTest(models.Model):
file1 = models.ForeignKey("Uploa... | [
"Your approach here isn't quite right. The inline formset is a pattern to \"edit multiple MTests linked to the same UploadedFile\".\nI would create a model forms for UploadedFile and Mtest. Exclude the file1 and file2 fields from the MtestModelForm. Put two uploaded file forms and the MtestModelForm in the same htm... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008213261_django_python.txt |
Q:
generating a mel script
Following the question I had asked yesterday which is here passing contents from multiple lists generated in different functions to a file I have written the code. Part of the code is below,
def lower_lip_under_upper_teeth_bezier(x_n, p0, p3) :
""" Calculating sampling points using rati... | generating a mel script | Following the question I had asked yesterday which is here passing contents from multiple lists generated in different functions to a file I have written the code. Part of the code is below,
def lower_lip_under_upper_teeth_bezier(x_n, p0, p3) :
""" Calculating sampling points using rational bezier curve equation"""... | [
"You are not calling the function. To call it, use\nlower_lip_under_upper_teeth_bezier(x_n, p0, p3)\n\nand substitute appropriate values for the parameters.\n",
"lower_lip_under_upper_teeth_bezier is a function. The error message clearly tells it, there is no way around it.\nYou might believe that lower_lip_unde... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0008214006_python.txt |
Q:
Unable to do client-server communication via sockets in Python
I have been banging my head against a socket issue for the last two weeks to no avail. I have a setup of 12 'client' machines and one server machine. The server is given a large task, splits it into 12 smaller tasks and then distributes them to the 12 ... | Unable to do client-server communication via sockets in Python | I have been banging my head against a socket issue for the last two weeks to no avail. I have a setup of 12 'client' machines and one server machine. The server is given a large task, splits it into 12 smaller tasks and then distributes them to the 12 clients. The clients churn away and once they finish their task, the... | [
"Alright, this took me a while but I think I figured out what was causing this:\n\nglglgl's answer is correct - using 'localhost' causes the machine to\nonly listen to itself and not to other machines on the network. This\nwas the main culprit.\nIncreasing the number allowed in the que from 0 to 5 reduced the\nlike... | [
3,
2,
2,
0,
0
] | [] | [] | [
"client_server",
"python",
"sockets"
] | stackoverflow_0008184208_client_server_python_sockets.txt |
Q:
Delete sublist from a list
I want to delete a sublist from a list. I only know the starting index and the ending index. how can I delete from the list?
I'm using the following code:
def delete_sub_list( self, cmd_list, start, end ):
tmp_lst = []
for i in range( len( cmd_list ) ):
if( i ... | Delete sublist from a list | I want to delete a sublist from a list. I only know the starting index and the ending index. how can I delete from the list?
I'm using the following code:
def delete_sub_list( self, cmd_list, start, end ):
tmp_lst = []
for i in range( len( cmd_list ) ):
if( i < start or i > end ):
... | [
"The Python syntax to do this is\ndel cmd_list[4:14 + 1]\n\n(The + 1 is necessary to match your code. Python uses half-open intervals, i.e. the first index is included in the slice, but the last isn't.)\n",
"You can use either:\ncmd_list[start:end + 1] = []\n\nor\ndel cmd_list[start:end + 1]\n\n",
"Might be ea... | [
7,
4,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008213090_list_python.txt |
Q:
Query Events from Multiple Google Calendars in Single Batch
Is there a way to query for events in multiple calendars (in the same Google account) in a single batch request?
I've been through the Google documentation here, but it hasn't really helped.
What I'm trying to do really is scan through a given user's cale... | Query Events from Multiple Google Calendars in Single Batch | Is there a way to query for events in multiple calendars (in the same Google account) in a single batch request?
I've been through the Google documentation here, but it hasn't really helped.
What I'm trying to do really is scan through a given user's calendars and get a list of events for each one.
An example in python... | [
"Short answer: No\nLong answer: The API does not allow you to fetch more than one calendar with a single request and it doesn't allow you to manipulate more than one calendar in a single request.\nIf this is really important to you (you're trying to reduce requests so I guess it's about performance), you could poss... | [
3
] | [] | [] | [
"gdata",
"gdata_api",
"google_calendar_api",
"python"
] | stackoverflow_0007986772_gdata_gdata_api_google_calendar_api_python.txt |
Q:
Query python gdata Calendar API by extended properties
Using the Python GData Calendar API, is there a way to search/query for events with specific extended properties?
Ie, my program is creating calendar events and setting an extended property ProgramID='xxxxx'. In a later period, I'd like to find all of the eve... | Query python gdata Calendar API by extended properties | Using the Python GData Calendar API, is there a way to search/query for events with specific extended properties?
Ie, my program is creating calendar events and setting an extended property ProgramID='xxxxx'. In a later period, I'd like to find all of the events where extended_property.ProgramID=='xxxx'
I'm currently ... | [
"At this moment you can not query by extended properties.\nDepending on how much control you have over the application and the calendars you can work around this by placing some sort of meta-data on the description field, querying for that and then filtering the results (as you're currently doing) via the extended ... | [
0
] | [] | [] | [
"gdata",
"gdata_api",
"google_calendar_api",
"python"
] | stackoverflow_0007957743_gdata_gdata_api_google_calendar_api_python.txt |
Q:
writing a line seperated by spaces to a csv file all elements in a different block
I have a tuple in which one element is just a string and the other is a list ('x',['y','z']), I want to output the tuple into a csv file with all of the different elements on the same row, but different blocks.
Here is what I have s... | writing a line seperated by spaces to a csv file all elements in a different block | I have a tuple in which one element is just a string and the other is a list ('x',['y','z']), I want to output the tuple into a csv file with all of the different elements on the same row, but different blocks.
Here is what I have so far
outputwriter=csv.writer(open('output.csv','wb'), delimiter=' ')
for tup in in_t... | [
"outputwriter = csv.writer(open('output.csv', 'w'), delimiter = ' ')\nfor tup in in_tup:\n inputList = [tup[0]]\n inputList.extend(tup[1])\n outputwriter.writerow(inputList)\n\n",
"This behavior is correct: You are adding just a single element to each row (which is a long string created by joining all th... | [
2,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008214563_csv_python.txt |
Q:
How is calling module and function by string handled in python?
Calling a function of a module from a string with the function's name in Python shows us how to call a function by using getattr("bar")(), but this assumes that we have the module foo imported already.
How would would we then go about calling for the ... | How is calling module and function by string handled in python? | Calling a function of a module from a string with the function's name in Python shows us how to call a function by using getattr("bar")(), but this assumes that we have the module foo imported already.
How would would we then go about calling for the execution of "foo.bar" assuming that we probably also have to perform... | [
"Use the __import__(....) function:\nhttp://docs.python.org/library/functions.html#import\n(David almost had it, but I think his example is more appropriate for what to do if you want to redefine the normal import process - to e.g. load from a zip file)\n",
"You can use find_module and load_module from the imp mo... | [
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006643324_python.txt |
Q:
javascript drop down menu with selenium 2
I've been trying for about a week to figure out a drop down menu using selenium 2. It's a project I am working on to automate a flight search using ITA Matrix 2 (http://matrix.itasoftware.com/). Everything works OK except selecting the number of passengers from the drop ... | javascript drop down menu with selenium 2 | I've been trying for about a week to figure out a drop down menu using selenium 2. It's a project I am working on to automate a flight search using ITA Matrix 2 (http://matrix.itasoftware.com/). Everything works OK except selecting the number of passengers from the drop down menu. Clicking on it works fine, but atte... | [
"In this case, it fails because the passenger drop down menu is not actually a drop down menu, it's some clever html and javascript so it won't respond to the usual events as expected.\nTry this:\nClick on the list at ID: \nita_form_pax_Passenger_0\n\nThen click the menu item at XPath (replace 'NUMBER_OF_PASSENGERS... | [
2
] | [] | [] | [
"drop_down_menu",
"javascript",
"python",
"selenium",
"webdriver"
] | stackoverflow_0008022156_drop_down_menu_javascript_python_selenium_webdriver.txt |
Q:
Python: access list value by reference
Very basic question here (I've just started with Python).
I have a list object. It contains five numbers [3,6,2,3,1]
I want find the sum of the first, third and fourth numbers in the list.
What is the syntax?
A:
You can for instance sum elements #1, #3, and #4 with the flex... | Python: access list value by reference | Very basic question here (I've just started with Python).
I have a list object. It contains five numbers [3,6,2,3,1]
I want find the sum of the first, third and fourth numbers in the list.
What is the syntax?
| [
"You can for instance sum elements #1, #3, and #4 with the flexible expression\nsum(my_list[i] for i in (0, 2, 3))\n\nThe index of the first element is 0 [not 1], etc., i.e. my_list[0] is the first element (with value 3, in the original question), etc.\n",
"The items of a list are numbered like this:\n a = [3, ... | [
7,
6,
3,
1
] | [] | [] | [
"list",
"python",
"syntax"
] | stackoverflow_0008215366_list_python_syntax.txt |
Q:
Reading Excel xml to dictionary
I want to read simple excel xml file to dictionary. I have tried to use xlrd 7.1 but it returns format errors. Now i'm trying to use xml.etree.ElementTree and also without success. I can't change structure of .xml file. Here my code:
<?xml version="1.0" encoding="UTF-8"?>
-<Workbook... | Reading Excel xml to dictionary | I want to read simple excel xml file to dictionary. I have tried to use xlrd 7.1 but it returns format errors. Now i'm trying to use xml.etree.ElementTree and also without success. I can't change structure of .xml file. Here my code:
<?xml version="1.0" encoding="UTF-8"?>
-<Workbook xmlns="urn:schemas-microsoft-com:off... | [
"Exclude \"junk\" with an if-statement:\ndef xml_to_list(fname):\n with open(fname) as xml_file:\n tree = etree.iterparse(xml_file)\n for item in tree:\n if item[1].text.strip() != '-':\n print item[1].text\n\n"
] | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0008214511_python_xml.txt |
Q:
Floating point accuracy in python
Any reason why c shouldn't equal 0.321?
>>> from math import ceil
>>> a = 123.321
>>> b = a % 60
>>> b
3.320999999999998
>>> ceil(b)
4.0
>>> c = ceil(b) - b
>>> c
0.679000000000002
Update:
For anyone wanting to know how I got the value I was looking for:
>>> c = b - floor(b)
A:
... | Floating point accuracy in python | Any reason why c shouldn't equal 0.321?
>>> from math import ceil
>>> a = 123.321
>>> b = a % 60
>>> b
3.320999999999998
>>> ceil(b)
4.0
>>> c = ceil(b) - b
>>> c
0.679000000000002
Update:
For anyone wanting to know how I got the value I was looking for:
>>> c = b - floor(b)
| [
"You're going to facepalm in about five minutes :P\nceil(b) is 4.0\nb is 3.320999999999998\nSo ceil(b) - b should be 4.0 - 3.320999999999998. Try putting that in your calculator and you'll see why c isn't equal to 0.321.\nIf you're trying to get c equal to .321, you should probably do b - floor(b).\n"
] | [
7
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0008215437_floating_point_python.txt |
Q:
matplotlib plt.show() only selected objects
I have several plt.plot instances and I wanted to only plt.show() certain objects. To illustrate here is some code:
import matplotlib.pyplot as plt
ax1 = plt.plot(range(5),range(5))
ax2 = plt.plot([x+1 for x in range(5)],[x+1 for x in range(5)])
ax3 = plt.plot([x+2 for ... | matplotlib plt.show() only selected objects | I have several plt.plot instances and I wanted to only plt.show() certain objects. To illustrate here is some code:
import matplotlib.pyplot as plt
ax1 = plt.plot(range(5),range(5))
ax2 = plt.plot([x+1 for x in range(5)],[x+1 for x in range(5)])
ax3 = plt.plot([x+2 for x in range(5)],[x+2 for x in range(5)])
#plt.sho... | [
"You can remove some of the plotted lines from the set of lines of the current axes:\naxes = plt.gca() # Get current axes\naxes.lines.remove(ax2[0]) # Removes the (first and only) line created in ax2\nplt.draw() # Updates the graph (in interactive mode)\n\nIf you want to put it back, you can similarly do\naxes.l... | [
5,
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008214586_matplotlib_python.txt |
Q:
passing python strings, through cython, to C
I am trying to write a module with some c and some python parts. I am using cython to bridge the gap.
I want to store my (very long) string constants in python, because of the much nicer syntax:
const char long_string = "\npart of string\n"
"next part\n"
"last part\... | passing python strings, through cython, to C | I am trying to write a module with some c and some python parts. I am using cython to bridge the gap.
I want to store my (very long) string constants in python, because of the much nicer syntax:
const char long_string = "\npart of string\n"
"next part\n"
"last part\n";
versus:
long_string = """
part of string
next... | [
"Importing printf from libc.stdio fixes the problem for me:\nfrom libc.stdio cimport printf\n\ndef go():\n py_string = \"\"\"\na complicated string\nwith a few\nnewlines.\n\"\"\"\n\n cdef bytes py_bytes = py_string.encode()\n cdef char* c_string = py_bytes\n printf(c_string)\n\n print \"we actually g... | [
9
] | [] | [] | [
"c",
"cython",
"python"
] | stackoverflow_0008215265_c_cython_python.txt |
Q:
Dynamically define a function
I am trying to write a curve fitting function which returns the optimal parameters a, b and c, here is a simplified example:
import numpy
import scipy
from scipy.optimize import curve_fit
def f(x, a, b, c):
return x * 2*a + 4*b - 5*c
xdata = numpy.array([1,3,6,8,10])
ydata = num... | Dynamically define a function | I am trying to write a curve fitting function which returns the optimal parameters a, b and c, here is a simplified example:
import numpy
import scipy
from scipy.optimize import curve_fit
def f(x, a, b, c):
return x * 2*a + 4*b - 5*c
xdata = numpy.array([1,3,6,8,10])
ydata = numpy.array([ 0.91589774, 4.9158977... | [
"Taking a page from the collections.namedtuple playbook, you can use exec to \"dynamically\" define func:\nimport numpy as np\nimport scipy.optimize as optimize\nimport textwrap\n\nfuncstr=textwrap.dedent('''\\\ndef func(x, {p}):\n return x * 2*a + 4*b - 5*c\n''')\ndef make_model(**kwargs):\n params=set(('a'... | [
8,
1,
0,
0
] | [
"def f(x, a = 10, b = 15, c = 25):\n return x * 2*a + 4*b - 5*c\n\nIf the user doesn't supply an argument for the parameter in question, whatever you specified on the right-hand side of the = sign will be used:\ne.g.:\nf(5, b = 20) will evaluate to return 5 * 2*10 + 4*20 - 5*25 and\nf(7) will evaluate to return ... | [
-2
] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008196744_numpy_python_scipy.txt |
Q:
How do I call request handler in google appengine, python
I try to load file from form in two steps, and use BlobStoreUploadHandler.
At 1st step I recive form data with request handler, and check it for valid (the form action = "/a"). Then if form is valid, I want rewrite form action to upload_url, where
upload_ur... | How do I call request handler in google appengine, python | I try to load file from form in two steps, and use BlobStoreUploadHandler.
At 1st step I recive form data with request handler, and check it for valid (the form action = "/a"). Then if form is valid, I want rewrite form action to upload_url, where
upload_url = blobstore.create_upload_url('/a')
and call the post reque... | [
"There is a new experimental code of writing files to the blobstore which may suit your needs. Quote: \n\nApp Engine allows you to programmatically create blobstore blobs, providing a file-like API that you can use to read and write to blobs\n\n",
"I'm not 100% sure why you need to process this with a request han... | [
1,
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0008204270_blobstore_google_app_engine_python.txt |
Q:
Python - Bulk Select then Insert from one DB to another
I'm looking for some help on how to do this in Python using sqlite3
Basically I have a process which downloads a DB (temp) and then needs to insert it's records into a 2nd identical DB (the main db).. and at the same time ignore/bypass any possible duplicate ... | Python - Bulk Select then Insert from one DB to another | I'm looking for some help on how to do this in Python using sqlite3
Basically I have a process which downloads a DB (temp) and then needs to insert it's records into a 2nd identical DB (the main db).. and at the same time ignore/bypass any possible duplicate key errors
I was thinking of two scenarios but am unsure how ... | [
"You can ATTACH two databases to the same connection with code like this:\nimport sqlite3\nconnection = sqlite3.connect('/path/to/temp.sqlite')\ncursor=connection.cursor()\ncursor.execute('ATTACH \"/path/to/main.sqlite\" AS master')\n\nThere is no ON DUPLICATE KEY syntax in sqlite as there is in MySQL. This SO ques... | [
6,
0
] | [] | [] | [
"bulk",
"insert",
"python",
"sql"
] | stackoverflow_0008215686_bulk_insert_python_sql.txt |
Q:
Tweepy "No Access_token Data Was Acquired"
Having trouble getting the oauth access token and secret exchanged from the request tokens any help would be great everything else seems to be in the right place
TweepError: HTTP Error 401: Unauthorized
callback_url = urllib.quote("%s?twitterCallback=1" % self.request.u... | Tweepy "No Access_token Data Was Acquired" | Having trouble getting the oauth access token and secret exchanged from the request tokens any help would be great everything else seems to be in the right place
TweepError: HTTP Error 401: Unauthorized
callback_url = urllib.quote("%s?twitterCallback=1" % self.request.url)
auth = tweepy.OAuthHandler(consumer_key, c... | [
"Needed to store the request token data in the session and recall it in the second part. the call was creating a new request token.\n"
] | [
0
] | [] | [] | [
"python",
"tweepy",
"twitter",
"twitter_oauth"
] | stackoverflow_0007809532_python_tweepy_twitter_twitter_oauth.txt |
Q:
Draw plots on screen using matplotlib API
I understand how to display matplotlib plots on-screen using the pyplot interface (I think!). I started plotting in a multi-threaded program, and this started causing errors, so I am trying to switch to the object-oriented interface. I can make a simple plot and save to ... | Draw plots on screen using matplotlib API | I understand how to display matplotlib plots on-screen using the pyplot interface (I think!). I started plotting in a multi-threaded program, and this started causing errors, so I am trying to switch to the object-oriented interface. I can make a simple plot and save to file using
from matplotlib.backends.backend_agg... | [
"Your problem is that you're using a non-interactive backend (Agg rather than TkAgg, GtkAgg, QtAgg, etc). By definition, it doesn't support display to the screen.\nHowever, working with multithreaded code with any gui library will require that the gui's mainloop be run in its own thread.\nIn other words, switching... | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008216199_matplotlib_python.txt |
Q:
Retrieve values of an entity by the Django's template with db.ListProperty(db.Key)
Thanks to this post I changed my class to:
class Foo(db.Model):
name = db.StringProperty(multiline=True)
bars = db.ListProperty(db.Key)
class Bar(db.Model):
name = db.StringProperty(multiline=True)
Here a piece of m... | Retrieve values of an entity by the Django's template with db.ListProperty(db.Key) | Thanks to this post I changed my class to:
class Foo(db.Model):
name = db.StringProperty(multiline=True)
bars = db.ListProperty(db.Key)
class Bar(db.Model):
name = db.StringProperty(multiline=True)
Here a piece of my Django Template
<div >
<h3>{{ current_foo.name }}</h3>
{% for bar in cur... | [
"The best bet is to define a simple method or property on your Foo model that queries the database for the relevant Bars.\nclass Foo(db.Model):\n ...\n def get_bars(self):\n return db.get(self.bars)\n\nThen you can call this in the template:\n{% for bar in current_foo.get_bars %}\n\n"
] | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0008216999_django_google_app_engine_python.txt |
Q:
Running Python Program via sshfs-mounted Share
I have a share (on Machine-A) mounted via sshfs on Machine-B. From Machine-C, I have this share mounted also via sshfs (double sshfs) like so:
On Machine-C: /mnt/Machine-B/target_share
On Machine-B: /mnt/Machine-A/target_share
On Machine-A: /media/target_share
Now I ... | Running Python Program via sshfs-mounted Share | I have a share (on Machine-A) mounted via sshfs on Machine-B. From Machine-C, I have this share mounted also via sshfs (double sshfs) like so:
On Machine-C: /mnt/Machine-B/target_share
On Machine-B: /mnt/Machine-A/target_share
On Machine-A: /media/target_share
Now I have a Python program that runs fine in all places t... | [
"I found that there may be a bug in sshfs, such that if a user on a Linux system has the same user ID as another, i.e., 1002, but different usernames, this causes problems.\nThe way I worked around this was to actually avoid sshfs for this case all together and mount the drives directly to a local system. I wanted... | [
0
] | [] | [] | [
"filesystems",
"mount_point",
"python",
"sshfs"
] | stackoverflow_0008189641_filesystems_mount_point_python_sshfs.txt |
Q:
Loop Through File Extensions, Looking for Non-ASCII Characters - Python
I wrote a little Python program that looks though a directory (and its subdirectories) for files that contain non-ASCII characters.
I want to improve it. I know that certain files in this "directory" may be ZIP, DTA/OUT, OMX, SFD/SF3, etc... ... | Loop Through File Extensions, Looking for Non-ASCII Characters - Python | I wrote a little Python program that looks though a directory (and its subdirectories) for files that contain non-ASCII characters.
I want to improve it. I know that certain files in this "directory" may be ZIP, DTA/OUT, OMX, SFD/SF3, etc... files that ARE SUPPOSED to have non-ASCII characters. So I want to know the... | [
"I figure since there aren't any answers I can go ahead and answer this myself with a partial answer. I basically took a different approach and looked for a particular file that is expected to be abundant for this share and then will do the same for each file. It's kind of hacky, but it will get the j ob done.\n"... | [
0
] | [] | [] | [
"ascii",
"file_encodings",
"file_extension",
"python"
] | stackoverflow_0008109589_ascii_file_encodings_file_extension_python.txt |
Q:
python: sort a nested dictionary
I have a nested dictionary of type following
{id_1 : [ {id_2:score},{id_3:score_2} .... and so on],id_2 :[{id_1:Score_!....]}
so basically a nested dictionary
Now I want to sort this dictionary per primary id on the basis of score
so basically
{id_1: [{element with max_score},{ele... | python: sort a nested dictionary | I have a nested dictionary of type following
{id_1 : [ {id_2:score},{id_3:score_2} .... and so on],id_2 :[{id_1:Score_!....]}
so basically a nested dictionary
Now I want to sort this dictionary per primary id on the basis of score
so basically
{id_1: [{element with max_score},{element_with next max_score....}]... id_2... | [
"You can use the key parameter to list.sort(). Assuming the outer dictionary is called d, the code could look like this:\nfor scores in d.itervalues():\n scores.sort(key=lambda x: next(x.itervalues()), reverse=True)\n\nThe lambda function simply extracts the single value of the dictionary.\nI think you'd be bet... | [
3
] | [] | [] | [
"dictionary",
"nested",
"python"
] | stackoverflow_0008217139_dictionary_nested_python.txt |
Q:
Cassandra or MongoDB for good scaling and big amount of queries
I have the following situation. There are a lot of queries to database (commonly writing comments, reading profiles, etc...), and, I think will be more reads than writes. I want to have a good possibility to scaling db to a several servers. So, and I ... | Cassandra or MongoDB for good scaling and big amount of queries | I have the following situation. There are a lot of queries to database (commonly writing comments, reading profiles, etc...), and, I think will be more reads than writes. I want to have a good possibility to scaling db to a several servers. So, and I enjoy nosql:)
As I understand by reading blogs and answers for questi... | [
"Half answer - since it's not about suitability. Tornado 2.1 supports twisted as a async pattern, which means that you can use the telephus Cassandra library (twisted+Cassandra) to have async Cassandra access.\n import tornado.platform.twisted\n from telephus.pool import CassandraClusterPool\n from twist... | [
3
] | [] | [] | [
"asynchronous",
"cassandra",
"mongodb",
"python",
"tornado"
] | stackoverflow_0008213049_asynchronous_cassandra_mongodb_python_tornado.txt |
Q:
What's a nice way to write a login required decorator for certain handlers in Tornado?
I have some web pages I want people to be logged in to see. I'm using Facebook connect for login, and running the site on a Tornado server.
Right now, I do this:
class Home(BaseHandler):
def get(self):
if not self.current_u... | What's a nice way to write a login required decorator for certain handlers in Tornado? | I have some web pages I want people to be logged in to see. I'm using Facebook connect for login, and running the site on a Tornado server.
Right now, I do this:
class Home(BaseHandler):
def get(self):
if not self.current_user:
self.redirect("/")
else:
context = dict(current_user=self.current_u... | [
"Sounds like you haven't found the authenticated decorator\n@tornado.web.authenticated\ndef get(self):\n ...\n\nIf you don't have a current_user it will redirect you to the login_url application setting.\n"
] | [
2
] | [] | [] | [
"decorator",
"python",
"tornado"
] | stackoverflow_0008199577_decorator_python_tornado.txt |
Q:
How to install standard Python module into Iron Python?
I'm writing some ETL scripts in Iron Python and have found that I could benefit from using the date parser in module dateutil. I know I can use my standard python library by pointing Iron Python at the appropriate location. My scripts, however, will likely ... | How to install standard Python module into Iron Python? | I'm writing some ETL scripts in Iron Python and have found that I could benefit from using the date parser in module dateutil. I know I can use my standard python library by pointing Iron Python at the appropriate location. My scripts, however, will likely run on a machine with Iron Python but without plain vanilla P... | [
"IronPython doesn't support eggs (because it doesn't support zipimport), but if you just place the folder containing the .py files in site-packages it should work (as long as it doesn't use a C extension).\nEggs are just zip files, so you may have to rename it to get at the .py files.\n"
] | [
8
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0008216842_ironpython_python.txt |
Q:
How to set for m2m-field different querysets for each inline object?
So I have a model that is shown in inline form.
That model have ManyToManyField.
Imagine that there are several inline-objects that are already created.
The problem is how to show different querysets of available objects in my m2m-field based on ... | How to set for m2m-field different querysets for each inline object? | So I have a model that is shown in inline form.
That model have ManyToManyField.
Imagine that there are several inline-objects that are already created.
The problem is how to show different querysets of available objects in my m2m-field based on original inline-object.
One more time:)
I mean that in each inline-object ... | [
"Question is very poorly written, so it's hard to be sure exactly what you're looking for, but my best guess is that you're want to limit the queryset for the ManyToManyField to items that are not assigned to anything else? If that's correct:\n(You also didn't post an example model, so I'll make one up to illustrat... | [
1
] | [] | [] | [
"django",
"inlines",
"python"
] | stackoverflow_0008216815_django_inlines_python.txt |
Q:
How to give with-statement-like functionality to class?
[I apologize for the inept title; I could not come up with anything better. Suggestions for a better title are welcome.]
I want to implement an interface to HDF5 files that supports multiprocess-level concurrency through file-locking. The intended environme... | How to give with-statement-like functionality to class? | [I apologize for the inept title; I could not come up with anything better. Suggestions for a better title are welcome.]
I want to implement an interface to HDF5 files that supports multiprocess-level concurrency through file-locking. The intended environment for this module is a Linux cluster accessing a shared disk... | [
"objects that can be used in with statements are called context managers; and they implement a simple interface. They must provide two methods, an __enter__ method, which takes no arguments and may return anything (which will be assigned to the variable in the as portion), and an __exit__ method, which takes three... | [
8,
6,
2
] | [] | [] | [
"concurrency",
"python",
"with_statement"
] | stackoverflow_0008217968_concurrency_python_with_statement.txt |
Q:
Google OpenID & OAuth - How to get access tokens
I have a website from where I want users to link their GMail account, I later want access to the users GMail account through OAuth. I use Google's OpenID+OAuth (Hybrid Protocol) for this.
When I follow the above mentioned documentation, I get the following -
openi... | Google OpenID & OAuth - How to get access tokens | I have a website from where I want users to link their GMail account, I later want access to the users GMail account through OAuth. I use Google's OpenID+OAuth (Hybrid Protocol) for this.
When I follow the above mentioned documentation, I get the following -
openid.assoc_handle AOQobUfg8E9PvTYX1huZPleVGoSvky57TxLHMzI... | [
"Once you have a token, you must \n\nauthorize it, and then\nexchange it for an access token\n\nTake a look at http://code.google.com/apis/accounts/docs/OAuth.html#WorkingOauth\nor https://developers.google.com/accounts/docs/OAuth2 (for OAuth v2)\n"
] | [
2
] | [] | [] | [
"access_token",
"google_openid",
"oauth",
"python"
] | stackoverflow_0005926297_access_token_google_openid_oauth_python.txt |
Q:
find index number of uppercase character in a string
string = "heLLo hOw are you toDay"
results = string.find("[A-Z]") <----- Here is my problem
string.lower().translate(table) <--- Just for the example.
>>>string
"olleh woh era uoy yadot"
#here i need to make the characters that where uppercase, be uppercase agai... | find index number of uppercase character in a string | string = "heLLo hOw are you toDay"
results = string.find("[A-Z]") <----- Here is my problem
string.lower().translate(table) <--- Just for the example.
>>>string
"olleh woh era uoy yadot"
#here i need to make the characters that where uppercase, be uppercase again at the same index number.
>>>string
"olLEh wOh era uoy y... | [
"You can do something along this line, just need to modify it a little bit and collect those start positions into an array etc:\nimport re\n\ns = \"heLLo hOw are you toDay\"\npattern = re.compile(\"[A-Z]\")\nstart = -1\nwhile True:\n m = pattern.search(s, start + 1) \n if m == None:\n break\n start ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008204712_python.txt |
Q:
xlrd "year is out of range" error, xldate_as_tuple
I am trying to use the xldate_as_tuplefunction to covert a datetime and a time value from two seperate cells in a spreadsheet into python datetime and time. I intend to combine the currently seperate values into one python datetime value for use later in my code.
... | xlrd "year is out of range" error, xldate_as_tuple | I am trying to use the xldate_as_tuplefunction to covert a datetime and a time value from two seperate cells in a spreadsheet into python datetime and time. I intend to combine the currently seperate values into one python datetime value for use later in my code.
I can get the date row values to convert but having trou... | [
"xldate_as_tuple works as advertised, producing a (year, month, day, hour, minute, second) tuple. The problem is with what you are doing with that tuple, which in your case will have 0 for each of year, month, and day.\nShort answer: \nIf you want a time value, call datetime.time, not datetime.datetime.\nLong answe... | [
1
] | [] | [] | [
"python",
"xlrd"
] | stackoverflow_0008210700_python_xlrd.txt |
Q:
Data structure to store program sequence - Python
I am writing a software to get sequence of commands from user with standard control flow (i.e user can nest his desired commands) :
cmd1
cmd2
cmd3
loop.1:
cmd1
cmd2
cmd3
loop.2
cmd1
cmd2
endloop.2
cmd4
cmd... | Data structure to store program sequence - Python | I am writing a software to get sequence of commands from user with standard control flow (i.e user can nest his desired commands) :
cmd1
cmd2
cmd3
loop.1:
cmd1
cmd2
cmd3
loop.2
cmd1
cmd2
endloop.2
cmd4
cmd5
endloop.1
Do you happen to know of a data structu... | [
"Use an (indirectly) nested list. I assume you have a class\nclass Command(object):\n def execute(self):\n # whatever\n\nfor you basic commands. Make a subclass for loops:\nclass Loop(Command):\n def __init__(self, condition, cmds):\n self.body = cmds # list of Commands\n ... | [
1,
0,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0008217831_data_structures_python.txt |
Q:
Django or Ruby on Rails
I'm a C#/.NET developer looking to mess around with something completely different - something LAM(*) stackish for building web apps quickly.
I'm thinking either Django or Rails. I kind of like the Python language better and it seems to be more full-featured than Ruby for statistical, scien... | Django or Ruby on Rails | I'm a C#/.NET developer looking to mess around with something completely different - something LAM(*) stackish for building web apps quickly.
I'm thinking either Django or Rails. I kind of like the Python language better and it seems to be more full-featured than Ruby for statistical, scientific and networking (let me ... | [
"\nI kind of like the Python language\n better and it seems to be more\n full-featured than Ruby for\n statistical, scientific and networking\n (let me know if you think this is\n wrong).\n\nIf you think you'll need libraries like NumPy or SciPy, probably best to stick with python/django. I've struggled to fin... | [
20,
10,
8,
7,
6,
6,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"c#",
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0000732476_c#_django_python_ruby_ruby_on_rails.txt |
Q:
change some lowercase letters to uppercase in string
index = [0, 2, 5]
s = "I am like stackoverflow-python"
for i in index:
s = s[i].upper()
print(s)
IndexError: string index out of range
I understand that in the first iteration the string, s, become just the first character, an uppercase "I" in this par... | change some lowercase letters to uppercase in string | index = [0, 2, 5]
s = "I am like stackoverflow-python"
for i in index:
s = s[i].upper()
print(s)
IndexError: string index out of range
I understand that in the first iteration the string, s, become just the first character, an uppercase "I" in this particular case. But, I have tried to do it without the "s =... | [
"Strings are immutable in Python, so you need to create a new string object. One way to do it:\nindices = set([0, 7, 12, 25])\ns = \"i like stackoverflow and python\"\nprint(\"\".join(c.upper() if i in indices else c for i, c in enumerate(s)))\n\nprinting\nI like StackOverflow and Python\n\n",
"Here is my soluti... | [
21,
7
] | [] | [] | [
"python",
"python_3.x",
"string",
"uppercase"
] | stackoverflow_0008217650_python_python_3.x_string_uppercase.txt |
Q:
CSound and Python communication
I am currently working on a specialization project on simulating guitar effects with Evolutionary Algorithms, and want to use Python and CSound to do this.
The idea is to generate effect parameters in my algorithm in Python, send them to CSound and apply the filter to the audio file... | CSound and Python communication | I am currently working on a specialization project on simulating guitar effects with Evolutionary Algorithms, and want to use Python and CSound to do this.
The idea is to generate effect parameters in my algorithm in Python, send them to CSound and apply the filter to the audio file, then send the new audio file back t... | [
"sending parameter values from python to csound could be done using the osc protocol\nsending audio from csound to python could be done by routing jack channels between the two applications \n",
"You can use Csound's python API, so you can run Csound within python and pass values using the software bus. See csoun... | [
1,
1
] | [] | [] | [
"audio",
"csound",
"evolutionary_algorithm",
"python"
] | stackoverflow_0008214339_audio_csound_evolutionary_algorithm_python.txt |
Q:
pyQT and MySQL or MSSQL Connectivity
After much study and investigation, I've decided to do my Python development with pyQT4 using Eric5 as the editor. However, I've run into a brick wall with trying to get MySQL to work. It appears that there's an issue with the QMySQL driver. From the discussions that I've se... | pyQT and MySQL or MSSQL Connectivity | After much study and investigation, I've decided to do my Python development with pyQT4 using Eric5 as the editor. However, I've run into a brick wall with trying to get MySQL to work. It appears that there's an issue with the QMySQL driver. From the discussions that I've seen so far, the only fix is to install the ... | [
"If you'd rather use MS SQL it's quite easy in PyQt using QSqlDatabase and the ODBC driver.\nHere's an excerpt from a project I'm working on that uses MS SQL.\ndb = QSqlDatabase.addDatabase('QODBC')\n#TODO: Add support for trusted connections.\n#(\"Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_N... | [
5,
2,
0
] | [] | [] | [
"mysql",
"pyqt",
"python",
"sql_server"
] | stackoverflow_0005642537_mysql_pyqt_python_sql_server.txt |
Q:
why is an empty char field in Django read out as None and not an empty string?
I have a model for example like this:
class Item(models.Model):
text = model.CharField(max_length=50)
extra_text = model.CharField(max_length=50, blank=True)
Lets say I have an object instance where extra_text is blank, so in t... | why is an empty char field in Django read out as None and not an empty string? | I have a model for example like this:
class Item(models.Model):
text = model.CharField(max_length=50)
extra_text = model.CharField(max_length=50, blank=True)
Lets say I have an object instance where extra_text is blank, so in the database it is stored as an empty string ''
I read that object, for example:
myit... | [
"I can only think of one scenario where this would occur:\nYou have an existing model with existing entries in the database. You then add a new CharField but neglect to provide a default for existing items to use. When you query an existing item, that CharField will not have a value, but will also not be allowed to... | [
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008217583_django_django_models_python.txt |
Q:
Tornado "error: [Errno 24] Too many open files" error
I've worked with Tornado quite a bit, but this is the first time I've run into this sort of error. I've been working on a very basic URL shortener. URLs are put into the database by a different application, this one just reads the URLs from a MongoDB store and ... | Tornado "error: [Errno 24] Too many open files" error | I've worked with Tornado quite a bit, but this is the first time I've run into this sort of error. I've been working on a very basic URL shortener. URLs are put into the database by a different application, this one just reads the URLs from a MongoDB store and redirects the clients. After I'd written the basic code I s... | [
"Very simple, the RequestHandler object is instantiated for every request. Which means that the cached object that you're saving is on the RequestHandler (e.g. expand) object. \nIf you were to add a simple \"print 'CREATED!'\" to the dbmongo(...) function you would see that it's created on every GET request. \nW... | [
4
] | [] | [] | [
"mongodb",
"python",
"tornado"
] | stackoverflow_0008204685_mongodb_python_tornado.txt |
Q:
What is the best/most efficient way to store User Sensative Data in MySQL
What would be the best way to save user sensational data like documents that people have typed? Would it be easiest to make a database of a bunch of VARCHAR(8000) rows, or should I make independent protected files? I don't want opinions, jus... | What is the best/most efficient way to store User Sensative Data in MySQL | What would be the best way to save user sensational data like documents that people have typed? Would it be easiest to make a database of a bunch of VARCHAR(8000) rows, or should I make independent protected files? I don't want opinions, just facts. Thanks!
| [
"Encrypt it :). Someone already asked this, so check this out:\nWhat's the best way to store sensitive data in MySQL?\n",
"Storing an encrypted file on the system and then storing that filename only in the database will allow you to easily leverage command line encryption tools like pgp in order to use strong enc... | [
3,
0
] | [] | [] | [
"mysql",
"php",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0008218903_mysql_php_python_ruby_ruby_on_rails.txt |
Q:
Python Crawler - AttributeError: Crawler instance has no attribute 'url'
I'm trying to learn the classes in python:
#!/usr/bin/env python
# *-* coding: utf-8 *-*
import urllib2
from BeautifulSoup import BeautifulSoup as bs
class Crawler:
def visit(self, url):
self.request = urllib2.Request(self.url)... | Python Crawler - AttributeError: Crawler instance has no attribute 'url' | I'm trying to learn the classes in python:
#!/usr/bin/env python
# *-* coding: utf-8 *-*
import urllib2
from BeautifulSoup import BeautifulSoup as bs
class Crawler:
def visit(self, url):
self.request = urllib2.Request(self.url)
self.response = urllib2.urlopen(self.request)
return self.res... | [
"You're saying self.url which is referring to the Crawler class's url attribute, which does not exist. You need to use just url since that's the name of the variable from your visit() function arguments.\n"
] | [
5
] | [] | [] | [
"attributeerror",
"class",
"python"
] | stackoverflow_0008218970_attributeerror_class_python.txt |
Q:
else block never executes
I am trying to compare a user input to every element of a list, where NL is the list, but for some reason it never enters the else loop.
NL = range(1, sc.NLayer + 1)
if (x for x in NL if x < sc.NLayer):
print 'true'
else:
print 'false'
sc.NLayer is user input.
assume sc.NLayer... | else block never executes | I am trying to compare a user input to every element of a list, where NL is the list, but for some reason it never enters the else loop.
NL = range(1, sc.NLayer + 1)
if (x for x in NL if x < sc.NLayer):
print 'true'
else:
print 'false'
sc.NLayer is user input.
assume sc.NLayer = 5; it is not hitting the els... | [
"You might want to use the built in any function.\nany([True, False, 0, []])\n=> True\n\nSo in your code, it would be:\nif any(x for x in NL if x < sc.NLayer):\n print 'true'\nelse:\n print 'false'\n\nor possibly a for loop:\nfor x in NL:\n if x < sc.NLayer:\n print 'true'\n else:\n print ... | [
3,
2,
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0008218697_if_statement_python.txt |
Q:
Django Storage Backend for local development that proxies to live site?
I have to work on several projects with huge amounts of user-generated media files. In the past, I rsynced the content every couple of days, but my local development machine fills up more and more with data that is, for the most part, not need... | Django Storage Backend for local development that proxies to live site? | I have to work on several projects with huge amounts of user-generated media files. In the past, I rsynced the content every couple of days, but my local development machine fills up more and more with data that is, for the most part, not needed.
I remember reading about a storage backend that would proxy local file ac... | [
"I went ahead and created one. Very limited ATM but it works.\nhttp://pypi.python.org/pypi/django-localdevstorage/\n",
"Possibly not the answer you're looking for, but could you not mount the data read only through ssh/smbfs. Gets you easy access to it, but protects you from damaging it. \n"
] | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008138618_django_python.txt |
Q:
python, I am not able to save special characters, such as θæŋ after making re,search
I am not able to save special characters, such as θæŋ after making re.search.
I am saving to the Django model Textfield. in Admin page, Instead of θæŋkfəli, i am getting
\xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li
Is it error of re.sea... | python, I am not able to save special characters, such as θæŋ after making re,search | I am not able to save special characters, such as θæŋ after making re.search.
I am saving to the Django model Textfield. in Admin page, Instead of θæŋkfəli, i am getting
\xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li
Is it error of re.search?
Is it error of Admin?
Am i saving wrongly?
How to search for needed part of string ... | [
"When you see \"\\xce\\xb8\\xc3\\xa6\\xc5\\x8bkf\\xc9\\x99li, what you're seeing is in fact the same as θæŋkfəli, but in hexadecimal notation. Similarly, you could represent the same set of characters as \nU+03B8 U+00E6 U+014BkfU+0259li\nThis is because the text is stored as a unicode string. To see that this is ac... | [
1
] | [] | [] | [
"character_encoding",
"django_admin",
"python",
"regex"
] | stackoverflow_0008218695_character_encoding_django_admin_python_regex.txt |
Q:
Difference between binary string, byte string, unicode string and an ordinary string (str)
I'm a little confused. In Python what is the difference between a binary string, byte string, unicode string and a plain old string (str)? I'm using Python 2.6.
A:
It depends on the version on Python you are using.
In Pyth... | Difference between binary string, byte string, unicode string and an ordinary string (str) | I'm a little confused. In Python what is the difference between a binary string, byte string, unicode string and a plain old string (str)? I'm using Python 2.6.
| [
"It depends on the version on Python you are using.\nIn Python 2.x if you write 'abc' it has type str but this means a byte string. If you want a Unicode string you must write u'abc'.\nIn Python 3.x if you write 'abc' it still has type str but now this means that is a string of Unicode characters. If you want a byt... | [
22
] | [] | [] | [
"python"
] | stackoverflow_0008219706_python.txt |
Q:
using mechanize to post on wordpress
Long story short I need to post automated comments to my WordPress blog. I find mechanize for Python (hurray! no need to muck around in PHP!) but I can't post comments with it. According to the debug info I logged in successfully and returned to the comment page, but comments d... | using mechanize to post on wordpress | Long story short I need to post automated comments to my WordPress blog. I find mechanize for Python (hurray! no need to muck around in PHP!) but I can't post comments with it. According to the debug info I logged in successfully and returned to the comment page, but comments don't show. What's weirder is that when I t... | [
"it's possible that code built into the blog is detecting the user agent string and refusing to show the comments, but I have little experience with either Wordpress code or this python module. \nmechanize looks like a spammer's best friend otherwise. Oh of course there are thousands of legitimate uses (and I'm not... | [
0
] | [] | [] | [
"http",
"mechanize",
"python",
"web"
] | stackoverflow_0008217258_http_mechanize_python_web.txt |
Q:
Handling leap years in Python
I have a program where the user enters a date and then compares it to another date to see which one comes first.
How would I go about writing a code where the user inputs Feb 29 and the program returns Feb 28 instead (since there is no leap year)?
Example:
def date(prompt):
''' retu... | Handling leap years in Python | I have a program where the user enters a date and then compares it to another date to see which one comes first.
How would I go about writing a code where the user inputs Feb 29 and the program returns Feb 28 instead (since there is no leap year)?
Example:
def date(prompt):
''' returns the date that user inputs and v... | [
"How do you compare dates? If you use the datetime functions then this should already account for this sort of stuff.\n>>> datetime.datetime(2011, 2, 28)\ndatetime.datetime(2011, 2, 28, 0, 0)\n\n>>> datetime.datetime(2011, 2, 29)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueErr... | [
6,
5
] | [] | [] | [
"error_handling",
"leap_year",
"python"
] | stackoverflow_0005319103_error_handling_leap_year_python.txt |
Q:
python2.7 - reading a dictionary from a .txt file riddled with unicode
I enrolled into a Chinese Studies course some time ago, and I thought it'd be a great exercise for me to write a flashcard program in python. I'm storing the flash card lists in a dictionary in a .txt file, so far without trouble. The real prob... | python2.7 - reading a dictionary from a .txt file riddled with unicode | I enrolled into a Chinese Studies course some time ago, and I thought it'd be a great exercise for me to write a flashcard program in python. I'm storing the flash card lists in a dictionary in a .txt file, so far without trouble. The real problems kick in when I try to load the file, encoded in utf-8, into my program.... | [
"There's nothing wrong with your encoding... Look at this:\n>>> d = {1:'男人'}\n>>> d[1]\n'\\xe7\\x94\\xb7\\xe4\\xba\\xba'\n>>> print d[1]\n男人\n\nOne thing is to print a unicode string another one is printing its representation.\n",
"str(quizy) calls repr(quizy['character1']) which produces an ASCII representation ... | [
3,
2
] | [] | [] | [
"dictionary",
"python",
"unicode"
] | stackoverflow_0008219838_dictionary_python_unicode.txt |
Q:
How can I get a client's Name attribute with SocketServer in python?
I'm using a class RequestHandler(SocketServer.BaseRequestHandler)to handle incoming connections to a server.
I am trying to get the name of the client which is stored as an attribute that sends data to this server, but right now I can only get it... | How can I get a client's Name attribute with SocketServer in python? | I'm using a class RequestHandler(SocketServer.BaseRequestHandler)to handle incoming connections to a server.
I am trying to get the name of the client which is stored as an attribute that sends data to this server, but right now I can only get it by asking for self.client_address which returns a tuple like Name of clie... | [
"No. You would have to send that name over the communication channel.\n"
] | [
1
] | [] | [] | [
"python",
"sockets",
"socketserver"
] | stackoverflow_0008219865_python_sockets_socketserver.txt |
Q:
Can I make a custom pygtk tooltip stay on when the cursor is over it?
Please look at the following snippet :
import gtk
def callback(widget, x, y, keyboard_mode, tooltip):
hbox = gtk.HBox(False, 8)
button = gtk.Button('Exit Tooltip')
label = gtk.Label('Tooltip text')
hbox.... | Can I make a custom pygtk tooltip stay on when the cursor is over it? |
Please look at the following snippet :
import gtk
def callback(widget, x, y, keyboard_mode, tooltip):
hbox = gtk.HBox(False, 8)
button = gtk.Button('Exit Tooltip')
label = gtk.Label('Tooltip text')
hbox.pack_start(label)
hbox.pack_start(button)
hbox.show_all()
... | [
"I had this issue as well, and as far as I know, there isn't any way to determine how long a tooltip stays up.\nWhat I did (and recommend to you) is that you make your own \"tooltip\" and set it's background color to yellow, or whatever color you want, via an eventbox. Make sure you don't show it yet. This is just ... | [
0
] | [] | [] | [
"cursor",
"mousehover",
"pygtk",
"python",
"tooltip"
] | stackoverflow_0007627372_cursor_mousehover_pygtk_python_tooltip.txt |
Q:
Python - How to calculate the elapsed time since X date?
I have a database table with articles and each one of this articles have a submitted date. I need to calculate the days and hours since the article have been published in the database, like:
This article has been published 4 hours ago.
This article has been ... | Python - How to calculate the elapsed time since X date? | I have a database table with articles and each one of this articles have a submitted date. I need to calculate the days and hours since the article have been published in the database, like:
This article has been published 4 hours ago.
This article has been published 3 days and 4 hours ago.
There are already some code... | [
"Have a look at the datetime package, it has everything you need.\nwhen you subtract one datetime from another, you get a timedelta object. You can use total_seconds() to get the duration in seconds and use division to convert it to hours and days. Then your only job then is to format it into a readable string.\n",... | [
11,
3
] | [] | [] | [
"elapsedtime",
"python"
] | stackoverflow_0008220140_elapsedtime_python.txt |
Q:
simplejson dumps and multi lines
I have a little question.
I use simplejson to dumps a string.
This string contains some new line characters ( \n ),
so when I print it on the server side, I get something like that :
toto
tata
titi
And I want that it displays the same way on the client side (html).
So I did simpl... | simplejson dumps and multi lines | I have a little question.
I use simplejson to dumps a string.
This string contains some new line characters ( \n ),
so when I print it on the server side, I get something like that :
toto
tata
titi
And I want that it displays the same way on the client side (html).
So I did simply :
return json.dumps(data.replace('\... | [
"I don't know the specifics of your situation, so maybe this is fine, but in general I'd recommend that you replace \\n in the client, not on the server side. If someone wants to use your JSON API for non-HTML client, having <br> will be pretty annoying, and they'll just have to parse that back out. The server sh... | [
2
] | [] | [] | [
"json",
"python"
] | stackoverflow_0008220069_json_python.txt |
Q:
Can I get mod_wsgi to work with a 64-bit Apache/Python install?
first, I'd like to say I've been lurking on this site for years and love it. For the first time, I feel like I've encountered a problem that hasn't been addressed on StackOverflow before, so here goes.
I am trying to get python to work on my 64-bit Wa... | Can I get mod_wsgi to work with a 64-bit Apache/Python install? | first, I'd like to say I've been lurking on this site for years and love it. For the first time, I feel like I've encountered a problem that hasn't been addressed on StackOverflow before, so here goes.
I am trying to get python to work on my 64-bit Wampserver install on Windows 7. I have a 64-bit version of python 2.7... | [
"Try:\nhttp://www.lfd.uci.edu/%7Egohlke/pythonlibs/#mod_wsgi\nYou may have to use that Apache distribution though.\n",
"You could always compile from source. \nEven if you do that you'll have to get 64 bit apache too, since ASF doesn't ditribute 64 bit windows binary. Are you sure you've got 64 bit one installed?... | [
5,
0
] | [] | [] | [
"64_bit",
"apache",
"python"
] | stackoverflow_0008219942_64_bit_apache_python.txt |
Q:
Creating a list containing 30k numbers
So I am trying to compare the speeds of sorting a list. I wrote my own insertion sort function and I am comparing it with pythons built in sorting method. I now am trying to create a list that randomly generates like 30,000 or whatever numbers. Then I'm going to use a for ... | Creating a list containing 30k numbers | So I am trying to compare the speeds of sorting a list. I wrote my own insertion sort function and I am comparing it with pythons built in sorting method. I now am trying to create a list that randomly generates like 30,000 or whatever numbers. Then I'm going to use a for loop to start with a list of like 1000 numbe... | [
"If you need to generate N random numbers, you could use:\nimport random\nrandom_numbers = [ random.random() for _ in xrange(N) ]\n\nThe random module also has methods like randint for returning a random integer. Consult its documentation for more detail.\n",
"If you want to seed a random list of digits, you didn... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008220333_python.txt |
Q:
SequenceMatcher: Recording no match just once?
I am using SequenceMatcher to find a set of words within a group of texts. The problem I am having is that I need to record when it does not find a match, but one time per text. If I try an if statement, it gives me a result each time the comparison to another word fa... | SequenceMatcher: Recording no match just once? | I am using SequenceMatcher to find a set of words within a group of texts. The problem I am having is that I need to record when it does not find a match, but one time per text. If I try an if statement, it gives me a result each time the comparison to another word fails.
names=[JOHN, LARRY, PETER, MARY]
files = [path... | [
"The simple way would be to keep track of matched names and not print them if they've already been printed:\nseen = {}\nfor file in files:\n for name in names:\n if SequenceMatcher(None, name, file).ratio() > .9:\n do something\n elif name not in seen:\n seen[name] = 0\n ... | [
0,
0
] | [] | [] | [
"if_statement",
"python",
"sequencematcher"
] | stackoverflow_0008219859_if_statement_python_sequencematcher.txt |
Q:
Convert ASCII armored output to binary data
How can I convert the following PGP message to binary data using Python 2.6?
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.0.7 (MingW32)
hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE
+K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA
IgD... | Convert ASCII armored output to binary data | How can I convert the following PGP message to binary data using Python 2.6?
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.0.7 (MingW32)
hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE
+K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA
IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaa... | [
"ORIGINAL ANSWER: Is this what you are after?\n>>> import binascii\n>>> message = '''hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE\n... +K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA\n... IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO\n... 0w3NCTERFJ8XaXKz/+qw4... | [
4
] | [] | [] | [
"binary_data",
"gnupg",
"python"
] | stackoverflow_0008220290_binary_data_gnupg_python.txt |
Q:
How do I make tags required with django-tagging?
I am using django-tagging to manage tags on my entities. How do I ensure that the user has entered at least one tag when filling out a form, other than using javascript validation on the front end?
A:
Are you using the TagField()? If so, it extends the default Dja... | How do I make tags required with django-tagging? | I am using django-tagging to manage tags on my entities. How do I ensure that the user has entered at least one tag when filling out a form, other than using javascript validation on the front end?
| [
"Are you using the TagField()? If so, it extends the default Django CharField which accepts a required=True argument.\nThe above applies to a FormField, not ModelField. You can do this instead to make sure the Model field is always required in any subsequent form:\nclass MyModel(models.Model):\n tags = TagField(... | [
4
] | [] | [] | [
"django",
"django_tagging",
"python"
] | stackoverflow_0008220077_django_django_tagging_python.txt |
Q:
Is AEoid compatible with Python 2.7 multithreading?
I've noticed the use of globals (global and os.environ) in AEoid.
Am I correct in assuming it will not work safely on App Engine using Python 2.7 with threadsafe = true?
If I am, is there some documentation that would help me in making it threadsafe?
A:
Because... | Is AEoid compatible with Python 2.7 multithreading? | I've noticed the use of globals (global and os.environ) in AEoid.
Am I correct in assuming it will not work safely on App Engine using Python 2.7 with threadsafe = true?
If I am, is there some documentation that would help me in making it threadsafe?
| [
"Because the current user is stored in a global, AEOid isn't currently threadsafe. This would be easy to fix, but AEOid has been deprecated for a long time, in favor of the official OpenID authentication support, there's probably no point fixing it (or using AEOid in the first place).\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008212872_google_app_engine_python.txt |
Q:
Closing exe and running from memory
Since exe is an archive, I want my program to be able to save stuff to it's own exe file. Unfortunately, Windows keeps the file open while it's running. I'd like to find a way in Python and/or C++ to force the program to run from memory and have the file close.
A:
You can't sa... | Closing exe and running from memory | Since exe is an archive, I want my program to be able to save stuff to it's own exe file. Unfortunately, Windows keeps the file open while it's running. I'd like to find a way in Python and/or C++ to force the program to run from memory and have the file close.
| [
"You can't save data to a program's own code without resorting to some dangerous, and frankly, pointless, hacks. So the short answer is \"you can't do this.\" And why would you ever want to?\nAn EXE is not an \"archive.\" It's a set of machine code to be executed, meant to be read-only. It may contain data, but tha... | [
3,
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0008220675_c++_python.txt |
Q:
Parse out elements from a pattern
I am trying to parse the result output from a natural language parser (Stanford parser).
Some of the results are as below:
dep(Company-1, rent-5')
conj_or(rent-5, share-10)
amod(information-12, personal-11)
prep_about(rent-5, you-14)
amod(companies-20, non-affiliated-19)
aux(provi... | Parse out elements from a pattern | I am trying to parse the result output from a natural language parser (Stanford parser).
Some of the results are as below:
dep(Company-1, rent-5')
conj_or(rent-5, share-10)
amod(information-12, personal-11)
prep_about(rent-5, you-14)
amod(companies-20, non-affiliated-19)
aux(provide-23, to-22)
xcomp(you-14, provide-23)... | [
"Here is something you're looking for:\n([\\w-]*)\\(([\\w-]*)-\\d*, ([\\w-]*)-\\d*\\)\nThe parenthesis around [\\w-]* are for grouping, so that you can access data as:\nex = r'([\\w-]*)\\(([\\w-]*)-\\d*, ([\\w-]*)-\\d*\\)'\nm = re.match(ex, line)\nprint(m.group(0), m.group(1), m.group(2))\n\nBtw, I recommend using ... | [
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008220007_python_regex.txt |
Q:
parsing json python
How can I iterate through the following json file and if fa="cc.ee" then add a value inside fb?
{
"pk": 1,
"fa": "cc.ee",
"fb": {
"fc": "",
"fd_id": "12345",
}
},
#!/usr/bin/env python
import json,urllib
json_data=open("my.json... | parsing json python | How can I iterate through the following json file and if fa="cc.ee" then add a value inside fb?
{
"pk": 1,
"fa": "cc.ee",
"fb": {
"fc": "",
"fd_id": "12345",
}
},
#!/usr/bin/env python
import json,urllib
json_data=open("my.json")
data = json.load(json... | [
"JSON objects behave like dictionaries. You can add a value by assigning to the new key like you would for a dictionary:\njson_string = \"\"\"\n{\n \"pk\": 1, \n \"fa\": \"cc.ee\", \n \"fb\": {\n \"fc\": \"\", \n \"fd_id\": \"12345\"\n }\n}\"\"\"\n\nimport json\ndata = json.loads(json_stri... | [
17
] | [] | [] | [
"json",
"python"
] | stackoverflow_0008220748_json_python.txt |
Q:
django memcahed for post form generated page
Is it possible to use django and memcached for dynamic page that are generated by POST form method?
The reason I'd like to do this because some of my pages are taking long time for processing while the form input from users are occasionally simillar.
A:
Short: Yes
Not... | django memcahed for post form generated page | Is it possible to use django and memcached for dynamic page that are generated by POST form method?
The reason I'd like to do this because some of my pages are taking long time for processing while the form input from users are occasionally simillar.
| [
"Short: Yes\nNot so short (but vague because of a vague question): First, find a way to build a cache key from the form values. Then on form submit, create the key and look in the cache and if there is no content with that key, create, store and return it. If there is content, return that. Maybe add and expiration ... | [
0,
0
] | [] | [] | [
"django",
"memcached",
"post",
"python"
] | stackoverflow_0008217798_django_memcached_post_python.txt |
Q:
Weird callback execution order in Twisted?
Consider the following code:
from twisted.internet.defer import Deferred
d1 = Deferred()
d2 = Deferred()
def f1(result):
print 'f1',
def f2(result):
print 'f2',
def f3(result):
print 'f3',
def fd(result):
return d2
d1.addCallback(f1)
d1.addCallback(f... | Weird callback execution order in Twisted? | Consider the following code:
from twisted.internet.defer import Deferred
d1 = Deferred()
d2 = Deferred()
def f1(result):
print 'f1',
def f2(result):
print 'f2',
def f3(result):
print 'f3',
def fd(result):
return d2
d1.addCallback(f1)
d1.addCallback(fd)
d1.addCallback(f3)
#/BLOCK====
d2.addCallbac... | [
"tl;dr — When you return a deferred (d2) from a callback (fd), it's inserted into the callback chain of whatever deferred (d1) called fd. This is done by adding a continuation of d1's callback chain as a callback on d2, so if you add a callback to d2 after firing d1, it gets tacked on after d1's continuation.\n\nI ... | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0008220898_python_twisted.txt |
Q:
Advice: Python Framework Server/Worker Queue management (not Website)
I am looking for some advice/opinions of which Python Framework to use in an implementation of multiple 'Worker' PCs co-ordinated from a central Queue Manager.
For completeness, the 'Worker' PCs will be running Audio Conversion routines (which I... | Advice: Python Framework Server/Worker Queue management (not Website) | I am looking for some advice/opinions of which Python Framework to use in an implementation of multiple 'Worker' PCs co-ordinated from a central Queue Manager.
For completeness, the 'Worker' PCs will be running Audio Conversion routines (which I do not need advice on, and have standalone code that works).
The Audio con... | [
"How about using pyro? It gives you remote object capability and you just need a client script to coordinate the work.\n"
] | [
0
] | [] | [] | [
"message_queue",
"python",
"rabbitmq",
"worker"
] | stackoverflow_0008219355_message_queue_python_rabbitmq_worker.txt |
Q:
Parse all item elements with children from RSS feed with beautifulsoup
From an RSS feed, how do you get a string of everything that's inside each item tag?
Example input (simplified):
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Test</title>
<item>
<title>Hello world1</title>
<co... | Parse all item elements with children from RSS feed with beautifulsoup | From an RSS feed, how do you get a string of everything that's inside each item tag?
Example input (simplified):
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Test</title>
<item>
<title>Hello world1</title>
<comments>Hi there</comments>
<pubDate>Tue, 21 Nov 2011 20:10:10 +0000</pubDa... | [
"Using BeautifulStoup 4:\nimport bs4 as bs\ndoc = bs.BeautifulSoup(xml, 'xml')\nfor item in doc.findAll('item'):\n for elt in item:\n if isinstance(elt, BeautifulSoup.Tag):\n print(elt)\n\nAnd here's how you could do the same thing with lxml:\nimport lxml.etree as ET\ndoc = ET.fromstring(xml)\n... | [
5
] | [] | [] | [
"beautifulsoup",
"python",
"rss"
] | stackoverflow_0008220732_beautifulsoup_python_rss.txt |
Q:
Python: saving large web page to file
Let me start off by saying, I'm not new to programming but am very new to python.
I've written a program using urllib2 that requests a web page that I would then like to save to a file. The web page is about 300KB, which doesn't strike me as particularly large but seems to b... | Python: saving large web page to file | Let me start off by saying, I'm not new to programming but am very new to python.
I've written a program using urllib2 that requests a web page that I would then like to save to a file. The web page is about 300KB, which doesn't strike me as particularly large but seems to be enough to give me trouble, so I'm calling... | [
"I'd use a handy fileobject copier function provided by shutil module. It worked on my machine :)\n>>> import urllib2\n>>> import shutil\n>>> remote_fo = urllib2.urlopen('http://docs.python.org/library/shutil.html')\n>>> with open('bigfile', 'wb') as local_fo:\n... shutil.copyfileobj(remote_fo, local_fo)\n... \... | [
5
] | [] | [] | [
"file",
"python",
"urllib2"
] | stackoverflow_0008220669_file_python_urllib2.txt |
Q:
how to make a breakpoint on class member function of python?
I used b "classname:function" or "b classname::function", and those didn't work. now I use "b linenum" as a workaround.but as I modifiy my code frequently, linenum changes.So how to make a breakpoint on class member function in python?I google it && rea... | how to make a breakpoint on class member function of python? | I used b "classname:function" or "b classname::function", and those didn't work. now I use "b linenum" as a workaround.but as I modifiy my code frequently, linenum changes.So how to make a breakpoint on class member function in python?I google it && read the python manual, and there's no direct answer.thanks!
| [
"In pdb, the Python debugger, the breakpoint can be set with\nb classname.methodname\n\nafter the class definition has been parsed. \n\nFor example,\n% pdb ~/pybin/test.py\n\n> /home/unutbu/pybin/test.py(4)<module>()\n-> class Foo(object):\n(Pdb) l\n 1 #!/usr/bin/env python\n 2 # coding: utf-8\n 3 \n... | [
19,
6
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0008221040_debugging_python.txt |
Q:
Use a Python Module to Open Explorer on a file
I'm a python newbie, and I'm having some difficulty making a module out of some very useful code located at: Open explorer on a file.
I can't figure out what I am doing wrong.
I get the following error messages:
line 31: C:\Apps\E_drive\Python_win32Clipboard.pdf lin... | Use a Python Module to Open Explorer on a file | I'm a python newbie, and I'm having some difficulty making a module out of some very useful code located at: Open explorer on a file.
I can't figure out what I am doing wrong.
I get the following error messages:
line 31: C:\Apps\E_drive\Python_win32Clipboard.pdf line 34: r'explorer
/select, "C:\Apps\E_drive\Python_wi... | [
"I think the problem is with the initialisation of Popen_arg. Notice from the output that the value of Popen_arg is:\nr'explorer /select, \"C:\\Apps\\E_drive\\Python_win32Clipboard.pdf\"'\n\nThis is actually a python raw string literal. You want Popen_arg to have the value which this string literal represents, not ... | [
7,
4
] | [] | [] | [
"python",
"pywin32",
"subprocess"
] | stackoverflow_0008220759_python_pywin32_subprocess.txt |
Q:
Average PHP developer wanting to move to Python+Django : Directly go with Django or learn the MVC Framework stuff in PHP first?
As a student in web development, I work with PHP, mainly through CMSs.
I already know the basic knowledge on the famous MVC design pattern, but now would like to work with a framework.
I'... | Average PHP developer wanting to move to Python+Django : Directly go with Django or learn the MVC Framework stuff in PHP first? | As a student in web development, I work with PHP, mainly through CMSs.
I already know the basic knowledge on the famous MVC design pattern, but now would like to work with a framework.
I've just discovered RoR and Django (respectively Ruby & Python Frameworks) and my first experiments with these frameworks, coupled to ... | [
"The shortest path to Python/Django is to learn Python/Django.\nIf you invest time in learning something different, it will just create some preconceptions that may not hold in a Python/Django environment.\n",
"Well, here's some info that may help along the way:\n\nDon't categorize everything that has routes, con... | [
3,
1
] | [] | [] | [
"cakephp",
"django",
"frameworks",
"php",
"python"
] | stackoverflow_0008221077_cakephp_django_frameworks_php_python.txt |
Q:
Automatically generate imports, to disentangle one method from a module
I'm working on a huge Python module, like this:
import millions, and, billions, of, modules...
...lots of functions...
def myfunc
...with huge body
...more functions
I'd like to extract myfunc to its own module. However, tracking down a... | Automatically generate imports, to disentangle one method from a module | I'm working on a huge Python module, like this:
import millions, and, billions, of, modules...
...lots of functions...
def myfunc
...with huge body
...more functions
I'd like to extract myfunc to its own module. However, tracking down all the imports I need is actually pretty tedious. Is there a way to do this a... | [
"Ok, maybe this is easier than I thought:\n\nCopy function definition to a new file\nCopy the entire imports section to that new file\nUnused imports are shown with a wiggly yellow line. Delete them.\nDelete the function definition from the original file, replacing it with a call reference.\nNow you have unused imp... | [
0
] | [] | [] | [
"aptana",
"module",
"pydev",
"python",
"refactoring"
] | stackoverflow_0008221236_aptana_module_pydev_python_refactoring.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.