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:
Python - print "x" "y" times when passed in a list of [x,y]
python n00b here doing the pythonchallenge, stuck on middle of a level right now.
ex: ([' ', 10], ['#', 20])
How do I print space 10 times with python? I've tried many things, but none worked...
Thanks!
edit: I'm not looking to learn how to use for-loops... | Python - print "x" "y" times when passed in a list of [x,y] | python n00b here doing the pythonchallenge, stuck on middle of a level right now.
ex: ([' ', 10], ['#', 20])
How do I print space 10 times with python? I've tried many things, but none worked...
Thanks!
edit: I'm not looking to learn how to use for-loops, but rather, list-manipulation(is that what they're called?) tec... | [
"print ' ' * 10\n\nSame as you would for any other character, e.g.\nprint 'a' * 10\n\nSo for your list, assuming it's called l:\nfor c, n in l:\n print c * n\n\n",
"In Python you can multiply a string by an integer to get a repeated version of the string:\n>>> mystring = ' ' * 10\n>>> mystring\n' '\n\... | [
18,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004912710_list_python.txt |
Q:
Python Network/cidr Calculations
I am working on building an embedded network appliance (linux based) and have come across the need to dynamically build daemon conf files. As such, I need to be able to do some network address calculations in the python code that will be building the conf files. I am not a progra... | Python Network/cidr Calculations | I am working on building an embedded network appliance (linux based) and have come across the need to dynamically build daemon conf files. As such, I need to be able to do some network address calculations in the python code that will be building the conf files. I am not a programmer so I'm fearful I wrote a module t... | [
"This can be solved using a Hamming weight algorithm. Stolen from How to count the number of set bits in a 32-bit integer? and translated into Python:\ndef number_of_set_bits(x):\n x -= (x >> 1) & 0x55555555\n x = ((x >> 2) & 0x33333333) + (x & 0x33333333)\n x = ((x >> 4) + x) & 0x0f0f0f0f\n x += x >> 8... | [
4,
2
] | [] | [] | [
"cidr",
"networking",
"python",
"scripting"
] | stackoverflow_0004912523_cidr_networking_python_scripting.txt |
Q:
Getting the row index for a 2D numPy array when multiple column values are known
Suppose I have a 2D numPy array such as:
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
How to I find the index of the row for which I know multiple values? For example, if it is known that the 0th column is 2 and the 1st column is 5, I w... | Getting the row index for a 2D numPy array when multiple column values are known | Suppose I have a 2D numPy array such as:
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
How to I find the index of the row for which I know multiple values? For example, if it is known that the 0th column is 2 and the 1st column is 5, I would like to know the row index where this condition is met (row 1 in this case).
In m... | [
"In [80]: a = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])\nIn [81]: a\nOut[81]: \narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\na==2 returns a boolean numpy array, showing where the condition is True:\nIn [82]: a==2\nOut[82]: \narray([[False, True, False],\n [False, False, False],\n [Fa... | [
9,
4,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004910789_numpy_python.txt |
Q:
django - calling functions form one file to another
I would like keep reusing some functions I've created on many of my django views so I don't have to write them over and over on every view.
So I created a folder with a __init__.py in it. In the same folder I also created a myfunctions.py file where I placed my ... | django - calling functions form one file to another | I would like keep reusing some functions I've created on many of my django views so I don't have to write them over and over on every view.
So I created a folder with a __init__.py in it. In the same folder I also created a myfunctions.py file where I placed my functions I would like to reuse on my django views.
Here ... | [
"test_variable is a local variable so you cant see it after function finished.\nYou should rewrite your function to this:\ndef test_function():\n test_variable = 1\n return test_variable\n\nAnd use it in a views.py\ndef View(request):\n result = test_function()\n return render_to_response('template', {'te... | [
3,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004912076_django_django_templates_django_views_python.txt |
Q:
How to sum-up the numbers for the similar groups?
I've two questions. I'm trying to write a script which takes command line arguments and I see I can start the script either using:
#!/bin/env python
or
exec python -x "$0" "$@"
What's the difference between those two?
The second question is with scripting. I have... | How to sum-up the numbers for the similar groups? | I've two questions. I'm trying to write a script which takes command line arguments and I see I can start the script either using:
#!/bin/env python
or
exec python -x "$0" "$@"
What's the difference between those two?
The second question is with scripting. I have an input data-set like this:
group_a 5
group_a 7
group... | [
"This should be two separate questions.\n1) The two ways are equivalent. The shebang just marks the program as to be executed by Python, so you don't have to specify it when you run it.\n2)\nimport collections\ngroups = collections.defaultdict(int)\n\nfor line in data_set:\n group, value = line.split()\n grou... | [
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004912931_python.txt |
Q:
Image color recognition, the general color
I want to get the most prominent color of an image, and the language can be in either python or ruby.
Is this easily done?
A:
Not sure if this is what you mean, but the Python PIL has im.histogram() and im.getcolors() functions. http://effbot.org/imagingbook/image.htm
... | Image color recognition, the general color | I want to get the most prominent color of an image, and the language can be in either python or ruby.
Is this easily done?
| [
"Not sure if this is what you mean, but the Python PIL has im.histogram() and im.getcolors() functions. http://effbot.org/imagingbook/image.htm\n",
"OK. Let me introduce the library for Ruby.\nUsing Camellia, http://camellia.sourceforge.net/examples.html, you can label the area with the most prominent color.\n",
... | [
1,
1,
1
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0004911066_python_ruby.txt |
Q:
Customized command line parsing in Python
I'm writing a shell for a project of mine, which by design parses commands that looks like this:
COMMAND_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com
My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of... | Customized command line parsing in Python | I'm writing a shell for a project of mine, which by design parses commands that looks like this:
COMMAND_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com
My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my ... | [
"You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split().\nargs = {}\nfor arg in shlex.split(cmdln_args):\n key, valu... | [
10,
9,
2,
1,
0,
0,
0
] | [] | [] | [
"arguments",
"command_line",
"parsing",
"python",
"shell"
] | stackoverflow_0000156873_arguments_command_line_parsing_python_shell.txt |
Q:
Python threaded code not acting threaded
Why doesn't this code "act" threaded? (Please see the output.)
import time
from threading import Thread
def main():
for nums in [range(0,5), range(5,10)]:
t = Spider(nums)
t.start()
print 'started a thread'
t.join()
print "done"
cl... | Python threaded code not acting threaded | Why doesn't this code "act" threaded? (Please see the output.)
import time
from threading import Thread
def main():
for nums in [range(0,5), range(5,10)]:
t = Spider(nums)
t.start()
print 'started a thread'
t.join()
print "done"
class Spider(Thread):
def __init__(self, num... | [
"When you say t.join(), you're telling it to wait for the thread to end.\nThis means, you're asking it to make a thread, start it, then wait for the thread to end before making a new one.\nIf you want it to act multithreaded, you'll need to move the join()s outside of the loop.\ndef main():\n # We will store the... | [
6,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004913938_multithreading_python.txt |
Q:
How can you setup multiple WSGI apps on one server?
I'm working on a python based server product where a user can install WSGI-based python apps on their server. I can enforce any restriction on the application structure or format to make this easy.
The user workflow would be:
browse an app market, showing a list... | How can you setup multiple WSGI apps on one server? | I'm working on a python based server product where a user can install WSGI-based python apps on their server. I can enforce any restriction on the application structure or format to make this easy.
The user workflow would be:
browse an app market, showing a list of WSGIpython apps
select an app and choose "install"
th... | [
"Python Paste URLMap does this via a config file, that might give you a good start.\n"
] | [
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0004913112_python_wsgi.txt |
Q:
How do you call a handler from your basehandler in python appengine?
I'd like to do something like this:
class Basehandler(webapp.RequestHandler):
def __init__(self):
if checkforspecialcase: #check something that always needs to be handled
return SpecialCaseHandler.get()
class NormalHandler(Basehandl... | How do you call a handler from your basehandler in python appengine? | I'd like to do something like this:
class Basehandler(webapp.RequestHandler):
def __init__(self):
if checkforspecialcase: #check something that always needs to be handled
return SpecialCaseHandler.get()
class NormalHandler(Basehandler):
def get(self):
print 'hello world'
return
class SpecialCa... | [
"WSGIApplication routes incoming requests based on the URL. For example,\napplication = webapp.WSGIApplication(\n [('/special-case', SpecialCaseHandler)])\n\nWhen checkforspecialcase passes, you can use self.redirect('/special-case').\n",
"To keep things DRY, use the Template Method pattern\nclass Ba... | [
3,
3,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0004901108_google_app_engine_python_web_applications.txt |
Q:
Processing a JSON response in python for the Bing API
I am writing the back-end of an answers aggregator site in python using the Bing API (python bindings here:http://uswaretech.com/blog/2009/06/bing-python-api/). The following is my code:
#!/usr/bin/python
from bingapi import bingapi
import re
import cgi
import ... | Processing a JSON response in python for the Bing API | I am writing the back-end of an answers aggregator site in python using the Bing API (python bindings here:http://uswaretech.com/blog/2009/06/bing-python-api/). The following is my code:
#!/usr/bin/python
from bingapi import bingapi
import re
import cgi
import cgitb
from HTMLParser import HTMLParser
class MLStripper(H... | [
"Nevermind, just found a syntax error that apache didn't pick up I guess. In the \"getInfo()\" function it says \"return result\" when it should say \"return results\".\n"
] | [
1
] | [] | [] | [
"bing",
"bing_api",
"json",
"python"
] | stackoverflow_0004911735_bing_bing_api_json_python.txt |
Q:
Can google.appengine.api.taskqueue payload argument be query result?
I'm trying to pass a query result to a taskqueue:
q = models.Spam.all()
results = q.fetch(10)
taskqueue.add(url='/_ah/queue/do-spams', payload=results)
This isn't working. I either have the argument structure wrong, or payload cannot be result ... | Can google.appengine.api.taskqueue payload argument be query result? | I'm trying to pass a query result to a taskqueue:
q = models.Spam.all()
results = q.fetch(10)
taskqueue.add(url='/_ah/queue/do-spams', payload=results)
This isn't working. I either have the argument structure wrong, or payload cannot be result sets.
| [
"Instead of adding directly to a task queue I would use the deferred queue. Deferred Queues have similar functionality as task queues. One of the key features of deferred queues is that you can pass any type of data to one of your internal methods. \nYou specify the method you want to defer, the parameter values,... | [
1,
0
] | [] | [] | [
"datastore",
"google_app_engine",
"python",
"task"
] | stackoverflow_0004914209_datastore_google_app_engine_python_task.txt |
Q:
Optimize generator for multivariate polynomial exponents
HI,
I'm try to find a general expression to obtain exponents of a multivariate polynomial of order order and with n_variables, like the one presented in this reference in equation (3).
Here is my current code, which uses an itertools.product generator.
def ... | Optimize generator for multivariate polynomial exponents | HI,
I'm try to find a general expression to obtain exponents of a multivariate polynomial of order order and with n_variables, like the one presented in this reference in equation (3).
Here is my current code, which uses an itertools.product generator.
def generalized_taylor_expansion_exponents( order, n_variables ):
... | [
"Actually your biggest performance issue is that most of the tuples you're generating are too big and need to be thrown away. The following should generate exactly the tuples you want.\ndef generalized_taylor_expansion_exponents( order, n_variables ):\n \"\"\"\n Find the exponents of a multivariate polynomia... | [
2,
0
] | [] | [] | [
"generator",
"optimization",
"python",
"python_itertools"
] | stackoverflow_0004913902_generator_optimization_python_python_itertools.txt |
Q:
Query on im.save in PIL python
I am using im.load() to get the pixels of ORIGINAL_IMAGE. Subsequently, I save it
I see that whatever is saved is different from what I wanted to save -
This is a code snippet and output that will highlight my issue -
Snippet:
im = Image.open(ORIGINAL_IMAGE)
dup_im = im.copy()
pix ... | Query on im.save in PIL python | I am using im.load() to get the pixels of ORIGINAL_IMAGE. Subsequently, I save it
I see that whatever is saved is different from what I wanted to save -
This is a code snippet and output that will highlight my issue -
Snippet:
im = Image.open(ORIGINAL_IMAGE)
dup_im = im.copy()
pix = dup_im.load()
dup_im.save(DUP_IMA... | [
"I can recreate this when loading a JPG and saving it as JPG again. The pixel data is equal when saving it as bitmap though. As JPG is a lossy image format, the save causes a re-encoding, thus changing the pixel data.\n"
] | [
6
] | [] | [] | [
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0004914764_image_image_processing_python_python_imaging_library.txt |
Q:
Using Python to generate JSON Data
I'm working on a little project, the aim being to generate a report from a database for a server. The database is SQLite and contains tables like 'connections', 'downloads', etc.
The report I produce will ultimately contain a number of graphs displaying things like 'connections ... | Using Python to generate JSON Data | I'm working on a little project, the aim being to generate a report from a database for a server. The database is SQLite and contains tables like 'connections', 'downloads', etc.
The report I produce will ultimately contain a number of graphs displaying things like 'connections per day', 'top downloads this month', et... | [
"It sounds sensible to me.\n\nYou need some programming language to talk to SQLite. You could do it in C, but if you can write the necessary glue code easily in Python, why not? You'll almost certainly save more time writing it than you'll lose from not having the most efficient possible program.\nThere are definit... | [
3,
2
] | [] | [] | [
"json",
"python",
"report",
"reporting",
"sqlite"
] | stackoverflow_0004914558_json_python_report_reporting_sqlite.txt |
Q:
Virtualenvs won't work after switching from 64 to 32-bit Python on OSX
I re-installed Python 2.7 with the official DMG installer from python.org because I needed to use a pre-compiled binary which choked on my 64-bit Python install..
(Recompiling it to run in 64-bit is too difficult for me, not an option)
It wor... | Virtualenvs won't work after switching from 64 to 32-bit Python on OSX | I re-installed Python 2.7 with the official DMG installer from python.org because I needed to use a pre-compiled binary which choked on my 64-bit Python install..
(Recompiling it to run in 64-bit is too difficult for me, not an option)
It worked, the Python mac Installer fixes all the links, so my new python install ... | [
"I'd go with recreating them. The \"python\" executable in the bin folder is an executable and is probably specific to your architecture and/or python binary. You can save all installed python packages and reinstall them in the new virtual environment using pip:\npip freeze -E lepoc > requirements.txt\npip install ... | [
3
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0004914866_python_virtualenv.txt |
Q:
Including distutils in a py2app bundle
I have a script that installs Python, and then installs some modules modules with:
subprocess.call("python setup.py install")
It works OK on windows with py2exe. But with Mac, using py2app, I get the following error when installing the additional modules:
File setup.py
... | Including distutils in a py2app bundle | I have a script that installs Python, and then installs some modules modules with:
subprocess.call("python setup.py install")
It works OK on windows with py2exe. But with Mac, using py2app, I get the following error when installing the additional modules:
File setup.py
from distutils.core import setup
ImportError... | [
"Try passing env={} for MacOS.\nI found you need env=None for Windows and env={} for MacOS for some reason. I was trying to launch Pylint in the local Python from an app running through py2exe on Windows and py2app on MacOS (and via egg install on Linux).\n"
] | [
0
] | [] | [] | [
"distutils",
"macos",
"py2app",
"python"
] | stackoverflow_0004512628_distutils_macos_py2app_python.txt |
Q:
Using gobject.timeout_add_seconds - Segmentation Fault
I am writing a gui program that allows a user to repeatedly send a message to a phone number with a configurable delay and number of repetitions.
I used QT Designer to create a gui, and now I am trying to create the code behind it. I am trying to make the pro... | Using gobject.timeout_add_seconds - Segmentation Fault | I am writing a gui program that allows a user to repeatedly send a message to a phone number with a configurable delay and number of repetitions.
I used QT Designer to create a gui, and now I am trying to create the code behind it. I am trying to make the program start sending messages when the start button is pressed... | [
"You appear to be using a (Py)GTK timer object within a (Py)Qt application. Try replacing\n self.maintimer = gobject.timeout_add_seconds(1, self.sendMessages)\n\nwith the equivalent PyQt code\n self.maintimer = QtCore.QTimer(self);\n self.connect(self.maintimer, QtCore.SIGNAL('timeout()'), self.sendMessag... | [
4
] | [] | [] | [
"gobject",
"python"
] | stackoverflow_0004914796_gobject_python.txt |
Q:
Using mock objects without tying down unit tests
I'm currently writing a set of unit tests for a Python microblogging library, and following advice received here have begun to use mock objects to return data as if from the service (identi.ca in this case).
However, surely by mocking httplib2 - the module I am usin... | Using mock objects without tying down unit tests | I'm currently writing a set of unit tests for a Python microblogging library, and following advice received here have begun to use mock objects to return data as if from the service (identi.ca in this case).
However, surely by mocking httplib2 - the module I am using to request data - I am tying the unit tests to a spe... | [
"Not sure what your problem is. The mock class is part of the tests, conceptually at least. It is ok for the tests to depend on particular behaviour of the mock objects that they inject into the code being tested. Of course the injection itself should be shared across unit tests, so that it is easy to change the mo... | [
1,
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0004914582_python_unit_testing.txt |
Q:
Multiple inheritance with Django
I'm using Django for a project, and I want to use a couple of apps that extend the admin by subclassing the admin class.
How can I have them both sublass the admin class?
from django.contrib import admin
from testing.models import *
from reversion.admin import VersionAdmin
from mod... | Multiple inheritance with Django | I'm using Django for a project, and I want to use a couple of apps that extend the admin by subclassing the admin class.
How can I have them both sublass the admin class?
from django.contrib import admin
from testing.models import *
from reversion.admin import VersionAdmin
from moderation.admin import ModerationAdmin
... | [
"Both VersionAdmin and ModerationAdmin appear to use the \"cooperative super\" feature of Python. So I'd try to just use multiple inheritance:\nclass ItemAdmin(VersionAdmin, ModerationAdmin):\n pass\n\nIf this fails, you can see whether it works better with the reverse order. If this still fails, you need to stu... | [
4
] | [] | [] | [
"class",
"django",
"inheritance",
"multiple_inheritance",
"python"
] | stackoverflow_0004915178_class_django_inheritance_multiple_inheritance_python.txt |
Q:
Python: 'ascii' codec can't encode character u'\\u2026'
I am trying to use the Bing api in python with the following code:
#!/usr/bin/python
from bingapi import bingapi
import re
import json
import urllib
import cgi
import cgitb
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(se... | Python: 'ascii' codec can't encode character u'\\u2026' | I am trying to use the Bing api in python with the following code:
#!/usr/bin/python
from bingapi import bingapi
import re
import json
import urllib
import cgi
import cgitb
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
d... | [
"That particular Unicode character is \"HORIZONTAL ELLIPSIS\". One or more of your getXXXXX() functions are returning Unicode strings, one of which contains a non-ASCII character. I suggest declaring the encoding of your output, for example:\nContent-Type: text/html; charset=utf-8\n\nand explicitly encoding your ... | [
3,
2
] | [] | [] | [
"encoding",
"python",
"unicode"
] | stackoverflow_0004915186_encoding_python_unicode.txt |
Q:
CherryPy doesn't properly handle non-ASCII characters in Jinja2 templates
I am trying to run a website using Python 2.7.1, Jinja 2.5.2, and CherryPy 3.1.2. The Jinja templates I am using are UTF-8 encoded. I noticed that some of the characters in those templates are being turned into question marks and other gibbe... | CherryPy doesn't properly handle non-ASCII characters in Jinja2 templates | I am trying to run a website using Python 2.7.1, Jinja 2.5.2, and CherryPy 3.1.2. The Jinja templates I am using are UTF-8 encoded. I noticed that some of the characters in those templates are being turned into question marks and other gibberish. If I try to render the templates directly without Jinja, I don't notice t... | [
"jinja2 works with Unicode only. It seems that cherrypy usually uses utf-8 as output encoding when the client sends no Accept-Header, but falls back to iso-8859-1 when it is empty.\n\ntools.encode.encoding: If specified,\n the tool will error if the response\n cannot be encoded with it. Otherwise,\n the tool wil... | [
6,
2
] | [] | [] | [
"character_encoding",
"cherrypy",
"jinja2",
"python",
"unicode"
] | stackoverflow_0004915411_character_encoding_cherrypy_jinja2_python_unicode.txt |
Q:
How to update records in SQL Alchemy in a Loop
I am trying to use SQLSoup - the SQLAlchemy extention, to update records in a SQL Server 2008 database. I am using pyobdc for the connections. There are a number of issues which make it hard to find a relevant example.
I am reprojection a geometry field in a very lar... | How to update records in SQL Alchemy in a Loop | I am trying to use SQLSoup - the SQLAlchemy extention, to update records in a SQL Server 2008 database. I am using pyobdc for the connections. There are a number of issues which make it hard to find a relevant example.
I am reprojection a geometry field in a very large table (2 million + records), so many of the stand... | [
"Try using a Session.\nrs = s.execute() then becomes session.execute(rs) and you can replace the last three lines with session.execute(update_sql). I'd also suggest configuring your Session with autocommit off and call session.commit() at the end.\n",
"Can I suggest that when your process hangs you do a sp_who2 o... | [
1,
1,
1
] | [] | [] | [
"python",
"sql_server",
"sqlalchemy",
"sqlsoup"
] | stackoverflow_0004904872_python_sql_server_sqlalchemy_sqlsoup.txt |
Q:
What's wrong with this url?
I have a root urls.py and an app urls.py. In my root I have this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', include('realestate.properties.urls')),
(r'^admin/', include(admin.site.urls)),
)
... | What's wrong with this url? | I have a root urls.py and an app urls.py. In my root I have this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', include('realestate.properties.urls')),
(r'^admin/', include(admin.site.urls)),
)
In my app urls I have the follow... | [
"I think you need to drop the $ from your urlconf, where you include the app's urls. Probably you can remove the ^ too.\nurlpatterns = patterns('',\n (r'^', include('realestate.properties.urls')),\n (r'^admin/', include(admin.site.urls)),\n)\n\nhttp://docs.djangoproject.com/en/1.2/topics/http/urls/#including-... | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004915647_django_python.txt |
Q:
Python Class / Instance /Object Organization Question
The following is a simplified example for something I'm trying to do in python (with pygame, but that's probably irrelevant).
I have a list of 8x8 pixel jpgs, each depicting an English letter:
[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
I want to arra... | Python Class / Instance /Object Organization Question | The following is a simplified example for something I'm trying to do in python (with pygame, but that's probably irrelevant).
I have a list of 8x8 pixel jpgs, each depicting an English letter:
[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
I want to arrange a 4x4 grid of these, in any pattern I want, as a larger... | [
"Since the size of a frame is fixed, and the number of frames is not, then making a class Frame seems like a good first choice. Each Frame would contain a member grid which could be a list of four lists of four letters. A list of four strings wouldn't work as well since strings are immutable, though having it be ... | [
1,
0,
0
] | [] | [] | [
"class",
"instance",
"object",
"pygame",
"python"
] | stackoverflow_0004914939_class_instance_object_pygame_python.txt |
Q:
Implementing Email Verification process with GAE python
I want to implement a simple registration to my app on google app engine.
I store the user email and password on the db and than i want to send an authentication email to the email the user have entered to verify if he is the actual owner of the address
i gue... | Implementing Email Verification process with GAE python | I want to implement a simple registration to my app on google app engine.
I store the user email and password on the db and than i want to send an authentication email to the email the user have entered to verify if he is the actual owner of the address
i guess i will generate some GUID and store it in the DB
than have... | [
"Afair GAE is based on python-django, so there’s much information on this in the web.\nCheck for example: http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/\nMore is available if you google for: django email confirmation\n"
] | [
0
] | [] | [] | [
"email_verification",
"google_app_engine",
"python"
] | stackoverflow_0004915922_email_verification_google_app_engine_python.txt |
Q:
Mixing white to a color
I have a set of colors specified in RBG and CMYK. I want to mix a certain amount of white (given in percent) to these colors. How can I do this based on the representations available? Can someone recommend a package that can help me with this kind of color conversions?
A:
If you have RGB ... | Mixing white to a color | I have a set of colors specified in RBG and CMYK. I want to mix a certain amount of white (given in percent) to these colors. How can I do this based on the representations available? Can someone recommend a package that can help me with this kind of color conversions?
| [
"If you have RGB values r, g and b between 0 and 255 and want to mix them with x% white, you can calculate\nr' = ((100 - x) * r + x * 255) / 100\ng' = ((100 - x) * g + x * 255) / 100\nb' = ((100 - x) * b + x * 255) / 100\n\nIf you need it to be efficient, there are ways of doing this with efficient bit operations.\... | [
1,
1,
0
] | [] | [] | [
"colors",
"python"
] | stackoverflow_0004916189_colors_python.txt |
Q:
Scraping values from HTML header and saving as a CSV file in Python
All,
I've just started using Python (v 2.7.1) and one of my first programs is trying to scrape information from a website containing power station data using the Standard Library and BeautifulSoup to handle the HTML elements.
The data I'd like to ... | Scraping values from HTML header and saving as a CSV file in Python | All,
I've just started using Python (v 2.7.1) and one of my first programs is trying to scrape information from a website containing power station data using the Standard Library and BeautifulSoup to handle the HTML elements.
The data I'd like to access is obtainable in either the 'Head' section of the HTML or as table... | [
"Don't turn it back into a string and then use replace. That completely defeats the point of using BeautifulSoup!\nTry starting like this:\nscripttag = soup.head.findAll(\"script\")[1]\njavascriptdata = scripttag.contents[0]\n\nThen you can use:\n\npartition('=')[2] to cut off the \"var gs_csv\" bit.\nstrip(' \\n\"... | [
4,
1
] | [] | [] | [
"csv",
"html",
"python",
"scrape",
"web"
] | stackoverflow_0004914883_csv_html_python_scrape_web.txt |
Q:
How to set up icon for a program?
How can i set up icon for my existing program.exe and icon.ico ( in the same folder ) using some sort of hidden (settings) file ?
Edit: i am aware of py2exe CustomIcon option, also about WinRar Sfx ...
Question is: it is possible in this specific way i described ?
A:
Read py2exe... | How to set up icon for a program? | How can i set up icon for my existing program.exe and icon.ico ( in the same folder ) using some sort of hidden (settings) file ?
Edit: i am aware of py2exe CustomIcon option, also about WinRar Sfx ...
Question is: it is possible in this specific way i described ?
| [
"Read py2exe doc:\nhttp://www.py2exe.org/index.cgi/CustomIcons\n",
"do it like this:\nIf you dont have winrar then install it!\nThen right click on your program.exe and select \"Add to archive...\", under \"Archiving options\" select \"Create SFX Archive\". Now go to tab \"Advanced\" and click on \"SFX Options\" ... | [
2,
0
] | [] | [] | [
"exe",
"ico",
"icons",
"python"
] | stackoverflow_0004915202_exe_ico_icons_python.txt |
Q:
Modify passed, nested dict/list
I was thinking of writing a function to normalize some data. A simple approach is
def normalize(l, aggregate=sum, norm_by=operator.truediv):
aggregated=aggregate(l)
for i in range(len(l)):
l[i]=norm_by(l[i], aggregated)
l=[1,2,3,4]
normalize(l)
l -> [0.1, 0.2, 0.3, ... | Modify passed, nested dict/list | I was thinking of writing a function to normalize some data. A simple approach is
def normalize(l, aggregate=sum, norm_by=operator.truediv):
aggregated=aggregate(l)
for i in range(len(l)):
l[i]=norm_by(l[i], aggregated)
l=[1,2,3,4]
normalize(l)
l -> [0.1, 0.2, 0.3, 0.4]
However for nested lists and di... | [
"I don't think any change to the normalize() function is necessary. To handle the nested lists, you just need to supply the right aggregate() and norm_by() functions to handle the case.\nl = [[1, 100], [2, 100], [3, 100], [4, 100]]\ndef aggregator(l):\n return sum(item[0] for item in l)\n\ndef normalizer(item ,... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004915861_python.txt |
Q:
Django: Display a model and a count of how often another model uses it
I am creating a TODO list that categorizes tasks by their status. IE: Waiting, Today, Tomorrow, Scheduled. My models look something like:
class Status(models.Model):
title = models.CharField(max_length=32)
class Task(models.Model):
u... | Django: Display a model and a count of how often another model uses it | I am creating a TODO list that categorizes tasks by their status. IE: Waiting, Today, Tomorrow, Scheduled. My models look something like:
class Status(models.Model):
title = models.CharField(max_length=32)
class Task(models.Model):
user = models.ForeignKey(User)
status = models.ForeignKey(Status, default... | [
"Django's aggregation features can do this quite simply.\nfrom django.db.models import Count\nstatuses = Status.objects.all().annotate(Count('task'))\n\nNow each item in statuses has an attribute task__count which is the number of tasks related to that status.\n"
] | [
2
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0004916552_django_django_orm_python.txt |
Q:
How do I sort a query object which is a StringListProperty()?
I have this model:
class ArticleTagList(db.Model):
article_tags = db.StringListProperty()
In the EditArticleHandler I do:
tag_query = ArticleTagList.all()
for tag in tag_query:
for i in range(len(tag.article_tags)):
... | How do I sort a query object which is a StringListProperty()? | I have this model:
class ArticleTagList(db.Model):
article_tags = db.StringListProperty()
In the EditArticleHandler I do:
tag_query = ArticleTagList.all()
for tag in tag_query:
for i in range(len(tag.article_tags)):
self.response.out.write(""" <span id="small-tags">
... | [
"You probably want:\n for article_tag_list in tag_query:\n article_tags = sorted(article_tag_list.article_tags)\n for tag in article_tags:\n self.response.out.write(\"\"\"<span id=\"small-tags\">\n <input type=\"checkbox\" name=\"article_tag\" value=\"%s\">%s </span>\"\"\"\n ... | [
2,
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"sorting"
] | stackoverflow_0004916347_google_app_engine_python_sorting.txt |
Q:
Does main() need to be in every script containing handlers?
Experienced Java programmer trying to learn Python. I have an applicaiton on Google App Engine and want to move my admin Handlers to a separate file. So now I have main.py and admin.py. I've set up app.yaml to route traffic properly, and have added the... | Does main() need to be in every script containing handlers? | Experienced Java programmer trying to learn Python. I have an applicaiton on Google App Engine and want to move my admin Handlers to a separate file. So now I have main.py and admin.py. I've set up app.yaml to route traffic properly, and have added the call to WSGIApplication() in each file to route to the appropria... | [
"You need this in any script that's referenced directly your app.yaml.\nAny time App Engine needs to send a request to one of your scripts, it goes through the following steps:\n\nHas the script been imported before? If not, just import it and stop.\nIf the script has been imported before, does it have a function c... | [
4,
3
] | [] | [] | [
"google_app_engine",
"httphandler",
"python"
] | stackoverflow_0004910363_google_app_engine_httphandler_python.txt |
Q:
Is there a name to the "things to handle" design pattern?
There's a design pattern I use once in a while, and I don't know what's it called. Perhaps it has a name and someone here knows it?
It's something I use when I want to traverse a tree-like structure and do some action on all of its nodes. It goes something ... | Is there a name to the "things to handle" design pattern? | There's a design pattern I use once in a while, and I don't know what's it called. Perhaps it has a name and someone here knows it?
It's something I use when I want to traverse a tree-like structure and do some action on all of its nodes. It goes something like this:
nodes_to_handle = [root_node]
while nodes_to_handle:... | [
"This looks like the depth-first traversal algorithm. (since you pop the list from the end)\nIt can be implemented generically in a few different ways:\n\nUsing an iterator which traverses the tree (the preferred way)\nUsing a traversal function (like yours) with a callback (for the #handle node code).\n\nOutside t... | [
3,
3,
1
] | [] | [] | [
"algorithm",
"design_patterns",
"python"
] | stackoverflow_0004908131_algorithm_design_patterns_python.txt |
Q:
Problem querying from a model object
I'm trying to use Pylons with SqlAlchemy (through Elixir).
Here is my testdb/model/entities.py:
from elixir import *
metadata.bind = "mysql://testdb:hundertwasser@localhost/testdb"
metadata.bind.echo = True
class Post(Entity):
text = Field(Unicode(128))
And here is the c... | Problem querying from a model object | I'm trying to use Pylons with SqlAlchemy (through Elixir).
Here is my testdb/model/entities.py:
from elixir import *
metadata.bind = "mysql://testdb:hundertwasser@localhost/testdb"
metadata.bind.echo = True
class Post(Entity):
text = Field(Unicode(128))
And here is the controller:
import logging
from pylons imp... | [
"The answer is as follows:\nentities.py is missing the following two lines at the bottom:\nsetup_all()\ncreate_all()\n\n",
"I don't know Elixir well, but isn't putting the following in the .ini enough?\nsqlalchemy.url = mysql://user:pass@localhost/dbname?charset=utf8&use_unicode=0\nsqlalchemy.pool_recycle = 3600\... | [
1,
0
] | [] | [] | [
"mysql",
"pylons",
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0004915644_mysql_pylons_python_python_elixir_sqlalchemy.txt |
Q:
Given a noun, what's the best way to determine the "gender"?
I'm given the task of determining whether an advertisement is suited for male or female.
What's the best way of determining this?
The words looks like this:
Cheetos
Coca Cola
Nike
Ferrari
24
Arrested Development
Transformers
Nestle
American Eagle
For ea... | Given a noun, what's the best way to determine the "gender"? | I'm given the task of determining whether an advertisement is suited for male or female.
What's the best way of determining this?
The words looks like this:
Cheetos
Coca Cola
Nike
Ferrari
24
Arrested Development
Transformers
Nestle
American Eagle
For each word, I'd like to know if it's more associated to male or femal... | [
"Testing for these kinds of associations is very difficult, and I doubt you could do it without doing actual research. However, if you're up for it, you should look into the \"Implicit Association Test.\" You can find a demonstration of it here:\nhttp://www.understandingprejudice.org/iat/index2.htm\nHere's a Wikipe... | [
3
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0004915776_nlp_nltk_python.txt |
Q:
Python Determine week of Year (non-ISO way)
Is there a pythonic way of getting the equivalent of the following in .NET?
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt.Date, CalendarWeekRule.FirstDay, DayOfWeek.Monday)
dt.isocalendar()[1] does not seem to work for me as it returns 53 (expecting 52) for date... | Python Determine week of Year (non-ISO way) | Is there a pythonic way of getting the equivalent of the following in .NET?
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt.Date, CalendarWeekRule.FirstDay, DayOfWeek.Monday)
dt.isocalendar()[1] does not seem to work for me as it returns 53 (expecting 52) for datetime.date(2010, 1, 1)
Thanks.
| [
"The ISO calendar has a range of confusing rules that are likely the source of the issues you face here. In particular, the .NET implementation of GetWeekOfYear (with the parameters you have used) is so similar to ISO that explicit clarifications are required and linked from MSDN. The result is that isocalendar and... | [
3
] | [] | [] | [
".net",
"python"
] | stackoverflow_0004917045_.net_python.txt |
Q:
pygtk image grid
I'm looking for an easy way to implement something like this: http://www.dinointeractive.com/?p=117. And I was guessing if somebody here had an idea.
I want to arrange images in a grid view.
And additionally the images should arrange their position automaticly
A:
You might find gtk.IconView usef... | pygtk image grid | I'm looking for an easy way to implement something like this: http://www.dinointeractive.com/?p=117. And I was guessing if somebody here had an idea.
I want to arrange images in a grid view.
And additionally the images should arrange their position automaticly
| [
"You might find gtk.IconView useful. You might also want to look into gtk.Layout depending on what you might want to do.\nSome sample code can be found here and a related SO question here.\n"
] | [
1
] | [] | [] | [
"gridview",
"pygtk",
"python"
] | stackoverflow_0004916935_gridview_pygtk_python.txt |
Q:
Django : Foreign key set not found after saving object
I've got a question model and mcq choices model which have foreign key to question.
class Question(models.Model):
statement = models.TextField(max_length=1024)
def save(self, *args, **kwargs):
super(Question,self).save(*args,**kwargs)
#... | Django : Foreign key set not found after saving object | I've got a question model and mcq choices model which have foreign key to question.
class Question(models.Model):
statement = models.TextField(max_length=1024)
def save(self, *args, **kwargs):
super(Question,self).save(*args,**kwargs)
#ques = Question.objects.get(id = self.id)
f = open('... | [
"class Foo(models.Model):\n pass\n\n\nclass Bar(models.Model):\n foo = models.ForeignKey(Foo)\n\nWhen using inlines of Bar in the Foo admin, Django has to save the Foo object first, because the Bar objects need the primary key to reference it in a ForeignKey:\nself.save_model(request, new_object, form, change... | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004916981_django_django_models_python.txt |
Q:
Where does easy_install install things?
I want to install sphinx, and the website says to use:
easy_install -U Sphinx
What will happen when I install this command? will I get the source also?
Where will it install?
A:
On Ubuntu I believe it installs to /usr/local/lib/python2.6/dist-packages/ and I believe it in... | Where does easy_install install things? | I want to install sphinx, and the website says to use:
easy_install -U Sphinx
What will happen when I install this command? will I get the source also?
Where will it install?
| [
"On Ubuntu I believe it installs to /usr/local/lib/python2.6/dist-packages/ and I believe it install the egg for it. -U denotes upgrading it if its already installed\n",
"/usr/lib/pythonx.y/site-packages\n\npythonx.y is your version of python. It could be python2.4, python2.7, python3.1, etc.\nIf you have multi... | [
6,
6,
5,
0
] | [] | [] | [
"easy_install",
"python"
] | stackoverflow_0004917190_easy_install_python.txt |
Q:
BadKeyError when posting keys from an HTML form
I'm trying to make a function in my app in which a user can associate a current location with their account. Users can add several Locations, and when a Location is added it is added as a child of that User. To allow the user to set their current location, I have cre... | BadKeyError when posting keys from an HTML form | I'm trying to make a function in my app in which a user can associate a current location with their account. Users can add several Locations, and when a Location is added it is added as a child of that User. To allow the user to set their current location, I have created a form in which they specify which location they... | [
"You need to include the complete stacktrace and the code where it includes to be certain, but it sounds like you're getting the exception when generating the form, not when submitting it. \nThe exception you're referring to occurs if you fetch the .key() from an object and attempt to call str() on it, when you hav... | [
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004888605_google_app_engine_google_cloud_datastore_python.txt |
Q:
How can I post a comment to a wordpress blog?
I have a django site that's tightly coupled with a wordpress blog. I want to have a form on the django site that posts comments (for moderation) to the wordpress blog.
I keep seeing references to comment apis and xmlrpc, so I feel like this should be possible.
1) what... | How can I post a comment to a wordpress blog? | I have a django site that's tightly coupled with a wordpress blog. I want to have a form on the django site that posts comments (for moderation) to the wordpress blog.
I keep seeing references to comment apis and xmlrpc, so I feel like this should be possible.
1) what POST / GET can I call, from python, to post a comm... | [
"I see that python-blogger project has friendly python wrapper over wordpress apis that you are looking for, there specifically is bug-report and a patch to have you post comment on the wordpress site using the wordpress XMLRPC call.\n"
] | [
3
] | [] | [] | [
"api",
"python",
"wordpress"
] | stackoverflow_0004917905_api_python_wordpress.txt |
Q:
How to check what permission failed in authorization in pyramid (pylons 2)?
I add a view for the forbidden view:
from pyramid.exceptions import Forbidden
config.add_view(forbidden_view, context=Forbidden)
which redirects to a log in screen.
But now i added some admin things which needed admin access, and I want t... | How to check what permission failed in authorization in pyramid (pylons 2)? | I add a view for the forbidden view:
from pyramid.exceptions import Forbidden
config.add_view(forbidden_view, context=Forbidden)
which redirects to a log in screen.
But now i added some admin things which needed admin access, and I want to just show a "you don't have the permission" screen, how do I check for that in ... | [
"I'm afraid that information is lost when Pyramid raises a Forbidden error as the result of a permission denial. There's an item in the TODO.txt to carry it along through the Forbidden error.\n"
] | [
3
] | [] | [] | [
"pylons",
"pyramid",
"python"
] | stackoverflow_0004916149_pylons_pyramid_python.txt |
Q:
Check if a user has a permission in pyramid (pylons 2)?
How do i check if a user has a permission in pyramid. For example, I want to show some HTML only if a user has some permission, but have the view available for everybody.
A:
The usual method is:
from pyramid.security import has_permission
has_permission('v... | Check if a user has a permission in pyramid (pylons 2)? | How do i check if a user has a permission in pyramid. For example, I want to show some HTML only if a user has some permission, but have the view available for everybody.
| [
"The usual method is:\nfrom pyramid.security import has_permission\nhas_permission('view', someresource, request)\n\nSee also http://docs.pylonsproject.org/projects/pyramid/1.0/narr/security.html#debugging-imperative-authorization-failures and http://docs.pylonsproject.org/projects/pyramid/1.0/api/security.html#pyr... | [
8
] | [] | [] | [
"pylons",
"pyramid",
"python"
] | stackoverflow_0004916127_pylons_pyramid_python.txt |
Q:
How to convert entire table from text to int
I have a txt file that I read with:
fdata =[]
with open(fn,'rb') as fo:
for i in xrange(1):
fo.next()
for line in fo:
data = line.split(',')
data = data[:23]
fdata.append(data)
print ... | How to convert entire table from text to int | I have a txt file that I read with:
fdata =[]
with open(fn,'rb') as fo:
for i in xrange(1):
fo.next()
for line in fo:
data = line.split(',')
data = data[:23]
fdata.append(data)
print fdata
I would like convert the entire table to n... | [
"To limit lines, try iterating using a counter and readlines():\nmaxlines = 100\nlines = f.readlines()\n\nif maxlines > len(lines): maxlines = len(lines)\n\nfor i in xrange(maxlines):\n line = lines[i]\n\n # Do your stuff...\n\nTo convert a string to a number (an integer in this case. float() is for floating poi... | [
2,
2
] | [] | [] | [
"int",
"python",
"text"
] | stackoverflow_0004918214_int_python_text.txt |
Q:
how to change the look of an image according to the season we like
We are working with Image magik and using python programming language.
We have been able to make some changes to the colours but it does not work for every image and at other times the entire image changes colour not just the required portions .
We... | how to change the look of an image according to the season we like | We are working with Image magik and using python programming language.
We have been able to make some changes to the colours but it does not work for every image and at other times the entire image changes colour not just the required portions .
We only want to change the colours and don't want to add any effects
These... | [
"For the expressions lambda i: i > 100 and 300 - It will return 300 if i is greater than 100 otherwise it will return False.\nFor the expression: lambda i: i < 100 and 300 - It will return 300 if i is lesser than 100 otherwise it will return False.\nThis is what you intended?\nFrom what I understand of your code re... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004918317_python.txt |
Q:
Bash or GoogleCL: new line in a string parameter
HI, I am using GoogleCL version 0.9.11 to upload videos to Youtube. My OS is CentOS 5.5 and Python 2.5.
One of the string parameters contain new line "\n", and it cant display properly.
google youtube post ~/videos/cat-falls-down-stairs.avi Comedy --tags "currency o... | Bash or GoogleCL: new line in a string parameter | HI, I am using GoogleCL version 0.9.11 to upload videos to Youtube. My OS is CentOS 5.5 and Python 2.5.
One of the string parameters contain new line "\n", and it cant display properly.
google youtube post ~/videos/cat-falls-down-stairs.avi Comedy --tags "currency of the internet" --summary "Poor whiskers takes a tumbl... | [
"You can use Bash's $'' construct to expand escape sequences before they are passed to googlecl.\ngoogle youtube post ~/videos/cat-falls-down-stairs.avi Comedy \\\n --tags 'currency of the internet' \\\n --summary $'Poor whiskers takes a tumble.\\nShe'\\''s fine, though, don'\\''t worry.'\n\n",
"Just put an... | [
9,
1,
0
] | [] | [] | [
"bash",
"command_line",
"python"
] | stackoverflow_0004918067_bash_command_line_python.txt |
Q:
Fast Bluetooth Name Lookup
I'm experiencing problems in fast detecting nearby bluetooth devices' names (human names, not BTADDR)
I found a very interesting Python-based project here [http://code.google.com/p/python-bluetooth-scanner/] but the issue basically is that, while looking for BTADDR and RSSI is fast, dete... | Fast Bluetooth Name Lookup | I'm experiencing problems in fast detecting nearby bluetooth devices' names (human names, not BTADDR)
I found a very interesting Python-based project here [http://code.google.com/p/python-bluetooth-scanner/] but the issue basically is that, while looking for BTADDR and RSSI is fast, detecting the "human" name of the de... | [
"Finding a remote device's friendly name is generally a two-step process. First, you perform an inquiry scan \"discovering\" nearby device that are discoverable. Second, you need to connect to \nthe remote device and \"ask\" it for its friendly name. Part of the delay comes from the fact that these two steps are of... | [
2
] | [] | [] | [
"bluetooth",
"discovery",
"python"
] | stackoverflow_0004897692_bluetooth_discovery_python.txt |
Q:
Django admin. Displaying a hierarchical dropdown filter
I have the following model:
from django.db import models
class State(models.Model):
name = models.CharField(max_length=30)
abbreviation = models.CharField(max_length=2)
def numberOfCities(self):
return self.city_set.count()
def __un... | Django admin. Displaying a hierarchical dropdown filter | I have the following model:
from django.db import models
class State(models.Model):
name = models.CharField(max_length=30)
abbreviation = models.CharField(max_length=2)
def numberOfCities(self):
return self.city_set.count()
def __unicode__(self):
return u"{0} - {1}".format(self.abbrev... | [
"It is not easy to bend the admin, but it is just another django app, albeit a really complex one. I usually do something like this:\n\nMake a custom admin template for the model in question (override the change_form.html).\nMake an ajax url that returns the City widget filtered by State id.\nUse something like jQu... | [
1,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004917893_django_django_admin_python.txt |
Q:
Regular expression for optionally matching the end of a string (optional $)
I'm looking to extract,
ID=(?P<group>.+?);
from a string, the 'ID=' is a constant, group can be anything. The match's position will vary in the string.
This is fine in most cases, however, occasionally the match will be at the end of the s... | Regular expression for optionally matching the end of a string (optional $) | I'm looking to extract,
ID=(?P<group>.+?);
from a string, the 'ID=' is a constant, group can be anything. The match's position will vary in the string.
This is fine in most cases, however, occasionally the match will be at the end of the string and the semi-colon will be missing. In this case, how do I optionally match... | [
"You can use (;|$) to match it. Or if you don't want a capture, (?:;|$)\n",
"if the option re.MUTILINE is NOT enabled ($ means end of string)\nID=(?P<group>)[^;]+\n\nif the option re.MUTILINE IS enabled ($ means end of line)\nID=(?P<group>)[^;\\r\\n]+\n\nWhat do you capture, by the way : what is between (?P<group... | [
30,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004918616_python_regex.txt |
Q:
Comparing/Clustering Trajectories (GPS data of (x,y) points) and Mining the data
I've got 2 questions on analyzing a GPS dataset.
1) Extracting trajectories I have a huge database of recorded GPS coordinates of the form (latitude, longitude, date-time). According to date-time values of consecutive records, I'm try... | Comparing/Clustering Trajectories (GPS data of (x,y) points) and Mining the data | I've got 2 questions on analyzing a GPS dataset.
1) Extracting trajectories I have a huge database of recorded GPS coordinates of the form (latitude, longitude, date-time). According to date-time values of consecutive records, I'm trying to extract all trajectories/paths followed by the person. For instance; say from t... | [
"Have a look at work done at Geography Department of University of Zurich, especially by Patrick Laube and Somayeh Dodge.\nHave a look at the paper\n\nIndividual Movements and Geographical Data Mining. Clustering\nAlgorithms for Highlighting Hotspots in Personal Navigation Routes\n\n(link, presentation). It showcas... | [
10,
1
] | [] | [] | [
"algorithm",
"data_mining",
"gis",
"gps",
"python"
] | stackoverflow_0004910510_algorithm_data_mining_gis_gps_python.txt |
Q:
Installing python with python win32 extensions on a network drive
I need to keep a large number of Windows XP machines running the same version of python, with an assortment of modules, one of which is python-win32. I thought about installing python on a network drive that is mounted by all the client machines, a... | Installing python with python win32 extensions on a network drive | I need to keep a large number of Windows XP machines running the same version of python, with an assortment of modules, one of which is python-win32. I thought about installing python on a network drive that is mounted by all the client machines, and just adjust the path on the clients. Python starts up fine from the... | [
"On every machine you have to basically run following pywin32_postinstall.py -install once. Assuming your python installation on the network is N:\\Python26, run following command on every client:\nN:\\Python26\\python.exe N:\\Python26\\Scripts\\pywin32_postinstall.py -install\n\nAnother important thing is Good Luc... | [
10,
1,
0
] | [] | [] | [
"networking",
"python",
"share",
"windows"
] | stackoverflow_0002319495_networking_python_share_windows.txt |
Q:
how do i keep track of title changes for firefox in ubuntu?
A lot of websites (like gmail, facebook) change the page title when a new notification arrives. For eg, when i get a new email my gmail page title changes to "Gmail - Inbox (1)". Is there a way to keep track of when this changes using bash or python ? Lik... | how do i keep track of title changes for firefox in ubuntu? | A lot of websites (like gmail, facebook) change the page title when a new notification arrives. For eg, when i get a new email my gmail page title changes to "Gmail - Inbox (1)". Is there a way to keep track of when this changes using bash or python ? Like a small code which runs in the background and keeps track of ti... | [
"What operating system? For the title on Unix you can poll for the X Window title using Xlib.\nSomething like this:\nfrom Xlib.display import Display\nfrom Xlib.Xatom import WINDOW\ndisplay = Display()\nroot = display.screen().root\nactive_id = root.get_full_property(_NET_ACTIVE_WINDOW, WINDOW).value[0]\nwindow = d... | [
0,
0
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0004918753_bash_python.txt |
Q:
Being able to detect int's in strings, Python
I'm trying to seperate a number from a string in python. Basically I want it so if color == 'gray' + a number, then it will return that number. For example if color equaled 'grey23', it would return 23. If color equaled 'grey', it would trigger the else statement.
p... | Being able to detect int's in strings, Python | I'm trying to seperate a number from a string in python. Basically I want it so if color == 'gray' + a number, then it will return that number. For example if color equaled 'grey23', it would return 23. If color equaled 'grey', it would trigger the else statement.
pseudo code:
# = an int
def func (color):
if c... | [
"import re\n\ndef func (color):\n try:\n return int(re.search('(\\d+)$',color).group(0)))\n except AttributeError:\n print 'pass'\n\n",
"You can use regular expressions for that:\nimport re\n\nmatches = re.match('\\w+(\\d+)', color)\nresult = matches.groups()\nif(len(result) > 0):\n return ... | [
4,
2,
1
] | [] | [] | [
"int",
"python",
"string"
] | stackoverflow_0004918817_int_python_string.txt |
Q:
Save two file filelds in a model at once
I have a model with 3 file fields, and manipulate them when .save is called. The problem is that saving any FileField triggers .save of the object. What can I do to save several FileFields at once?
class Record(Model):
name = CharField(max_length=30)
audio = FileFie... | Save two file filelds in a model at once | I have a model with 3 file fields, and manipulate them when .save is called. The problem is that saving any FileField triggers .save of the object. What can I do to save several FileFields at once?
class Record(Model):
name = CharField(max_length=30)
audio = FileField(upload_to=settings.AUDIO_ROOT)
alt_audi... | [
"There is an optional parameter when you call save. By default, commit is triggered, but if you do record.audio.save(\"audiofile.mp3\", File(open(path_to_audio)), False), save method won't be triggered.\n",
"Use .update, it will not trigger anything, when only on the database\nRecord.objects.filter(pk=record.pk).... | [
3,
1
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0004920053_django_django_models_django_orm_python.txt |
Q:
Problem reading text files without extensions in python
I have written a piece of a code which is supposed to read the texts inside several files which are located in a directory. These files are basically text files but they do not have any extensions.But my code is not able to read them:
corpus_path = 'Reviews/'... | Problem reading text files without extensions in python | I have written a piece of a code which is supposed to read the texts inside several files which are located in a directory. These files are basically text files but they do not have any extensions.But my code is not able to read them:
corpus_path = 'Reviews/'
for infile in glob.glob(os.path.join(corpus_path,'*.*')):
... | [
"Glob patterns don't work the same way as wildcards on the Windows platform. Just use * instead of *.*. i.e. os.path.join(corpus_path,'*'). Note that * will match every file in the directory - if that's not what you want then you can revise the pattern accordingly.\nSee the glob module documentation for more detail... | [
6,
5,
3,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004920542_file_python.txt |
Q:
Unable to Install pycrypto
ValueError: invalid version number '2.20.51.20100613'
I'm having problems installing pycrypto. Tried package manager: pip & easy_install, didn't work. Tried to manually install it via "python setup.py install", the same error like the above appears.
I've followed the instructions here a... | Unable to Install pycrypto | ValueError: invalid version number '2.20.51.20100613'
I'm having problems installing pycrypto. Tried package manager: pip & easy_install, didn't work. Tried to manually install it via "python setup.py install", the same error like the above appears.
I've followed the instructions here and got stuck at installing pycry... | [
"You can get working windows binaries on this page.\n"
] | [
2
] | [] | [] | [
"installation",
"mingw32",
"pycrypto",
"python",
"windows_7"
] | stackoverflow_0004920986_installation_mingw32_pycrypto_python_windows_7.txt |
Q:
python threads & sockets
I have a "I just want to understand it" question..
first, I'm using python 2.6.5 on Ubuntu.
So.. threads in python (via thread module) are only "threads", and is just tells the GIL to run code blocks from each "thread" in a certain period of time and so and so.. and there aren't actually r... | python threads & sockets | I have a "I just want to understand it" question..
first, I'm using python 2.6.5 on Ubuntu.
So.. threads in python (via thread module) are only "threads", and is just tells the GIL to run code blocks from each "thread" in a certain period of time and so and so.. and there aren't actually real threads here..
So the ques... | [
"Python uses \"real\" threads, i.e. threads of the underlying platform. On Linux, it will use the pthread library (if you are interested, here is the implementation).\nWhat is special about Python's threads is the GIL: A thread can only modify Python data structures if it holds this global lock. Thus, many Pytho... | [
12,
6,
5
] | [] | [] | [
"python",
"python_multithreading"
] | stackoverflow_0004920471_python_python_multithreading.txt |
Q:
how do i change templates on django admin pages?
i am walking through this tutorial for django
in the section: Customize the admin look and feel at the bottom it talks about taking files from the default installation of django, (such as: django/contrib/admin/templates) and applying it to your specific site.
it kee... | how do i change templates on django admin pages? | i am walking through this tutorial for django
in the section: Customize the admin look and feel at the bottom it talks about taking files from the default installation of django, (such as: django/contrib/admin/templates) and applying it to your specific site.
it keeps referring to:
/home/my_username/mytemplates
direct... | [
"I must defend the honor of the django docs!\n\"/home/my_username/mytemplates\", # Change this to your own directory.\n\nYou are supposed to replace it with your own directory, wherever that might be.\nYes, create a new directory and point to it in your settings.py\n\nBy default, TEMPLATE_DIRS is empty.\n So, let'... | [
6
] | [] | [] | [
"admin",
"django",
"python",
"templates"
] | stackoverflow_0004921080_admin_django_python_templates.txt |
Q:
Deleting row with Flask-SQLAlchemy
I'm trying to make a function to delete a record in my database with flask and the extension for SQLAlchemy. Problem is, instead of deleting just one row, it deletes all of them. Can someone tell me what's wrong with my code?
@app.route('/admin/delete/<int:page_id>', methods=['GE... | Deleting row with Flask-SQLAlchemy | I'm trying to make a function to delete a record in my database with flask and the extension for SQLAlchemy. Problem is, instead of deleting just one row, it deletes all of them. Can someone tell me what's wrong with my code?
@app.route('/admin/delete/<int:page_id>', methods=['GET','POST'])
@requires_auth
def delete_pa... | [
"I suspect that this line does not what you think.\n Page.query.get(page_id).query.delete()\n\nYou're getting a single instance (which you already did before), and by using query you actually issue a new query over all objects without filtering and therefore deleting all of them.\nProbably what you want to do is... | [
32
] | [] | [] | [
"flask",
"python",
"sqlalchemy"
] | stackoverflow_0004921038_flask_python_sqlalchemy.txt |
Q:
How do I add Python to WAMP or just Windows XP to make an Openlayers Build Profile?
I would like to use Python to run a profile building script for Openlayers.js. Here is the documentation page for the Openlayers profile builder. I wouldn't know where to begin.
A:
You should start with installing Python. It can ... | How do I add Python to WAMP or just Windows XP to make an Openlayers Build Profile? | I would like to use Python to run a profile building script for Openlayers.js. Here is the documentation page for the Openlayers profile builder. I wouldn't know where to begin.
| [
"You should start with installing Python. It can be downloaded here\nThen add location of your Python installation directory to PATH variable in Environment Variable so that python keyword can be globally accessed in command prompt.\nAfter that you should be able to follow instructions from OpenLayers tutorial that... | [
1
] | [] | [] | [
"openlayers",
"python",
"windows_xp"
] | stackoverflow_0004907392_openlayers_python_windows_xp.txt |
Q:
Problem with mod_wsgi
I installed my django project on Apache web server using mod_wsgi. I used a WSGIScriptAlias directive inside VirtualHost, pointing to a wsgi_handler.py file in my project. It worked fine.
Nevertheless, I had to write inside the wsgi_handler.py something like:
sys.append(absolute_file_path) i... | Problem with mod_wsgi | I installed my django project on Apache web server using mod_wsgi. I used a WSGIScriptAlias directive inside VirtualHost, pointing to a wsgi_handler.py file in my project. It worked fine.
Nevertheless, I had to write inside the wsgi_handler.py something like:
sys.append(absolute_file_path) in order to include some pyt... | [
"If using embedded mode of mod_wsgi you use WSGIPythonPath directive. If you are using daemon mode, you use the python-path option to the appropriate WSGIDaemonProcess directive.\nEnsure you are not using mod_wsgi 1.X and not using mod_python in same Apache.\n"
] | [
2
] | [] | [] | [
"mod_wsgi",
"python"
] | stackoverflow_0004910875_mod_wsgi_python.txt |
Q:
How to draw a line of characters in a grid (nested lists)
Given a w x h sized grid, produced in the following way
self.grid = [ ['-'] * self.w ] * self.h
I wish to "draw" a "line" of characters between two points in said grid. The following code is what I've come up with
def line( self, char, (x1, y1), (x2, y2) )... | How to draw a line of characters in a grid (nested lists) | Given a w x h sized grid, produced in the following way
self.grid = [ ['-'] * self.w ] * self.h
I wish to "draw" a "line" of characters between two points in said grid. The following code is what I've come up with
def line( self, char, (x1, y1), (x2, y2) ):
self.point( char, (x1, y1) )
x = x1 + cmp( x2, x1 )
... | [
"You should be using Bresenham's line algorithm, if you insist on programming this yourself at all. Furthermore, be careful about initialising the grid like this:\ngrid = [ ['-'] * self.w ] * self.h\n\nbecause of edning up with self.h copies of the same list:\ngrid = [ ['-'] * 3 ] * 3 \ngrid[0][0] = 'X'\nprint gri... | [
2
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0004922244_nested_lists_python.txt |
Q:
Django: How can I show a list of values in a text input field?
I have defined a Model with a ManyToManyField, and I want the field to show the values joined by spaces, for example:
<input type="text" name="foo" value="val1 val2 val3"/>
I have defined the form to use CharField to represent the multiple values:
cla... | Django: How can I show a list of values in a text input field? | I have defined a Model with a ManyToManyField, and I want the field to show the values joined by spaces, for example:
<input type="text" name="foo" value="val1 val2 val3"/>
I have defined the form to use CharField to represent the multiple values:
class MyForm(ModelForm):
foo = CharField(label='Foo')
class Met... | [
"You have a basic misunderstanding, which is that fields themselves aren't responsible for how they're rendered. That's what widgets do.\n",
"Ok, I finally figured it out:\nclass MultiValueTextWidget(TextInput):\n def _get_value(self, value):\n return \" \".join(value)\n\n def _format_value(self, val... | [
0,
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0004913967_django_forms_python.txt |
Q:
pyodbc.Error when trying to open jet database
I'm trying to read data stored in a ms access database that generated by a piece of software Hy Tek Meet Manager
import pyodbc
filename = 'db.mdb'
connection = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+filename)
cursor = conn.cursor()
When I run... | pyodbc.Error when trying to open jet database | I'm trying to read data stored in a ms access database that generated by a piece of software Hy Tek Meet Manager
import pyodbc
filename = 'db.mdb'
connection = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+filename)
cursor = conn.cursor()
When I run this code I get the error:
pyodbc.Error: ('IM002',... | [
"Based on one of your comments it sounds like you are using the EasySoft MS Access ODBC drivers. Referencing their support page, I would guess the following is what you want to use for your connection string:\nimport pyodbc\n\nfilename = 'db.mdb'\n\nconnection = pyodbc.connect('DRIVER={Easysoft ODBC-ACCESS}; MDBFI... | [
1
] | [] | [] | [
"ms_access",
"pyodbc",
"python"
] | stackoverflow_0004909812_ms_access_pyodbc_python.txt |
Q:
How do I do logging in a WSGI application across several processes?
I have a simple webservice written in Python WSGI, it's running in Apache and modwsgi using the WSGIDaemonProcess processes=4 directive.
How do I add logging? Obviously I can't log to the same file without some sort of mutex, but I don't want per... | How do I do logging in a WSGI application across several processes? | I have a simple webservice written in Python WSGI, it's running in Apache and modwsgi using the WSGIDaemonProcess processes=4 directive.
How do I add logging? Obviously I can't log to the same file without some sort of mutex, but I don't want performance degraded.
The logging can't block. As far as I know the standard... | [
"Direct logging output to sys.stderr. Doing that will see anything logged get routed into the internal Apache logging routines and into the Apache error logs. The way Apache does this works when done from multiple process at the same time.\n",
"Use SysLogHandler(NTEventLogHandler on Windows) or ConcurrentLogHandl... | [
1,
0
] | [
"Take a look at the logging module in the python docs. They allow for instance logging, so you just spawn a new instance from the log factory and a new file will be written to.\nhttp://docs.python.org/library/logging.html\n"
] | [
-1
] | [
"logging",
"python",
"wsgi"
] | stackoverflow_0004919133_logging_python_wsgi.txt |
Q:
Issues Viewing PDF's
Platform: Linux, GTK+
Tools: Python, PyGTK and Glade.
Problem:
I'd like to write a program that is capable of displaying a PDF file.
Question:
Which widget(s) and Python module(s) do I need?
Thanks for any suggestions!
A:
look into the python poppler bindings.
I render pdf files in a sim... | Issues Viewing PDF's | Platform: Linux, GTK+
Tools: Python, PyGTK and Glade.
Problem:
I'd like to write a program that is capable of displaying a PDF file.
Question:
Which widget(s) and Python module(s) do I need?
Thanks for any suggestions!
| [
"look into the python poppler bindings.\nI render pdf files in a simple dirty way. I copied the method used in the example for the python poppler gtk bindings\ndef load_pdf(self):\n self.doc = poppler.document_new_from_file (uri, None)\n # the number of pages in the pdf\n self.n_pgs = self.document.get_n_p... | [
2,
0
] | [
"http://pypi.python.org/pypi/ghostscript/\n"
] | [
-1
] | [
"glade",
"gtk",
"interface",
"pygtk",
"python"
] | stackoverflow_0004777898_glade_gtk_interface_pygtk_python.txt |
Q:
Starting a long running process on a server from a WSGI application
I need to start a long running process (30 min) via http and get status as it's running. The "process" is basically a Python script that updates a database. I have the following constraints:
Only one instance of the process can run at a time.
The... | Starting a long running process on a server from a WSGI application | I need to start a long running process (30 min) via http and get status as it's running. The "process" is basically a Python script that updates a database. I have the following constraints:
Only one instance of the process can run at a time.
The WSGI application is running in several interpreters, so I can't just mak... | [
"Isolate the process as a separate daemon, and use MQ or some other IPC to hand it jobs. Have it update a value in a database as it progresses, and read that value in a web page.\n",
"Look at using Celery (http://celeryproject.org/) and run the task outside of the Python web application processes.\n"
] | [
2,
1
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0004918867_python_wsgi.txt |
Q:
Problem with Python server and Ajax on Firefox
I have a simple Python server,
import BaseHTTPServer
import SimpleHTTPServer
PORT = 8080
class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.wfile.write("ok")
def start_server():
"""Start the server."""
server_ad... | Problem with Python server and Ajax on Firefox | I have a simple Python server,
import BaseHTTPServer
import SimpleHTTPServer
PORT = 8080
class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.wfile.write("ok")
def start_server():
"""Start the server."""
server_address = ("", PORT)
server = BaseHTTPServer.HTTPS... | [
"Can't you just serve the local file via the same small Python server on another URL? This will put them both in the same domain.\nIf you use Apache to serve your HTML page, you can proxy (see ProxyPass) your Python server so that it appears on the same domain and on the same port, just under different URL.\n"
] | [
0
] | [] | [] | [
"ajax",
"python"
] | stackoverflow_0004922680_ajax_python.txt |
Q:
Python Script for Encryption and Decryption of files
i was going through one of the python recipes in active state and found the following code. I've come up with the following 4 questions. Will be very grateful for any guidance and explanations.
Q::Im unable to exactly figure out as to why is a "key-random seed" ... | Python Script for Encryption and Decryption of files | i was going through one of the python recipes in active state and found the following code. I've come up with the following 4 questions. Will be very grateful for any guidance and explanations.
Q::Im unable to exactly figure out as to why is a "key-random seed" taken from the user at the first place in line "k=long(sys... | [
"random.seed(k) will set the random number generator to some state, that it will deliver the same list of random numbers for the same k.\nimport random\nprint [random.randint(0,255) for i in xrange(5)]\n\nreturns different numbers each time I run the script.\nimport random\nrandom.seed(2)\nprint [random.randint(0,2... | [
6
] | [] | [] | [
"cryptography",
"encryption",
"python"
] | stackoverflow_0004922779_cryptography_encryption_python.txt |
Q:
django authentication backend
I followed the method of extending the User class for implementing custom users in my application.
As mentioned in the link, custom authentication backend needs to be written in order to return the appropriate custom user class rather than User.
However I have more than one custom use... | django authentication backend | I followed the method of extending the User class for implementing custom users in my application.
As mentioned in the link, custom authentication backend needs to be written in order to return the appropriate custom user class rather than User.
However I have more than one custom users class, namely Student, Teacher,P... | [
"The only solution I could think of is to actually change the User model that django uses and add a content_type field that would tell you what type of user the actual user object is. Then you could directly query on that one. You'd still need 2 queries every time to fetch the correct user object.\nAlternatively yo... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004922623_django_python.txt |
Q:
In Python, how can I determine which class a method was declared in?
How can I get a reference to the class a method was declared in? In the code below, I'm trying to get a reference to Classical in test.
class Classical:
def method():
pass
def test(func):
# How can I get a reference to 'Classical... | In Python, how can I determine which class a method was declared in? | How can I get a reference to the class a method was declared in? In the code below, I'm trying to get a reference to Classical in test.
class Classical:
def method():
pass
def test(func):
# How can I get a reference to 'Classical' using only 'func'?
pass
test(Classical.method)
I've tried dir()ing... | [
"The function decorator test() is executed in the context of the class Classical while this class is being created. While executing the code in the class body, the class does not exist yet, so there is no means of accessing it. You should use a class decorator instead of a function decorator to work around this.\... | [
2
] | [] | [] | [
"decorator",
"introspection",
"python"
] | stackoverflow_0004922926_decorator_introspection_python.txt |
Q:
Django: model foreign key and a selectbox widget
I've 2 models Worker and Position when I add a new worker there should be selectbox with the positions listed in Positions model.
I tried to use Select widget but django fails with no such property exception.
Models
# Position model
class Position(models.Model):
... | Django: model foreign key and a selectbox widget | I've 2 models Worker and Position when I add a new worker there should be selectbox with the positions listed in Positions model.
I tried to use Select widget but django fails with no such property exception.
Models
# Position model
class Position(models.Model):
p_name = models.CharField(max_length = 40, uniqu... | [
"You could try just re-declaring the field for the form inside the form (making sure to use the same name as it is in the Model) and setting the widget and attrs in there?\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0004922252_django_django_admin_django_forms_python.txt |
Q:
How to tell BeautifulSoup to extract the content of a specific tag as text? (without touching it)
I need to parse an html document which contains "code" tags
I'm getting the code blocks like this:
soup = BeautifulSoup(str(content))
code_blocks = soup.findAll('code')
The problem is, if i have a code tag like this:... | How to tell BeautifulSoup to extract the content of a specific tag as text? (without touching it) | I need to parse an html document which contains "code" tags
I'm getting the code blocks like this:
soup = BeautifulSoup(str(content))
code_blocks = soup.findAll('code')
The problem is, if i have a code tag like this:
<code class="csharp">
List<Person> persons = new List<Person>();
</code>
BeautifulSoup forse the ... | [
"Add the code tag to the QUOTE_TAGS dictionary.\nfrom BeautifulSoup import BeautifulSoup\n\ncontent = \"<code class='csharp'>List<Person> persons = new List<Person>();</code>\"\n\nBeautifulSoup.QUOTE_TAGS['code'] = None\nsoup = BeautifulSoup(str(content))\ncode_blocks = soup.findAll('code')\n\nOutput:\n[<code class... | [
9
] | [] | [] | [
"beautifulsoup",
"python",
"syntax_highlighting"
] | stackoverflow_0004922969_beautifulsoup_python_syntax_highlighting.txt |
Q:
pygtk how to limit line length in gtk.TextView
I'm building a GUI in which I need to allow the user to enter text in a TextView, but I need to limit each line of text to 70 characters or less.
using python + pygtk.
Any tips are welcome.
A:
You can use the insert-text signal of GtkTextBuffer and remove the excess... | pygtk how to limit line length in gtk.TextView | I'm building a GUI in which I need to allow the user to enter text in a TextView, but I need to limit each line of text to 70 characters or less.
using python + pygtk.
Any tips are welcome.
| [
"You can use the insert-text signal of GtkTextBuffer and remove the excess characters.\nSample code in C:\nhttp://www.gtkforums.com/about1012.html\n"
] | [
0
] | [] | [] | [
"pygtk",
"python",
"user_interface"
] | stackoverflow_0004923122_pygtk_python_user_interface.txt |
Q:
App Engine: TypeError in handlers.py
I get a problem in a form handler in app engine (Python). Basically when I post the form to the handler I get the following traceback:
INFO 2011-02-07 14:06:59,364 dev_appserver.py:3317] "GET /favicon.ico HTTP/1.1" 404 -
Traceback (most recent call last):
File "/System/L... | App Engine: TypeError in handlers.py | I get a problem in a form handler in app engine (Python). Basically when I post the form to the handler I get the following traceback:
INFO 2011-02-07 14:06:59,364 dev_appserver.py:3317] "GET /favicon.ico HTTP/1.1" 404 -
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Version... | [
"The RequestHandler class has a method named error \nerror(code) \n\nA shortcut method for handlers to use to return an error response. Clears the response output stream and sets the HTTP error code to code. Equivalent to calling self.response.clear() and self.response.set_status(code).\n\nYour POST handler above o... | [
2
] | [] | [] | [
"google_app_engine",
"post",
"python",
"typeerror"
] | stackoverflow_0004922310_google_app_engine_post_python_typeerror.txt |
Q:
python : decode strings
Can someone give an advice of how to decode these strings?
They are parts of email subjects.
=?Windows-1251?B?ICLRLcvu5Obo8fLo6iI?=
=?koi8-r?B?5tLPzM/XwSDtwdLJzsEg98nUwczYxdfOwQ?=
=?Windows-1251?B?1PDu6+7i4CDM4PDo7eAgwujy4Ov85eLt4A?=
It's probably necessary to take inner part of string ICL... | python : decode strings | Can someone give an advice of how to decode these strings?
They are parts of email subjects.
=?Windows-1251?B?ICLRLcvu5Obo8fLo6iI?=
=?koi8-r?B?5tLPzM/XwSDtwdLJzsEg98nUwczYxdfOwQ?=
=?Windows-1251?B?1PDu6+7i4CDM4PDo7eAgwujy4Ov85eLt4A?=
It's probably necessary to take inner part of string ICLRLcvu5Obo8fLo6iI and then bas... | [
"test = [\n '=?Windows-1251?B?ICLRLcvu5Obo8fLo6iI?=',\n '=?koi8-r?B?5tLPzM/XwSDtwdLJzsEg98nUwczYxdfOwQ?=',\n '=?Windows-1251?B?1PDu6+7i4CDM4PDo7eAgwujy4Ov85eLt4A?='\n]\n\ndef decodeStr(s):\n s = s.split('?')\n enc = s[1]\n dat = s[3]\n\n return (dat+'===').decode('base-64').decode(enc)\n\nfor t... | [
4,
2
] | [] | [] | [
"base64",
"decode",
"python"
] | stackoverflow_0004923509_base64_decode_python.txt |
Q:
import modules in python
when i write import win32print in my python command line (IDLE) it works fine and it is imported...
but when i write import win32print in my py file then it gives an error
says no module named win32print
why am i not able to load the module when writing the same statement in a py script...... | import modules in python | when i write import win32print in my python command line (IDLE) it works fine and it is imported...
but when i write import win32print in my py file then it gives an error
says no module named win32print
why am i not able to load the module when writing the same statement in a py script...im using windows XP
| [
"Check if you are running on the same installation. I'd do that by looking the path:\nimport sys\nprint sys.path\n\nAnd compare the output on IDLE and when you run the .py\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0004923911_python.txt |
Q:
UnicodeDecodeError reading string in CSV
I'm having a problem reading some chars in python.
I have a csv file in UTF-8 format, and I'm reading, but when script read:
Preußen Münster-Kaiserslautern II
I get this error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/... | UnicodeDecodeError reading string in CSV | I'm having a problem reading some chars in python.
I have a csv file in UTF-8 format, and I'm reading, but when script read:
Preußen Münster-Kaiserslautern II
I get this error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Conte... | [
"Try the unicode_csv_reader() generator described in the csv module docs.\n"
] | [
7
] | [] | [] | [
"csv",
"python",
"unicode"
] | stackoverflow_0004923929_csv_python_unicode.txt |
Q:
Python bitmask (variable length)
in order to solve one research problem we have to organise the bitmask search in python.
As an input we have a raw data (we present it as a sequence of bits). Size is smth about 1,5Gb.
as an output we have to get the number of occurrence of a specific bitmasks.
Let me give an examp... | Python bitmask (variable length) | in order to solve one research problem we have to organise the bitmask search in python.
As an input we have a raw data (we present it as a sequence of bits). Size is smth about 1,5Gb.
as an output we have to get the number of occurrence of a specific bitmasks.
Let me give an example to discribe the situation
input: ... | [
"Your algorithm is the naive way to search for \"strings\" in data, but luckily there are much better algorithms.\nOne example is the KMP algorithm, but there are others that might fit your use case better. \nWith a better algorithm you can go from complexity of O(n*m) to O(n+m).\n",
"Where your mask is a multipl... | [
4,
3,
1
] | [] | [] | [
"bitmask",
"python"
] | stackoverflow_0004916170_bitmask_python.txt |
Q:
Decorating a class method after @property
I want to wrap every method of various objects except __init__ using a decorator.
class MyObject(object):
def method(self):
print "method called on %s" % str(self)
@property
def result(self):
return "Some derived property"
def my_decorator(fu... | Decorating a class method after @property | I want to wrap every method of various objects except __init__ using a decorator.
class MyObject(object):
def method(self):
print "method called on %s" % str(self)
@property
def result(self):
return "Some derived property"
def my_decorator(func):
def _wrapped(*args, **kwargs):
... | [
"There are a few other issues in this sample, but to atain to question, all you have to do\nis, when you are wrapping a property\nWhen you are wrapping a property, wrap its __get__ method instead:\nclass MyObject(object):\n\n def method(self):\n print \"method called on %s\" % str(self)\n\n @property\n... | [
6,
2,
0
] | [] | [] | [
"decorator",
"metaclass",
"python"
] | stackoverflow_0004923706_decorator_metaclass_python.txt |
Q:
Is there a way to change the Jinja2 template loading directory per-request?
Is there a way to change the Jinja2 root directory per-request on Flask? Right now I do:
app.jinja_loader = FileSystemLoader(template_directory)
but it seems to work only once per process (the process chooses the correct directory at firs... | Is there a way to change the Jinja2 template loading directory per-request? | Is there a way to change the Jinja2 root directory per-request on Flask? Right now I do:
app.jinja_loader = FileSystemLoader(template_directory)
but it seems to work only once per process (the process chooses the correct directory at first and then stays there, no matter how many changes I make)...
| [
"It turns out that a Jinja caching bug is preventing the correct template from loading, so disabling the cache works:\napp.jinja_env.cache = None\n\n",
"You can try this:\napp._get_current_object().jinja_loader = FileSystemLoader(template_directory)\n\nDocs http://flask.pocoo.org/docs/api/#notes-on-proxies or htt... | [
5,
0
] | [] | [] | [
"flask",
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0004921662_flask_google_app_engine_jinja2_python.txt |
Q:
Python regex - multiple search
Here is what I'm trying to accomplish:
Using python mechanize I open a site
If content does not match my regex I open another site
I perform searching using another regex
And the extracted code:
m = re.search('<td>(?P<alt>\d+)', response.read())
...
m = re.search('<td>(?P<alt>\w+)'... | Python regex - multiple search | Here is what I'm trying to accomplish:
Using python mechanize I open a site
If content does not match my regex I open another site
I perform searching using another regex
And the extracted code:
m = re.search('<td>(?P<alt>\d+)', response.read())
...
m = re.search('<td>(?P<alt>\w+)', response.read())
print m.group('al... | [
"Assuming response is a file-like object, calling read a second time might return a empty string as you consumed the file before.\ndata = response.read()\nm = re.search('<td>(?P<alt>\\d\\d*)', data)\nm = re.search('<td>(?P<alt>\\d\\d*)', data)\nprint m.group('alt')\n\nWhy would you call search multiple times?\n"
] | [
2
] | [] | [] | [
"mechanize",
"python",
"regex"
] | stackoverflow_0004924496_mechanize_python_regex.txt |
Q:
Google App Engine deferred.defer() failing when method returns
I'm trying to use google.appengine.ext.deferred to run a Task. I am passing a method to the defer() method, and that method runs successfully, but upon returning, a ValueError is thrown:
File ".../admin.py", line 73, in post
result = deferred.de... | Google App Engine deferred.defer() failing when method returns | I'm trying to use google.appengine.ext.deferred to run a Task. I am passing a method to the defer() method, and that method runs successfully, but upon returning, a ValueError is thrown:
File ".../admin.py", line 73, in post
result = deferred.defer(meeple_tasks.buildGames())
File "/Applications/GoogleAppEn... | [
"You should use:\nresult = deferred.defer(meeple_tasks.buildGames)\n\nIf you use buildGames(), that invokes the function right then and there, passing the return value to defer(). By removing the parenthesis, you pass the function itself to defer.\n",
"You need to call your deferred task like this:\n\ndeferred.de... | [
10,
2
] | [] | [] | [
"exception",
"google_app_engine",
"python",
"task"
] | stackoverflow_0004924648_exception_google_app_engine_python_task.txt |
Q:
Do nothing if RSS feed hasn't changed
I want to run a Python script every so many minutes. The script starts by fetching the newest article from a rss-feed (using feedparser). What I want, is when the newest article is the same as the last time it ran, the script just ends. How do I accomplish this?
A:
Since you... | Do nothing if RSS feed hasn't changed | I want to run a Python script every so many minutes. The script starts by fetching the newest article from a rss-feed (using feedparser). What I want, is when the newest article is the same as the last time it ran, the script just ends. How do I accomplish this?
| [
"Since you mention feedparser in a python question, I'll assume you mean feedparser.org\nIf yes, then the easiest way to do this is make the server do most of the work for you and only request updates since the last change you fetched: See ETag and Last-Modified headers for RSS feeds\n",
"You could store the stat... | [
5,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004924781_python.txt |
Q:
Why is my Django installation delivering an empty HTTP response?
Final Update: There was a stray LoadModule python_module modules/mod_python.so that conflicted with mod_wsgi. Removing that LoadModule made everything work again.
I am setting up a production server with Django and following along with the Django tu... | Why is my Django installation delivering an empty HTTP response? | Final Update: There was a stray LoadModule python_module modules/mod_python.so that conflicted with mod_wsgi. Removing that LoadModule made everything work again.
I am setting up a production server with Django and following along with the Django tutorial, yet receiving a blank page (or, as Chrome likes to report, Err... | [
"Make sure there are no conflicting modules installed in Apache. Specifically, check for mod_python or similar.\n"
] | [
3
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003375836_django_mod_wsgi_python.txt |
Q:
Django transactions locking tables
I need to upadte, add and delete rows from the auth.models.User table, unfortunately...
when I do so the table locks and I cannot perform any SELECT queries against the table.
I'm surrounding these queries by @transaction.commit_manually, which might have something to do with th... | Django transactions locking tables | I need to upadte, add and delete rows from the auth.models.User table, unfortunately...
when I do so the table locks and I cannot perform any SELECT queries against the table.
I'm surrounding these queries by @transaction.commit_manually, which might have something to do with the tables locking.
The transaction look l... | [
"Yes, you lock the tables on purpose. I would suggest studying transaction isolation because it is one of the core concepts of databases. \nAs for your problem, you could do several things, for both the UPDATE and the SELECT statements:\n\nYou could SET the transaction isolation level to something lower for the res... | [
2
] | [] | [] | [
"django",
"mysql",
"python",
"sql",
"sql_server"
] | stackoverflow_0004671523_django_mysql_python_sql_sql_server.txt |
Q:
How to make sure buildout doesn't use the already installed packages?
I am trying to switch fully to buildout - but our development environment already has lot of stuff installed in /usr/lib/pythonxx/
How can I make sure that buildout doesn't use the libraries installed on the system already - eventually without v... | How to make sure buildout doesn't use the already installed packages? | I am trying to switch fully to buildout - but our development environment already has lot of stuff installed in /usr/lib/pythonxx/
How can I make sure that buildout doesn't use the libraries installed on the system already - eventually without virtualenv ?
For example - how to avoid this behavior ? :
> cat buildout.cf... | [
"You can tell buildout if you want to use site-pakages or not with one of these two directives: include-site-packages and allowed-eggs-from-site-packages\nFrom buildout documentation:\n\nYou can then use include-site-packages\n = false and exec-sitecustomize = false buildout options to eliminate access\n to your ... | [
9,
3,
0
] | [] | [] | [
"buildout",
"django",
"python",
"virtualenv"
] | stackoverflow_0004839194_buildout_django_python_virtualenv.txt |
Q:
Error in python code
Please see the code and the error in the last.
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
import os
from brisa.upnp.device import Device, Service
from brisa.upnp.device.service import StateVariable
class BinaryLight(Device):
... | Error in python code | Please see the code and the error in the last.
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
import os
from brisa.upnp.device import Device, Service
from brisa.upnp.device.service import StateVariable
class BinaryLight(Device):
def __init__(self):
... | [
"This is not an error. On line 3 you are printing the object \"reactor\". \n",
"As others have mentioned, that's not an error. However, my guess would be that you have an error and something's going wrong somewhere or you wouldn't have bothered posting here. Try removing the print statement. Then let us know i... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004904502_python.txt |
Q:
How to apply regex to the content of a file?
I would like to apply regex to the content of a file without loading the entire file into a string. The RegexObject takes as its first argument a string or a buffer. Is there any way to turn the file into a buffer?
A:
Yes! Try mmap:
you can use the re module to sea... | How to apply regex to the content of a file? | I would like to apply regex to the content of a file without loading the entire file into a string. The RegexObject takes as its first argument a string or a buffer. Is there any way to turn the file into a buffer?
| [
"Yes! Try mmap:\n\nyou can use the re module to search through a memory-mapped file\n\n",
"Quote from Python doc:\n\nBuffer objects are not directly\n supported by Python syntax, but can be\n created by calling the built-in\n function buffer().\n\nAnd some other interesting part:\n\nbuffer(object[, offset[, si... | [
4,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004925371_python_regex.txt |
Q:
Searching through webpage
Hey I'm working on a Python project that requires I look through a webpage. I want to look through to find a specific text and if it finds the text, then it prints something out. If not, it prints out an error message. I've already tried with different modules such as libxml but I can't f... | Searching through webpage | Hey I'm working on a Python project that requires I look through a webpage. I want to look through to find a specific text and if it finds the text, then it prints something out. If not, it prints out an error message. I've already tried with different modules such as libxml but I can't figure out how I would do it.
Co... | [
"You could do something simple like:\n\nimport urllib2\nimport re\n\nhtml_content = urllib2.urlopen('http://www.domain.com').read()\n\nmatches = re.findall('regex of string to find', html_content);\n\nif len(matches) == 0: \n print 'I did not find anything'\nelse:\n print 'My string is in the html'\n\n",
"lxm... | [
4,
3
] | [] | [] | [
"find",
"python",
"search",
"text",
"webpage"
] | stackoverflow_0004925966_find_python_search_text_webpage.txt |
Q:
Calculating a timewindow with Python datetime
I'd like to query my DB for all records posted on a particular day (e.g. today between 00:00 and 23:59:59) given a datetime.datetime timestamp such as datetime.datetime(2010, 12, 21, 17, 59, 43, 85335).
What's the best method to calculate the start and end datetime.dat... | Calculating a timewindow with Python datetime | I'd like to query my DB for all records posted on a particular day (e.g. today between 00:00 and 23:59:59) given a datetime.datetime timestamp such as datetime.datetime(2010, 12, 21, 17, 59, 43, 85335).
What's the best method to calculate the start and end datetime.datetime instances, please? I'd like to end up with so... | [
"Ah, found what I want. I struggle with datetime every time.\n>>> timestamp = datetime.datetime.now()\n>>> timestamp\ndatetime.datetime(2010, 12, 21, 18, 31, 37, 900795)\n>>> timestamp.replace(hour=0, minute=0, second=0, microsecond=0)\ndatetime.datetime(2010, 12, 21, 0, 0)\n\n",
"If it's just calculating a day, ... | [
3,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004501372_datetime_python.txt |
Q:
Django: Filtering Annotated Results
I have two models:
class Status(models.Model):
title = models.CharField(max_length=32)
class Task(models.Model):
user = models.ForeignKey(User)
status = models.ForeignKey(Status, default=1)
title = models.CharField(max_length=128)
I want to create a nav list th... | Django: Filtering Annotated Results | I have two models:
class Status(models.Model):
title = models.CharField(max_length=32)
class Task(models.Model):
user = models.ForeignKey(User)
status = models.ForeignKey(Status, default=1)
title = models.CharField(max_length=128)
I want to create a nav list that contains all of the statuses I have in... | [
"This should give you a count of all Task objects belonging to the User by count.\nStatus.objects.filter(task__user=current_user).annotate(Count('task'))\n\nWhat do you mean adding a filter removes any zero statuses?\nAdding the user filter would get all Task objects that are associated with the User, regardless of... | [
0,
0,
0
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0004917243_django_django_orm_python.txt |
Q:
Need help for troubleshooting traceroute in Unix
I have a traceroute Python program for a Unix system that prints out the path the packets take to get from the local machine to a destination — that is, the sequence of routers that the packets go through. The problem is I get an output which displays:
traceroute to... | Need help for troubleshooting traceroute in Unix | I have a traceroute Python program for a Unix system that prints out the path the packets take to get from the local machine to a destination — that is, the sequence of routers that the packets go through. The problem is I get an output which displays:
traceroute to yahoo.co.in (68.180.206.184), 30 hops max, 60 byte pa... | [
"traceroute/tracert act differently on Linux and Windows.\nLinux will send a UDP packet with a decreasing TTL and listen for ICMP responses. Windows sends ICMP echo requests and listens for ICMP responses.\nThe Python version is failing because the UDP packets are being blocked.\n\nOn Unix-like operating systems, t... | [
2
] | [] | [] | [
"python",
"traceroute",
"unix"
] | stackoverflow_0004888333_python_traceroute_unix.txt |
Q:
IE 8 Crashes when displaying PDF in IFrame served from Django
I have a web application which displays pdf's in an IFrame. I recently made a change to start serving up the PDF using Django instead of allowing Apache to serve the PDF. Initially, I used the FileWrapper approach to return the file. This worked fine on... | IE 8 Crashes when displaying PDF in IFrame served from Django | I have a web application which displays pdf's in an IFrame. I recently made a change to start serving up the PDF using Django instead of allowing Apache to serve the PDF. Initially, I used the FileWrapper approach to return the file. This worked fine on all browsers except for IE 8 which crashed (maybe other versions o... | [
"The solution was to use mod_xsendfile as suggested in this post with the following tweaks:\nmimeType,_ = mimetypes.guess_type(filePath)\nresponse = django.http.HttpResponse(mimetype = mimeType)\nresponse['Accept-Ranges'] = 'bytes'\nresponse['X-Sendfile'] = filePath\nreturn response\n\nIn addition to working correc... | [
3
] | [] | [] | [
"apache",
"django",
"internet_explorer",
"python"
] | stackoverflow_0004926355_apache_django_internet_explorer_python.txt |
Q:
How to define findAll for html nested tags using beautifulsoup
Given
<a href="www.example.com/"></a>
<table class="theclass">
<tr><td>
<a href="www.example.com/two">two</a>
</td></tr>
<tr><td>
<a href ="www.example.com/three">three</a>
<span>blabla<span>
</td></td>
</table>
How can I scrape only the that is in... | How to define findAll for html nested tags using beautifulsoup | Given
<a href="www.example.com/"></a>
<table class="theclass">
<tr><td>
<a href="www.example.com/two">two</a>
</td></tr>
<tr><td>
<a href ="www.example.com/three">three</a>
<span>blabla<span>
</td></td>
</table>
How can I scrape only the that is inside table class="the class"? I tried using
soup = util.mysoupopen(t... | [
"If I understood your question. That's the python code which should work. Iterating to find all tables with the class=\"theclass\", then finding links inside.\n>>> foo = \"\"\"<a href=\"www.example.com/\"></a>\n... <table class=\"theclass\">\n... <tr><td>\n... <a href=\"www.example.com/two\">two</a>\n... </td></tr>... | [
4,
2
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0004925341_beautifulsoup_html_python.txt |
Q:
Best way to mix and match components in a python app
I have a component that uses a simple pub/sub module I wrote as a message queue. I would like to try out other implementations like RabbitMQ. However, I want to make this backend change configurable so I can switch between my implementation and 3rd party modules... | Best way to mix and match components in a python app | I have a component that uses a simple pub/sub module I wrote as a message queue. I would like to try out other implementations like RabbitMQ. However, I want to make this backend change configurable so I can switch between my implementation and 3rd party modules for cleanliness and testing.
The obvious answer seems to... | [
"One thing I've done before is to create a common class that each specific implementation inherits from. Then there's a spec that can easily be followed, and each implementation can avoid repeating certain code they'll all share.\nThis is a bad example, but you can see how you could make the saver object use any of... | [
2
] | [] | [] | [
"architecture",
"composition",
"python"
] | stackoverflow_0004926338_architecture_composition_python.txt |
Q:
Circumstantial python script, need to use results from previous runs
Ok, I'm sure there may be plenty of ways to do this but I'm asking because I don't know where to start looking for a way to do this. I have a python script that runs some basic bash commands and based on the output will send an email to a given e... | Circumstantial python script, need to use results from previous runs | Ok, I'm sure there may be plenty of ways to do this but I'm asking because I don't know where to start looking for a way to do this. I have a python script that runs some basic bash commands and based on the output will send an email to a given email address. I want to make it so that an email will only be sent if that... | [
"The shelve module offers a very simple persistent dictionary in Python.\nhttp://docs.python.org/library/shelve.html\n",
"I suggest you go straight to using Pickle or JSON, you get a lot more flexibility than shelve. Note that this code would work nearly identically with Pickle, JSON or Yaml.\nBasically you'd wri... | [
5,
1
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0004926147_python_scripting.txt |
Q:
_URLFetchResult object has no attribute 'body' when calling Freebase via Python Module
I've been using the Freebase Python module successfully to read data, and today I started testing writing data to Freebase.
But I keep getting an error that isn't making sense to me:
Within the same scope of code, I can perform ... | _URLFetchResult object has no attribute 'body' when calling Freebase via Python Module | I've been using the Freebase Python module successfully to read data, and today I started testing writing data to Freebase.
But I keep getting an error that isn't making sense to me:
Within the same scope of code, I can perform an mqlread(query) without error.
But when I try:
freebase.mqlwrite(query)
I get an error li... | [
"It turns out this is a bug in Freebase-Python. I've filed the bug and offered a solution: http://code.google.com/p/freebase-python/issues/detail?id=15\n"
] | [
0
] | [] | [] | [
"freebase",
"httprequest",
"python"
] | stackoverflow_0004926422_freebase_httprequest_python.txt |
Q:
Escape from html %20
I'm working on something in Python and I need to escape from %20, the space in a URL. For example:
"%20space%20in%20%d--" % ordnum
So I need to use %20 for a URL but then %d for a number. But I get this error:
TypeError: not enough arguments for format string
I know what the problem is I just ... | Escape from html %20 | I'm working on something in Python and I need to escape from %20, the space in a URL. For example:
"%20space%20in%20%d--" % ordnum
So I need to use %20 for a URL but then %d for a number. But I get this error:
TypeError: not enough arguments for format string
I know what the problem is I just don't know how to escape f... | [
"One way would be to double the % characters:\n\"%%20space%%20in%%20%d--\" % ordnum\n\nbut a probably better way is using urllib.quote_plus():\nurllib.quote_plus(\" space in %d--\" % ordnum)\n\n",
"The %20 should look like %%20 when Python's formatter sees it. To Python, %% formats out to %.\n",
">>> import ur... | [
6,
4,
1,
0
] | [] | [] | [
"escaping",
"format_string",
"python",
"string"
] | stackoverflow_0004927018_escaping_format_string_python_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.