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 for UPnp- Compatible with windows
Please advice me some framework that can be run on windows with linux commands. I can install the framework with linux commands, so i need some framework where I can write protocols for UPnP. I want to write protocols in python and Python-Brisa supports only LINUX commands ... | python for UPnp- Compatible with windows | Please advice me some framework that can be run on windows with linux commands. I can install the framework with linux commands, so i need some framework where I can write protocols for UPnP. I want to write protocols in python and Python-Brisa supports only LINUX commands to install it.
| [
"If you need a Linux-like environment in your windows, look into Cygwin.\n"
] | [
0
] | [] | [] | [
"frameworks",
"python",
"upnp",
"windows"
] | stackoverflow_0004854524_frameworks_python_upnp_windows.txt |
Q:
Declarative SQLAlchemy CREATE SQLITE in memory tables
This is how I setup my database for an application (in Flask):
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import scoped_session, create_session
from sqlalchemy.ext.declarative import declarative_base
engine = None
db_session = scoped_sessi... | Declarative SQLAlchemy CREATE SQLITE in memory tables | This is how I setup my database for an application (in Flask):
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import scoped_session, create_session
from sqlalchemy.ext.declarative import declarative_base
engine = None
db_session = scoped_session(lambda: create_session(bind=engine,
... | [
"The code you posted doesn't contain any table/class declaration. Are you sure that the declaration is done before init_engine() is called?\n"
] | [
4
] | [] | [] | [
"declarative",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0004840324_declarative_python_sqlalchemy_sqlite.txt |
Q:
How to separate read db server and write db server on django 0.97?
I am using Django 0.97 version with postgresql 9.0. I have configured hot streaming replication on a master db server and a slave db server. My application has heavy bot-driven writes on the DB and reads only from the users. So, it makes it very op... | How to separate read db server and write db server on django 0.97? | I am using Django 0.97 version with postgresql 9.0. I have configured hot streaming replication on a master db server and a slave db server. My application has heavy bot-driven writes on the DB and reads only from the users. So, it makes it very optimized if I make the read-access slave db for the users' and write-acce... | [
"Your best bet is to upgrade to 1.2 as it will be significantly less work than hacking together features that already exist. If you stick with 0.97 for much longer your life will only be more difficult down the road.\nI'm guessing you may have some misconceptions on how using multiple DBs works in Django 1.2. You... | [
1
] | [] | [] | [
"django",
"django_models",
"postgresql",
"python",
"scalability"
] | stackoverflow_0004848333_django_django_models_postgresql_python_scalability.txt |
Q:
How to call Unix command through pyjamas
I am trying to create web based system using pyjamas and hangs on one functionality.
The functionality is, to click a button and it should run some python programs in back-end. I have to display the logs generated by back-end python program in the same page(where the clicke... | How to call Unix command through pyjamas | I am trying to create web based system using pyjamas and hangs on one functionality.
The functionality is, to click a button and it should run some python programs in back-end. I have to display the logs generated by back-end python program in the same page(where the clicked button is).
I really appreciate your help gu... | [
"There is a tutorial on how to use Pyjamas with AJAX on this page of of Pyjamas book.\n"
] | [
2
] | [] | [] | [
"pyjamas",
"python"
] | stackoverflow_0004849722_pyjamas_python.txt |
Q:
Python: Cut and Paste Data on Text File.
I have a text file that contains numbers.
I need to move some of the numbers from the beginning of the file to the end in the correct order.
For example, the Original TEXT file has the following content: 0123456789.
I need to move the first 4 numbers to the end in the sam... | Python: Cut and Paste Data on Text File. | I have a text file that contains numbers.
I need to move some of the numbers from the beginning of the file to the end in the correct order.
For example, the Original TEXT file has the following content: 0123456789.
I need to move the first 4 numbers to the end in the same order so it'll look like this:
4567890123.
U... | [
"See the Python tutorial (section \"Strings\"; search for \"slice notation\"):\n>>> a = \"0123456789\"\n>>> b = a[4:] + a[:4]\n>>> b\n'4567890123'\n\nOr what is it you're really trying to do?\n",
"The individual characters of the string a = '0123456789' can be accessed through a[i], where for i=0 you get the char... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0004854605_python.txt |
Q:
Creating a system-independent minimal Python footprint in Linux
My intention is to try to compile such a Linux Python minimal base, that is totally portable, and system-independent (meaning that it doesn't even interacts with the system-installed Python base at all).
It was done with relative ease under Windows, h... | Creating a system-independent minimal Python footprint in Linux | My intention is to try to compile such a Linux Python minimal base, that is totally portable, and system-independent (meaning that it doesn't even interacts with the system-installed Python base at all).
It was done with relative ease under Windows, having nothing but the Python binary files, and a minimal, yet custom ... | [
"Using --prefix as you yourself suggested works. I compiled Python 2.7.1 with --prefix=/usr/local, and running the resultant binary results in:\nPython 2.7.1 (r271:86832, Jan 31 2011, 11:06:01) \n[GCC 4.5.1 20100924 (Red Hat 4.5.1-4)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more inf... | [
2
] | [] | [] | [
"linux",
"portable_executable",
"python"
] | stackoverflow_0004854787_linux_portable_executable_python.txt |
Q:
Can I use Python Exceptions to handle the aftermath of SIGHUP signals for a daemon?
I'm writing a simple little file-syncing daemon in python to implement a synchronised file system between a primary and secondary machine. Most of the heavy lifting is done by rsync.
On the primary side it periodically calls rsync ... | Can I use Python Exceptions to handle the aftermath of SIGHUP signals for a daemon? | I'm writing a simple little file-syncing daemon in python to implement a synchronised file system between a primary and secondary machine. Most of the heavy lifting is done by rsync.
On the primary side it periodically calls rsync and sleeps for a few seconds before repeating. On the secondary side it spawns rsyncd wit... | [
"You should raise a fsync_config_exception instance, not the class. (Instantiate it using its __init__() signature)\nHowever, I do not suggest raising asynchronous exceptions in that manner. You'll have a hard time guaranteeing that the exception is only raised when it can be properly handled. It's also not a go... | [
2
] | [] | [] | [
"daemon",
"exception",
"python",
"signals"
] | stackoverflow_0004854894_daemon_exception_python_signals.txt |
Q:
Buildout: Including another Python project via mercurial?
I have a project called Foo/ that has buildout.cfg and setup.py. Now there is another project called Bar/ .. which too has buildout.cfg and setup.py. Since Bar/ depends on various Python modules, it has install_requires=['lxml', 'SQLAlchemy'] in its setup.p... | Buildout: Including another Python project via mercurial? | I have a project called Foo/ that has buildout.cfg and setup.py. Now there is another project called Bar/ .. which too has buildout.cfg and setup.py. Since Bar/ depends on various Python modules, it has install_requires=['lxml', 'SQLAlchemy'] in its setup.py. Foo/ depends on Bar/.
But Bar/ does not have a release yet. ... | [
"The only way I found to go around this issue is by adding extra-paths to buildout :\n[buildout]\nparts = ... pyrtm ...\ndevelop = . parts/pyrtm\neggs = pyrtm\n\nextra-paths = parts/pyrtm/src\n# or wherever your pyrtm folder \n# could as well be extra-paths = pyrtm/ \n# if you your code is on same path as buildout.... | [
1,
0
] | [
"You're using mercurial recipe to make a mercurial checkout of the mercurial recipe that you want to use as a development egg.... There's a huge circular dependency in there.\nBuildout needs the mercurial recipe to run the \"mr\" part. So it grabs the recipe from pypi. It doesn't yet know that the recipe will actua... | [
-1
] | [
"buildout",
"mercurial",
"python"
] | stackoverflow_0002150887_buildout_mercurial_python.txt |
Q:
Recovering from ECONNRESET in Python/Mechanize
I've got a large bulk downloading application written in Python/Mechanize, aiming to download something like 20,000 files. Clearly, any downloader that big is occasionally going to run into some ECONNRESET errors. Now, I know how to handle each of these individually... | Recovering from ECONNRESET in Python/Mechanize | I've got a large bulk downloading application written in Python/Mechanize, aiming to download something like 20,000 files. Clearly, any downloader that big is occasionally going to run into some ECONNRESET errors. Now, I know how to handle each of these individually, but there's two problems with that:
I'd really ra... | [
"Perhaps place the try..except block higher up in the chain of command:\nimport collections\ndef download_file(url):\n # Bundle together the bunch of browser calls necessary to download one file.\n browser.follow_link(...)\n ...\n response=browser.response()\n data=response.read()\n\nurls=collections... | [
2
] | [] | [] | [
"error_handling",
"mechanize",
"python",
"tcp"
] | stackoverflow_0004854809_error_handling_mechanize_python_tcp.txt |
Q:
Text Parsing Design
Let's say I have a paragraph of text like so:
Snails can be found in a very wide
range of environments including
ditches, deserts, and the abyssal
depths of the sea. Numerous kinds of snail can
also be found in fresh waters. (source)
I have 10,000 regex rules to match text, which can ... | Text Parsing Design | Let's say I have a paragraph of text like so:
Snails can be found in a very wide
range of environments including
ditches, deserts, and the abyssal
depths of the sea. Numerous kinds of snail can
also be found in fresh waters. (source)
I have 10,000 regex rules to match text, which can overlap. For example, the... | [
"I'm assuming that your regex does not cross between multiple sentences. In that case you could\n1) break your text into array of sentences\n2) for each sentence simply record which (id) regex have matched.\n3) when you would like to see the match - run the regex again.\n\n\"Store less / compute more\" solution.\n"... | [
1,
1
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0004855302_nlp_python.txt |
Q:
Acquiring the global interpreter lock from python
Is it possible to acquire the global interpreter lock from python code? Or is that purely implemented in the C side?
A:
If your code executes then you have the GIL, no need to acquire it manually.
| Acquiring the global interpreter lock from python | Is it possible to acquire the global interpreter lock from python code? Or is that purely implemented in the C side?
| [
"If your code executes then you have the GIL, no need to acquire it manually.\n"
] | [
7
] | [] | [] | [
"gil",
"multithreading",
"python"
] | stackoverflow_0004855903_gil_multithreading_python.txt |
Q:
Client-PC to Home-PC
Any method for the client-pc to directly contact the home-pc to exchange or give data to a python script in the home-pc?
Thanks
A:
http://twistedmatrix.com
Although without more information in terms of what you're trying to do exactly, it'll be hard to help further.
Twisted should give you t... | Client-PC to Home-PC | Any method for the client-pc to directly contact the home-pc to exchange or give data to a python script in the home-pc?
Thanks
| [
"http://twistedmatrix.com\nAlthough without more information in terms of what you're trying to do exactly, it'll be hard to help further.\nTwisted should give you the framework you need to build a solid networked environment in Python though.\n"
] | [
0
] | [] | [] | [
"ajax",
"python"
] | stackoverflow_0004855981_ajax_python.txt |
Q:
How to get zipcode - timezone data using python?
I am looking for a python package which can provide functionality like the following -
timezone = foo.gettimezoneinfo(zipcode)
date_time = foo.convert_time(datetime object, zipcode)
Is there any such package available? If not, how can I implement one? Any zipcode -... | How to get zipcode - timezone data using python? | I am looking for a python package which can provide functionality like the following -
timezone = foo.gettimezoneinfo(zipcode)
date_time = foo.convert_time(datetime object, zipcode)
Is there any such package available? If not, how can I implement one? Any zipcode - timezone database is available to use?
I need to use ... | [
"Take a look at pyzipcode. It was updated on 2010-09-06 so I would assume that is pretty accurate. I have never used it but, it looks pretty simplistic. If you run into issues; I can test it out and post some source code.\nThe Basic Usage section has some code that I believe will satisfy your query.\n"
] | [
2
] | [] | [] | [
"datetime",
"localization",
"python"
] | stackoverflow_0004855278_datetime_localization_python.txt |
Q:
Python CSV reader isn't reading CSV data the way I expect
I'm trying to read some CSV data into an array. I can probably explain what I'm trying to do better in Python than in English:
>>> line = ImportFile.objects.all().reverse()[0].file.split("\n")[0]
>>> line
'"007147","John Smith","100 Farley Ln","","Berlin NH... | Python CSV reader isn't reading CSV data the way I expect | I'm trying to read some CSV data into an array. I can probably explain what I'm trying to do better in Python than in English:
>>> line = ImportFile.objects.all().reverse()[0].file.split("\n")[0]
>>> line
'"007147","John Smith","100 Farley Ln","","Berlin NH 03570","Berlin","NH",2450000,"John",24643203,3454,"E","",23450... | [
"You are using StringIO in the wrong way. Try\ns = cStringIO.StringIO(line)\nr = csv.reader(s)\nnext(r)\n# \"['007147', 'John Smith', '100 Farley Ln', '', 'Berlin NH 03570', 'Berlin', 'NH', '2450000', 'John', '24643203', '3454', 'E', '', '2345071', '1201', 'N', '15465', 'I', '.00', '20102456', '945610', '20247320'... | [
6,
0
] | [] | [] | [
"csv",
"django",
"python"
] | stackoverflow_0004856172_csv_django_python.txt |
Q:
What on earth...? File permissions from files created by Python C code
If I have the following C code:
int main(int argc, char **arg)
{
int x = open("testfilefromc", O_RDWR | O_CREAT);
return 0;
}
which when I compile and run not unreasonably creates this:
-rw-r----- 1 joewass staff 0B 31 Jan 21:17... | What on earth...? File permissions from files created by Python C code | If I have the following C code:
int main(int argc, char **arg)
{
int x = open("testfilefromc", O_RDWR | O_CREAT);
return 0;
}
which when I compile and run not unreasonably creates this:
-rw-r----- 1 joewass staff 0B 31 Jan 21:17 testfilefromc
But the following C code, compiled into a Python module:
con... | [
"The function open takes three arguments. If you specify the O_CREAT flag, you need to call it with this signature:\nint open(const char *pathname, int flags, mode_t mode);\n\nOtherwise the behaviour is undefined. It's very unlikely for the creation of the file in your first example to work at all. Also take a look... | [
6
] | [] | [] | [
"c",
"cpython",
"distutils",
"python"
] | stackoverflow_0004856284_c_cpython_distutils_python.txt |
Q:
Adding to an array every 1 second in python
Can anyone please help me to add to an array every second? thanks.
A:
You can simply do time.sleep(secs) to create a delay in a script.
import time
ls = []
add = True
while add:
ls.append(0)
time.sleep(1)
A:
For 10 times a second, use a float in sleep
from t... | Adding to an array every 1 second in python | Can anyone please help me to add to an array every second? thanks.
| [
"You can simply do time.sleep(secs) to create a delay in a script.\nimport time\n\nls = []\nadd = True\nwhile add:\n ls.append(0)\n time.sleep(1)\n\n",
"For 10 times a second, use a float in sleep\nfrom time import sleep\nwhile True:\n y.append(k[3])\n sleep(0.1)\n\n"
] | [
2,
0
] | [] | [] | [
"python",
"timer"
] | stackoverflow_0004856373_python_timer.txt |
Q:
RESTful APIs for Django projects/apps
What do you prefer when you want to "RESTify" your Django project in Django?
I came to the conclusion that there are really three options to do that:
django-piston http://bitbucket.org/jespern/django-piston/wiki/Home
django-rest-interface http://code.google.com/p/django-rest-... | RESTful APIs for Django projects/apps | What do you prefer when you want to "RESTify" your Django project in Django?
I came to the conclusion that there are really three options to do that:
django-piston http://bitbucket.org/jespern/django-piston/wiki/Home
django-rest-interface http://code.google.com/p/django-rest-interface/
django-restful-resources http://... | [
"I'm most familiar with django-piston, so I would naturally steer you in that direction.\nA quick glance at the other two, though, indicates that django-rest-interface does nothing more than expose models as resources, and that django-restful-resources is some guy's one-off attempt at the same.\nPiston, if I recall... | [
7,
5,
3,
2
] | [] | [] | [
"api",
"django",
"django_piston",
"python",
"rest"
] | stackoverflow_0004233754_api_django_django_piston_python_rest.txt |
Q:
In Django, when someone uploads a text file, how do I turn it into a String?
thefile = request.FILES.get("uploaded_file","")
Now, how do I turn that into a string of text?
A:
You should be able to read it.
thefile.read()
| In Django, when someone uploads a text file, how do I turn it into a String? | thefile = request.FILES.get("uploaded_file","")
Now, how do I turn that into a string of text?
| [
"You should be able to read it.\nthefile.read()\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004856527_django_python.txt |
Q:
Any way to suppress/ignore specific types of errors when using BeautifulSoup
There are many elements that I need on each page I scrape, but many pages don't have all the items I need, so I end up having to wrap each and every item grab in
try:
itemNeeded = soup.find(text="yada yada yada").next
except Attribute... | Any way to suppress/ignore specific types of errors when using BeautifulSoup | There are many elements that I need on each page I scrape, but many pages don't have all the items I need, so I end up having to wrap each and every item grab in
try:
itemNeeded = soup.find(text="yada yada yada").next
except AttributeError:
pass
This balloons my code by 400%.
Is there any way to abstract this ... | [
"Build a list and iterate over the list... Use some templating.. You just need to figure out how to iterate over the whole page, in a smaller, simpler fashion.\ntext_list = ['items', 'to', 'search', 'for']\npre_find = {'items': (('span', 'nav'), 'a', ('manufacturer', 'model'))}\ncarDict = {}\nfor text in text_lis... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping"
] | stackoverflow_0004856071_beautifulsoup_python_screen_scraping.txt |
Q:
ruby fetching url content is always empty
I am so frustrated trying to use Ruby to fetch a specific url content.
I've tried many different ways like open-uri, standard request none worked so far. I always get empty html. I also tried to use python to fetch the same url which always returned the correct html conten... | ruby fetching url content is always empty | I am so frustrated trying to use Ruby to fetch a specific url content.
I've tried many different ways like open-uri, standard request none worked so far. I always get empty html. I also tried to use python to fetch the same url which always returned the correct html content. I am really not sure why... Please help as I... | [
"If that is your exact code it is invalid for several reasons. \n\nhttp: should be http://\nURL needs a path. if you want the root page of example.com it needs to be http://example.com/ the trailing slash is significant.\nif you put 2 lines of code on one line you need to use ; to denote the end of the first line... | [
5,
2
] | [] | [] | [
"http",
"python",
"ruby",
"url"
] | stackoverflow_0004856240_http_python_ruby_url.txt |
Q:
How do I pipe a subprocess call to a text file?
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.
How do I pipe this to a text file also? (And also print, i... | How do I pipe a subprocess call to a text file? | subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.
How do I pipe this to a text file also? (And also print, if possible)
| [
"If you want to write the output to a file you can use the stdout-argument of subprocess.call.\nIt takes either\n\nNone (the default, stdout is inherited from the parent (your script))\nsubprocess.PIPE (allows you to pipe from one command/process to another)\na file object or a file descriptor (what you want, to ha... | [
244,
24
] | [] | [] | [
"python",
"shell",
"subprocess"
] | stackoverflow_0004856583_python_shell_subprocess.txt |
Q:
Symmetric matrices in numpy?
I wish to initiate a symmetric matrix in python and populate it with zeros.
At the moment, I have initiated an array of known dimensions but this is unsuitable for subsequent input into R as a distance matrix.
Are there any 'simple' methods in numpy to create a symmetric matrix?
Edit
I... | Symmetric matrices in numpy? | I wish to initiate a symmetric matrix in python and populate it with zeros.
At the moment, I have initiated an array of known dimensions but this is unsuitable for subsequent input into R as a distance matrix.
Are there any 'simple' methods in numpy to create a symmetric matrix?
Edit
I should clarify - creating the 'sy... | [
"I don't think it's feasible to try work with that kind of triangular arrays.\nSo here is for example a straightforward implementation of (squared) pairwise Euclidean distances:\ndef pdista(X):\n \"\"\"Squared pairwise distances between all columns of X.\"\"\"\n B= np.dot(X.T, X)\n q= np.diag(B)[:, None]\n... | [
3
] | [] | [] | [
"matrix",
"numpy",
"python",
"symmetric"
] | stackoverflow_0004856090_matrix_numpy_python_symmetric.txt |
Q:
How to package a module with my python script
I just wrote a python script to fix some database issues and it uses the psycopg2 module. For some reason the person that needs to run it (on the server) is claiming that they can't install psycopg2 on their server machine... is there a way that I can package that modu... | How to package a module with my python script | I just wrote a python script to fix some database issues and it uses the psycopg2 module. For some reason the person that needs to run it (on the server) is claiming that they can't install psycopg2 on their server machine... is there a way that I can package that module within my script such that they don't have to ha... | [
"Make a directory, put your script into it.\ncd into that directory, then run:\n$ easy_install -Z --prefix . psycopg2\n\nThat should result in a copy of the python module in the same directory.\nZip it all up and send the whole thing off.\n",
"As to be unable to install psycopg2, I sure it relates to security pol... | [
1,
0
] | [] | [] | [
"packaging",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0004855629_packaging_postgresql_psycopg2_python.txt |
Q:
Python - iterate through list in threaded script
I am trying to write a threaded Python script which will iterate through a list of urls and open each one in a separate thread.
from BeautifulSoup import BeautifulSoup
from threading import Thread
import mechanize
tickers = ["aapl", "siri", "goog", "intc"]
nextTick... | Python - iterate through list in threaded script | I am trying to write a threaded Python script which will iterate through a list of urls and open each one in a separate thread.
from BeautifulSoup import BeautifulSoup
from threading import Thread
import mechanize
tickers = ["aapl", "siri", "goog", "intc"]
nextTicker = 0
def quotes(i):
br = mechanize.Browser()
... | [
"If you want thread specific data, pass it in the arguments.\nSo use tickers[i] instead of tickers[nextTicker]\nBetter yet, use \nfor ticker in tickers:\n t = Thread(target = quotes, args = (ticker,) )\n\nPossibly better yet, checkout eventlet. It allows writing code like this but avoids some of the problems with... | [
3,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004856843_multithreading_python.txt |
Q:
Parsing CSV data from memory in Python
Is there a way to parse CSV data in Python when the data is not in a file? I'm storing CSV data in my database and I'd like to parse it. I'm looking for something analogous to Ruby's CSV.parse. I know Python has a CSV class but everything I've seen in the docs seems to deal w... | Parsing CSV data from memory in Python | Is there a way to parse CSV data in Python when the data is not in a file? I'm storing CSV data in my database and I'd like to parse it. I'm looking for something analogous to Ruby's CSV.parse. I know Python has a CSV class but everything I've seen in the docs seems to deal with files as opposed to in-memory CSV data.
... | [
"There is no special distinction for files about the python csv module. You can use StringIO to wrap your strings as file-like objects.\n",
"Here is why you should use cStringIO.StringIO (io.StringIO in Python 3.x) instead of some DIY kludge:\n>>> import csv\n>>> from cStringIO import StringIO\n>>> fromDB = '\"Co... | [
9,
3,
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004855523_csv_python.txt |
Q:
String of values separated by commas or semicolons into a Python list
I'm reading a list of email addresses from a config file. The addresses can be delimited by comma or semicolon - e.g.,
billg@microsoft.com,steve@apple.com, dhh@37signals.com
billg@microsoft.com;steve@apple.com; dhh@37signals.com
I'd like to g... | String of values separated by commas or semicolons into a Python list | I'm reading a list of email addresses from a config file. The addresses can be delimited by comma or semicolon - e.g.,
billg@microsoft.com,steve@apple.com, dhh@37signals.com
billg@microsoft.com;steve@apple.com; dhh@37signals.com
I'd like to get rid of any whitespace around the email addresses too.
I need to get them... | [
"In this case I whould use the re module\n>>> import re\n>>> \n>>> data = \"billg@microsoft.com;steve@apple.com; dhh@37signals.com\"\n>>> stuff = re.split(r\"\\s*[,;]\\s*\", data.strip())\n\n",
"Regular expressions are powerful, and probably the way to go here; but for something as simple as this, string methods... | [
10,
6,
1,
1,
1,
0
] | [
"\ndef gen_list(file_path):\n read= open(file_path, \"r\")\n split1= read.split(\";\")\n new_list= []\n for i in split1:\n split2 = i.split(\",\")\n split_list = [item.strip() for item in split2 if \"@\" in item]\n new_list.extend(split_list)\n return new_list\n\n#\nThis works fo... | [
-1
] | [
"list",
"python",
"string"
] | stackoverflow_0004854341_list_python_string.txt |
Q:
Word wrapping in a ListCtrl (or ObjectListView)
I have a wxListCtrl (Actually it's an ObjectListView), set with LC_REPORT with two columns.
Is it possible to word wrap the first column of text when it reaches the end of the column?
A:
It's not possible with a ObjectListView (see their FAQ), because ListCtrl does... | Word wrapping in a ListCtrl (or ObjectListView) | I have a wxListCtrl (Actually it's an ObjectListView), set with LC_REPORT with two columns.
Is it possible to word wrap the first column of text when it reaches the end of the column?
| [
"It's not possible with a ObjectListView (see their FAQ), because ListCtrl doesn't support multiline entries.\nIt is possible, however, using UltimateListCtrl\nimport wx\nfrom wx.lib.wordwrap import wordwrap\nimport wx.lib.agw.ultimatelistctrl as ULC \n\nclass Frame(wx.Frame):\n def __init__(self, *args, **kw)... | [
2,
0
] | [] | [] | [
"objectlistview",
"python",
"word_wrap",
"wxpython",
"wxwidgets"
] | stackoverflow_0004733549_objectlistview_python_word_wrap_wxpython_wxwidgets.txt |
Q:
How come I can't implement Django's forget password feature?
Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{'uidb36': '1', 'token': '2u6-e139d87034d52a80c572'}' not found.
I already did this correctly:
(r'^password/reset/?$',password_reset ),
(r'^passwor... | How come I can't implement Django's forget password feature? | Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{'uidb36': '1', 'token': '2u6-e139d87034d52a80c572'}' not found.
I already did this correctly:
(r'^password/reset/?$',password_reset ),
(r'^password/reset/done/?$',password_reset_done ),
(r'^password/reset/confirm... | [
"Django is passing arguments itself; you need to accept them and pass them to the reset form.\nTo be really clear about what the error message is saying, it is expecting a url for the view, 'django.contrib.auth.views.password_reset_confirm', and that url MUST accept the arguments provided, in this case 'uidb36' and... | [
11,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004825910_django_python.txt |
Q:
virtualenv macosX --no-site-package ignored
I'm having problems with macOSX and virtualenv. It seems to ignore --no-site-package.
Using exactly the same commands with linux (archlinux) it works. It it macOSX 10.5 with python 2.5
curl -o virtualenv.py 'http://bitbucket.org/ianb/virtualenv/raw/tip/virtualenv.py
Cre... | virtualenv macosX --no-site-package ignored | I'm having problems with macOSX and virtualenv. It seems to ignore --no-site-package.
Using exactly the same commands with linux (archlinux) it works. It it macOSX 10.5 with python 2.5
curl -o virtualenv.py 'http://bitbucket.org/ianb/virtualenv/raw/tip/virtualenv.py
Create a new environment
python virtualenv.py --no-s... | [
"It also could be that the easy_install version was too old.\nI'd suggest using pip:\neasy_install pip\npip install virtualenv -U\nvirtualenv env\nsource env/bin/activate\npip -E env install cherrypy\n\n"
] | [
1
] | [] | [] | [
"macos",
"python",
"virtualenv"
] | stackoverflow_0002990945_macos_python_virtualenv.txt |
Q:
Pylucene in Python 2.6 + MacOs Snow Leopard
Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld... | Pylucene in Python 2.6 + MacOs Snow Leopard | Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/bui... | [
"I had to adjust line 44 to 49 in the Makefile to get pylucene to install correctly:\nPREFIX_PYTHON=/my/virtualenv\nANT=ant\nPYTHON=$(PREFIX_PYTHON)/bin/python\n# add .__main__ to default configuration!\n# --arch depends on your architecture of course\nJCC=$(PYTHON) -m jcc.__main__ --shared --arch x86_64 ... | [
1,
0
] | [] | [] | [
"jcc",
"lucene",
"macos",
"pylucene",
"python"
] | stackoverflow_0001527332_jcc_lucene_macos_pylucene_python.txt |
Q:
What is the Python version of a MATLAB structure array
I am new to Python. I want to put the result of a SQL query in a sort of matrix variable like the structure array of MATLAB. Basically a matrix that holds numbers and strings.
The variable then holds the rows and columns of the query.
How can I do this?
Thanks... | What is the Python version of a MATLAB structure array | I am new to Python. I want to put the result of a SQL query in a sort of matrix variable like the structure array of MATLAB. Basically a matrix that holds numbers and strings.
The variable then holds the rows and columns of the query.
How can I do this?
Thanks.
| [
"If you want just matrices and vectors like MATLAB, your best bet is NumPy (and SciPy if you want more MATLABby features)\nAlso if you want to make sexy plots, I recommend Matplotlib.\n",
"I trust you have already discovered MySQLdb for getting the stuff from the database into Python. That will by default return ... | [
3,
2,
1
] | [] | [] | [
"matlab",
"matrix",
"python",
"variables"
] | stackoverflow_0004844377_matlab_matrix_python_variables.txt |
Q:
Python Regex Help
I am trying to sort through HTML tags and I can't seem to get it right.
What I have done so far
import urllib
import re
s = raw_input('Enter URL: ')
f = urllib.urlopen(s)
s = f.read()
f.close
r = re.compile('<TAG\b[^>]*>(.*?)</TAG>',)
result = re.findall(r, s)
print(result)
Where I replace "... | Python Regex Help | I am trying to sort through HTML tags and I can't seem to get it right.
What I have done so far
import urllib
import re
s = raw_input('Enter URL: ')
f = urllib.urlopen(s)
s = f.read()
f.close
r = re.compile('<TAG\b[^>]*>(.*?)</TAG>',)
result = re.findall(r, s)
print(result)
Where I replace "TAG" with tag I want to... | [
"You should really try using libraries which can perform HTML parsing out of the box. Beautiful Soup is one of my favorites.\n",
"I'm not entirely clear on what you are trying to achieve with the regex. Capturing the contents between two div tags for instance works with\nre.compile(\"<div.*?>.*?</div>\")\n\nAltho... | [
5,
1,
1
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0004856600_html_python_regex.txt |
Q:
Python performance improvement request for winkler
I'm a python n00b and I'd like some suggestions on how to improve the algorithm to improve the performance of this method to compute the Jaro-Winkler distance of two names.
def winklerCompareP(str1, str2):
"""Return approximate string comparator measure (between 0... | Python performance improvement request for winkler | I'm a python n00b and I'd like some suggestions on how to improve the algorithm to improve the performance of this method to compute the Jaro-Winkler distance of two names.
def winklerCompareP(str1, str2):
"""Return approximate string comparator measure (between 0.0 and 1.0)
USAGE:
score = winkler(str1, str2)
ARGUM... | [
"I focused more on optimizing to get more out of Python than on optimizing the algorithm because I don't think that there is much of an algorithmic improvement to be had here. Here are some Python optimizations that I came up with.\n(1). Since you appear to be using Python 2.x, change all range()'s to xrange()'s. r... | [
4,
4,
0
] | [] | [] | [
"jaro_winkler",
"optimization",
"performance",
"python"
] | stackoverflow_0002741872_jaro_winkler_optimization_performance_python.txt |
Q:
Python: Downloading files from HTTP server
I have written some python scripts to download images off an HTTP website, but because I'm using urllib2, it closes the existing connection and then opens another before opening another. I don't really understand networking all that much, but this probably slows things do... | Python: Downloading files from HTTP server | I have written some python scripts to download images off an HTTP website, but because I'm using urllib2, it closes the existing connection and then opens another before opening another. I don't really understand networking all that much, but this probably slows things down considerably, and grabbing 100 images at a ti... | [
"since you asked for an httplib snippet:\nimport httplib\n\nimages = ['img1.png', 'img2.png', 'img3.png']\n\nconn = httplib.HTTPConnection('www.example.com')\n\nfor image in images:\n conn.request('GET', '/images/%s' % image)\n resp = conn.getresponse()\n data = resp.read()\n with open(image, 'wb') as f... | [
2,
1,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0004855810_http_python.txt |
Q:
Django ForeignKey _set on an inherited model
I have two models Category and Entry. There is another model ExtEntry that inherits from Entry
class Category(models.Model):
title = models.CharField('title', max_length=255)
description = models.TextField('description', blank=True)
...
class Entry(models.M... | Django ForeignKey _set on an inherited model | I have two models Category and Entry. There is another model ExtEntry that inherits from Entry
class Category(models.Model):
title = models.CharField('title', max_length=255)
description = models.TextField('description', blank=True)
...
class Entry(models.Model):
title = models.CharField('title', max_l... | [
"\nI need another method to get all ExtEntryrelated to one particular Category\n\nEasy:\nExtEntry.objects.filter(categories=my_category)\n\n\n\nDo you know if there is a way to use the _set feature of an inherited\n\nI don't know if there is a direct they for that. It is not mentioned in documentation.\nBut it is p... | [
4,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004856887_django_django_models_python.txt |
Q:
Can str() fail in Python?
Are there any cases where str() throws an exception in Python?
A:
Yes, it can fail for custom classes:
>>> class C(object):
... def __str__(self):
... return 'oops: ' + oops
...
>>> c = C()
>>> str(c)
NameError: global name 'oops' is not defined
It can even fail for some of... | Can str() fail in Python? | Are there any cases where str() throws an exception in Python?
| [
"Yes, it can fail for custom classes:\n>>> class C(object):\n... def __str__(self):\n... return 'oops: ' + oops\n...\n>>> c = C()\n>>> str(c)\nNameError: global name 'oops' is not defined\n\nIt can even fail for some of the built-in classes, such as unicode:\n>>> u = u'\\xff'\n>>> s = str(u)\nUnicodeEnc... | [
17,
11,
4
] | [] | [] | [
"python"
] | stackoverflow_0004857592_python.txt |
Q:
best practice for django request.method methods
I'm building a REST api and one of the methods from my view needs to accept the following http methods
GET
POST
DELETE
PUT
What is the best practice to achieve this ?
So far I came up with the following
with_id_storage = {
'GET' : _with_id_get,
'POST' : _with_id... | best practice for django request.method methods | I'm building a REST api and one of the methods from my view needs to accept the following http methods
GET
POST
DELETE
PUT
What is the best practice to achieve this ?
So far I came up with the following
with_id_storage = {
'GET' : _with_id_get,
'POST' : _with_id_post,
'PUT' : _with_id_put,
'DELETE': _with_id_del... | [
"Consider using django-piston. It does what you're asking for (and much more).\n"
] | [
3
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004857613_django_django_views_python.txt |
Q:
How to highlight a single cell in pygtk table?
Can anyone tell how to highlight a single cell in pygtk table?
A:
Which "table" are you using?
GtkTable is a layout container and doesn't really have any selection.
GtkTreeView only allows selecting whole rows, although it can place the focus on a particular cell us... | How to highlight a single cell in pygtk table? | Can anyone tell how to highlight a single cell in pygtk table?
| [
"Which \"table\" are you using?\nGtkTable is a layout container and doesn't really have any selection.\nGtkTreeView only allows selecting whole rows, although it can place the focus on a particular cell using gtk.TreeView.set_cursor.\nGtkSheet is a spreadsheet widget which allows you to actually select a single cel... | [
1
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0004850981_gtk_python.txt |
Q:
Multi-thread a download loop with python
I have a list.
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'rx', 'jnj', 'osip')
URL = "http://www.Xxxx_symbol=%s"
def fetch(symbols):
try:
url = URL % '+'.join(symbols)
fp = urllib2.urlopen(url)
try:
data = fp.read()
fin... | Multi-thread a download loop with python | I have a list.
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'rx', 'jnj', 'osip')
URL = "http://www.Xxxx_symbol=%s"
def fetch(symbols):
try:
url = URL % '+'.join(symbols)
fp = urllib2.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return da... | [
"This should get you started:\nfrom threading import Thread, Lock\n\ndata = {}\ndata_lock = Lock()\n\nclass Fetcher(Thread):\n def __init__(self, symbol):\n super(Thread, self).__init__()\n Thread.__init__(self)\n self.symbol = symbol\n\n def run(self):\n # put the code from fetch(... | [
4
] | [] | [] | [
"fetch",
"loops",
"multithreading",
"python"
] | stackoverflow_0004857731_fetch_loops_multithreading_python.txt |
Q:
Main functions, pythonic?
I am just getting into Python coding and I'm wondering which is considered more pythonic?
Example A: An obvious main method.
#!/usr/bin/env python -tt
import random
def dice_roll(num=1):
for _ in range(num):
print("Rolled a", random.randrange(1,7,1))
def main()
random.s... | Main functions, pythonic? | I am just getting into Python coding and I'm wondering which is considered more pythonic?
Example A: An obvious main method.
#!/usr/bin/env python -tt
import random
def dice_roll(num=1):
for _ in range(num):
print("Rolled a", random.randrange(1,7,1))
def main()
random.seed()
try:
num = in... | [
"A is better because it allows you to import your module and execute the stuff in main without having to funk about with things unnecessarily. In fact, that might be a good reason to name it something better than main if it really represents an actual function of your module.\n",
"Well, when it comes to being Py... | [
9,
3,
1
] | [] | [] | [
"program_entry_point",
"python"
] | stackoverflow_0004857899_program_entry_point_python.txt |
Q:
PySide / PyQt QStyledItemDelegate list in table
I'm trying to create a table of lists in Python with Qt (PySide/PyQt - matters not) and my lists are squashed into the table cells.
Is there a way to get the list delegates to 'pop out' of their cells? I've attached a simple code snippet - replace PySide with PyQt4 d... | PySide / PyQt QStyledItemDelegate list in table | I'm trying to create a table of lists in Python with Qt (PySide/PyQt - matters not) and my lists are squashed into the table cells.
Is there a way to get the list delegates to 'pop out' of their cells? I've attached a simple code snippet - replace PySide with PyQt4 depending on your preference
from PySide import QtCore... | [
"So the answer is to use\nQComboBox\n\nrather than \nQListWidget\n\nso line 6 becomes\neditor = QtGui.QComboBox(parent)\n\nand all is right with the world. Hope this helps someone...\n"
] | [
2
] | [] | [] | [
"pyqt",
"pyside",
"python"
] | stackoverflow_0004857274_pyqt_pyside_python.txt |
Q:
Restrict a regex to only search between two points
How do I restrict which parts of the text are searched using regular expressions? Given the example below, say I wanted to get the details of customer02. If I use
Name:\s*(.+)
then obviously I will get 3 results. So I want to restrict it to only search under the ... | Restrict a regex to only search between two points | How do I restrict which parts of the text are searched using regular expressions? Given the example below, say I wanted to get the details of customer02. If I use
Name:\s*(.+)
then obviously I will get 3 results. So I want to restrict it to only search under the details for customer02 and stop when it gets to customer... | [
"This is not a problem regular expressions are meant to solve. Your best bet is to parse out the data into structures first (possibly using regexs to aid in \"chunking\" the data).\n",
"What format is the data in? Is it a string? If efficiency is not a major issue, the obvious thing would be to slice the string:\... | [
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004830995_python_regex.txt |
Q:
evaluating a complex conditional python
show_prev_btn = (len(sessions) > 0 and (sessions[0].pk == \
Session.objects.filter(user=request.user).first().pk))
I have this boolean that I'm calculating. Sessions is a list and if it has 0 elements, sessions[0] will raise an exception. Fortunately, I think that I can... | evaluating a complex conditional python | show_prev_btn = (len(sessions) > 0 and (sessions[0].pk == \
Session.objects.filter(user=request.user).first().pk))
I have this boolean that I'm calculating. Sessions is a list and if it has 0 elements, sessions[0] will raise an exception. Fortunately, I think that I can catch it before it's evaluated by checking l... | [
"In Python, the and operator is defined to use short-circuit evaluation. So if you have an expression like \na() and b()\n\nthen first a() will be called. Only if that returns True, will b() be called. If a() returns False, then b() will not be called, so you can do things in b() that might crash if a() is False.\n... | [
5,
0,
0
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0004858102_conditional_python.txt |
Q:
Testing python code
I want to test a python code that gets inputs from a different function (eg MeasureRadius). MeasureRadius is not ready because it relies on an instrument that I haven't receive yet. What's the best way to test CalculateArea with different values on iRadius, and iErrorCode outputted from Measure... | Testing python code | I want to test a python code that gets inputs from a different function (eg MeasureRadius). MeasureRadius is not ready because it relies on an instrument that I haven't receive yet. What's the best way to test CalculateArea with different values on iRadius, and iErrorCode outputted from MeasureRadius? An automated way ... | [
"You need a \"Mock fixture\" that replaces the Instrument class.\nYou also need to redesign CalculateArea so it's testable.\ndef CalculateArea( someInstrument ):\n iRadius, iErrorCode, sErrorMsg = someInstrument.measureRadius()\n # rest of this is the same.\n\nclass MockInstrument( object ):\n def __init__... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004858152_python.txt |
Q:
python 3: class "template" (function that returns a parameterized class)
I am trying to create a function that is passed a parameter x and returns a new class C. C should be a subclass of a fixed base class A, with only one addition: a certain class attribute is added and is set to equal x.
In other words:
class C... | python 3: class "template" (function that returns a parameterized class) | I am trying to create a function that is passed a parameter x and returns a new class C. C should be a subclass of a fixed base class A, with only one addition: a certain class attribute is added and is set to equal x.
In other words:
class C(A):
C.p = x # x is the parameter passed to the factory function
Is this ea... | [
"First off, note that the term \"class factory\" is somewhat obsolete in Python. It's used in languages like C++, for a function that returns a dynamically-typed instance of a class. It has a name because it stands out in C++; it's not rare, but it's uncommon enough that it's useful to give the pattern a name. I... | [
27,
12
] | [] | [] | [
"class_design",
"factory_pattern",
"python",
"python_3.x"
] | stackoverflow_0004858298_class_design_factory_pattern_python_python_3.x.txt |
Q:
How much information does the deferred library allow a packaged function access to?
I know that if I defer a function and pass some args to it, the function has those args and can work with them, but can a function that's part of an instanced object (for example) access the variables of its object?
class foo (obje... | How much information does the deferred library allow a packaged function access to? | I know that if I defer a function and pass some args to it, the function has those args and can work with them, but can a function that's part of an instanced object (for example) access the variables of its object?
class foo (object):
def __init__ (self):
self.bar = 42
def do_work (self):
self.... | [
"If you pass in an instance method, as you are in your code sample, the entire instance will be serialized and passed around. Any objects that your foo object refers to will also be serialized, and so forth. Any global state - for example, module level and class level variables - will not be preserved, so it'll be ... | [
3
] | [] | [] | [
"deferred_execution",
"google_app_engine",
"oop",
"python"
] | stackoverflow_0004855855_deferred_execution_google_app_engine_oop_python.txt |
Q:
Python + GNU Plot: dealing with missing values
For clarity I have isolated my problem and used a small but complete snippet to describe it.
I have a bunch of data but there is a lot of missing pieces. I want to ignore these (a break in the graph if it were a line graph). I have set "?" to be the symbol for missing... | Python + GNU Plot: dealing with missing values | For clarity I have isolated my problem and used a small but complete snippet to describe it.
I have a bunch of data but there is a lot of missing pieces. I want to ignore these (a break in the graph if it were a line graph). I have set "?" to be the symbol for missing data. Here is my snippet:
import math
import Gnuplo... | [
"Gnuplot is calling numpy.asarray to convert your Python list into a numpy array.\nUnfortunately, this command (with dtype=numpy.float32) is incompatible with a Python list that contains strings.\nYou can reproduce the error like this:\nIn [36]: np.asarray(['?',1.0,2.0],np.float32)\n--------------------------------... | [
4
] | [] | [] | [
"gnuplot",
"python"
] | stackoverflow_0004858394_gnuplot_python.txt |
Q:
Loop a string search until a string is found python
I thought this would be easy, after 3 hours of searching and trial and error it appears not to be easy.
All I want to do is loop a search for a string until the string is found. I'm searching a log file for a string that appears when a condition arises e.g. when... | Loop a string search until a string is found python | I thought this would be easy, after 3 hours of searching and trial and error it appears not to be easy.
All I want to do is loop a search for a string until the string is found. I'm searching a log file for a string that appears when a condition arises e.g. when the string "function test 1" appears in the log I need t... | [
"Nice code Andrew. I wasn't informed of the existence of the for/else possibility.\nBut to temper the activity of machine's processes, it is possible to avoid repeated opening and closing of the file, and it is preferable to cool down the frequency of the verification IMO\nfrom time import sleep\n\nwith open(WebPat... | [
4,
1,
1
] | [] | [] | [
"file_io",
"python",
"search",
"string"
] | stackoverflow_0004857942_file_io_python_search_string.txt |
Q:
Problem setting up unit testing when using app engine patch on google app engine
I'm having a lot of trouble writing unit tests for my app engine patch solution.
I've asked this question on experts exchange (http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_26509115.html) but it's been there... | Problem setting up unit testing when using app engine patch on google app engine | I'm having a lot of trouble writing unit tests for my app engine patch solution.
I've asked this question on experts exchange (http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_26509115.html) but it's been there for two weeks with no answer - hopefully the SO crew can improve on that!!
I've tried... | [
"I haven't used nose-aep. We use nosetests with the google-app-engine plugin. It was very easy to set up, basically by following the links provided at the bottom. Sorry I can't help with your specific question using nose-aep. Good luck.\nComplete overview, including how to install:\nhttp://www.cuberick.com/2008... | [
0
] | [] | [] | [
"app_engine_patch",
"google_app_engine",
"python"
] | stackoverflow_0003918306_app_engine_patch_google_app_engine_python.txt |
Q:
PyInstaller error with email module
First create a script named test.py, with one line in it:
from email.MIMEMultipart import MIMEMultipart
Save it and run makespec.py and build.py, then I get the test.exe. This is what I get while running test.exe:
F:\SW\trunk\test\dist>test.exe
Traceback (most recent call last)... | PyInstaller error with email module | First create a script named test.py, with one line in it:
from email.MIMEMultipart import MIMEMultipart
Save it and run makespec.py and build.py, then I get the test.exe. This is what I get while running test.exe:
F:\SW\trunk\test\dist>test.exe
Traceback (most recent call last):
File "<string>", line 1, in <module>
... | [
"I should use from email.mime.multipart import MIMEMultipart. \nIt has been answered in the mailgroups ages ago, and it was the first hit when I google \"pyinstaller, email\". It's such a shame I didn't check it more carefully.\n"
] | [
2
] | [] | [] | [
"email",
"pyinstaller",
"python"
] | stackoverflow_0004848705_email_pyinstaller_python.txt |
Q:
What to chose for my next project with Amazon Web Services (Linux)? Ruby/Python/other, MySQL/PostgreSQL/other
I will soon start a new project with Amazon Web Services, on Linux
They have frameworks available for PHP, Ruby, Python, Java and .Net
http://aws.amazon.com/ruby/
http://aws.amazon.com/python/
I am fluent ... | What to chose for my next project with Amazon Web Services (Linux)? Ruby/Python/other, MySQL/PostgreSQL/other | I will soon start a new project with Amazon Web Services, on Linux
They have frameworks available for PHP, Ruby, Python, Java and .Net
http://aws.amazon.com/ruby/
http://aws.amazon.com/python/
I am fluent in PHP and Java, I hate .Net
The project is to have a lot (around 50) Amazon instances connect to a central pile (o... | [
"If you have no pressing need for a rewrite, just use your existing codebase. Maybe refactor some things step by step, to see if Ruby, Python or Java suit well for particular problems. Python for example is a perfect glue language, also good for crawling and has native json support since 2.6.\n"
] | [
1
] | [] | [] | [
"amazon_web_services",
"mysql",
"postgresql",
"python",
"ruby"
] | stackoverflow_0004858697_amazon_web_services_mysql_postgresql_python_ruby.txt |
Q:
Problems with PIL and py2exe
I'm trying to use Py2exe to convert a .py file to an .exe file. My program uses several modules from PIL
This is what my .py file imports from PIL (snippet):
import Tkinter, re, random, struct
from PIL import ImageTk, Image, ImageDraw, ImageGrab
This is the code I use to convert m... | Problems with PIL and py2exe | I'm trying to use Py2exe to convert a .py file to an .exe file. My program uses several modules from PIL
This is what my .py file imports from PIL (snippet):
import Tkinter, re, random, struct
from PIL import ImageTk, Image, ImageDraw, ImageGrab
This is the code I use to convert my .py file to an .exe:
from distut... | [
"Since the problem is apparently due to PIL's internal initialisation routines rather than anything specific your application does, I suggest trying the workaround described at the link you found and seeing if it helps.\nIf that still doesn't work, I also suggest running your application from the command line rathe... | [
2
] | [] | [] | [
"py2exe",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0004858667_py2exe_python_python_imaging_library_tkinter.txt |
Q:
Python :: ctypes :: GetProcAddress() returns error
The following is a part of a debugger class. I've got the following code for enumerating processes in debugee. First it enumerates and loads handles of the existing debugee's processes into an array. Then I'm trying to get an address of particular function in part... | Python :: ctypes :: GetProcAddress() returns error | The following is a part of a debugger class. I've got the following code for enumerating processes in debugee. First it enumerates and loads handles of the existing debugee's processes into an array. Then I'm trying to get an address of particular function in particular module. In this case i'm trying to get address of... | [
"GetProcAddress gets the address of a function in a DLL loaded in your process, not in a different process. You should check out the Debug Help Library.\nPer your request about GetProcAddress, my references:\nGetProcAddress\n\nhModule [in]\n A handle to the DLL module that contains the function or variable. The L... | [
2,
0
] | [] | [] | [
"c++",
"ctypes",
"python",
"winapi"
] | stackoverflow_0004858042_c++_ctypes_python_winapi.txt |
Q:
Editing Existing JSON in Python
I'm pulling in some JSON from a server in the given format:
{"images": [{"rating": 5.0, "thumburl": "http://something.jpg", "description": "dfgd", "submitdate": "2011-01-29T07:54:02", "submituser": "J", "imagekey": "a"}, ...]}
I have to add a new element "viewurl" to each element u... | Editing Existing JSON in Python | I'm pulling in some JSON from a server in the given format:
{"images": [{"rating": 5.0, "thumburl": "http://something.jpg", "description": "dfgd", "submitdate": "2011-01-29T07:54:02", "submituser": "J", "imagekey": "a"}, ...]}
I have to add a new element "viewurl" to each element using the "imagekey." For example, the... | [
"Is this what you are trying to do?\ndata = simplejson.loads(yourString)\nfor image in data['images']:\n image['viewurl'] = '/view?imagekey=%s' %(image['imagekey'])\n\nYou could also use an object_hook. This works for your example, but you may want to tweak it a bit depending on your actual data:\n>>> def addIm... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"simplejson"
] | stackoverflow_0004859071_python_simplejson.txt |
Q:
How to create array of the certain type in python
How do you create an array of defined length of the certain type in python? To be precise I am trying to create an array of handles that is able to hold up to 1024 records. I figured out an analog to HANDLE type in python, which would be c_void_p of ctypes.
For ex... | How to create array of the certain type in python | How do you create an array of defined length of the certain type in python? To be precise I am trying to create an array of handles that is able to hold up to 1024 records. I figured out an analog to HANDLE type in python, which would be c_void_p of ctypes.
For example C++ code would have:
HANDLE myHandles[1024];
Wha... | [
"You've already accepted an answer, but since you tagged ctypes you might want to know how to create arrays of ctypes types:\n>>> import ctypes\n>>> ctypes.c_void_p * 1024 # NOTE: this is a TYPE\n<class '__main__.c_void_p_Array_1024'>\n>>> (ctypes.c_void_p * 1024)() # This is an INSTANCE \... | [
7,
4
] | [] | [] | [
"arrays",
"ctypes",
"python"
] | stackoverflow_0004855774_arrays_ctypes_python.txt |
Q:
Parsing a uniprot flat file
Can anybody please let me know or help with parsing a uniprot flat file and access the information in the annotation (FT) line and produce an output file in python script. FT line is the on in a general uniprot flat file describing the nature of the proteins. Script written to this must... | Parsing a uniprot flat file | Can anybody please let me know or help with parsing a uniprot flat file and access the information in the annotation (FT) line and produce an output file in python script. FT line is the on in a general uniprot flat file describing the nature of the proteins. Script written to this must produce an output file with the ... | [
"I suggest looking at biopython: http://biopython.org\nIn particular, their SeqIO module: http://biopython.org/wiki/SeqIO\n"
] | [
1
] | [] | [] | [
"python",
"text_parsing"
] | stackoverflow_0004858837_python_text_parsing.txt |
Q:
common sense advice about python package management on OSX for beginners
If I'm learning python development on OSX (Snow Leopard), how should I best manage my python packages?
I am very excited about the large number of great python packages out there. I would love to start learning them, but package management ha... | common sense advice about python package management on OSX for beginners | If I'm learning python development on OSX (Snow Leopard), how should I best manage my python packages?
I am very excited about the large number of great python packages out there. I would love to start learning them, but package management has got me totally confused. Clearly I have no idea what I'm doing. I see many q... | [
"I would suggest the following strongly. I use them for basic package management.\n\nvirtualenv: http://pypi.python.org/pypi/virtualenv\nvirtualenvwrapper: http://pypi.python.org/pypi/virtualenvwrapper\nyolk: http://pypi.python.org/pypi/yolk\npip : http://pypi.python.org/pypi/pip\n\nTutorial / blogs that should hel... | [
6,
3,
0
] | [] | [] | [
"homebrew",
"installation",
"macports",
"package",
"python"
] | stackoverflow_0004835899_homebrew_installation_macports_package_python.txt |
Q:
Ruby to Python bridge
I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.
An obvious way to do this is via some... | Ruby to Python bridge | I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.
An obvious way to do this is via something like XML-RPC or maybe... | [
"Well, you could try named pipes or something similar but I really think that XML-RPC would be the most headache-free way.\n",
"Please be advised that I don't speak from personal experience here, but I imagine JRuby and Jython (The ruby and python implementations in the JVM) would be able to to easily talk to eac... | [
4,
3,
2,
1,
1
] | [] | [] | [
"interop",
"python",
"ruby"
] | stackoverflow_0000206823_interop_python_ruby.txt |
Q:
bat script linking to python script
I have a .bat that sets up an environment which allows users to execute several python scripts for specific jobs. My goal is to create links to the scripts.
For example, the user runs the .bat, a cmd window pops up, and instead of typing python theLongestPythonScriptNameInTheWor... | bat script linking to python script | I have a .bat that sets up an environment which allows users to execute several python scripts for specific jobs. My goal is to create links to the scripts.
For example, the user runs the .bat, a cmd window pops up, and instead of typing python theLongestPythonScriptNameInTheWorld.py he types python go.
My target platf... | [
"Your batch file could take a parameter, and use that to decide which Python package to run.\n@echo off\nREM Set Environment Here\nif %1==\"GO\" python yourLongestScriptNameInTheWorld.py %2 %3 %4 %5\nif %1==\"STOP\" python anotherScript.py %2 %3 %4 %5\n\nSo, if the batch file is called foo.bat they could type:\nfoo... | [
3,
1,
0
] | [] | [] | [
"batch_file",
"hyperlink",
"python",
"symlink",
"windows_xp"
] | stackoverflow_0004859291_batch_file_hyperlink_python_symlink_windows_xp.txt |
Q:
Reason for Assignment to " _ "
I have seen this in a few contexts, e.g.,
in sequence unpacking:
_, x = L.pop() # e.g., L is a list of tuples
to initialize a container:
X = _
So obviously this is not an element of the formal python syntax, rather the uses i am aware of appear discretionary.
So I'm curious what... | Reason for Assignment to " _ " | I have seen this in a few contexts, e.g.,
in sequence unpacking:
_, x = L.pop() # e.g., L is a list of tuples
to initialize a container:
X = _
So obviously this is not an element of the formal python syntax, rather the uses i am aware of appear discretionary.
So I'm curious what is the likely reason for its use an... | [
"I've seen it used in two ways. Both as a throw-away variable but more commonly as a text wrapper for internationalization.\nThrow-away variable\nname, _ = 'bida.bombu.foo'.split('.', 1)\n\nAlthough I would not recommend this. Call it \"ignored\" instead.\nname, ignored = 'bida.bombu.foo'.split('.', 1)\n\nIt's clea... | [
33,
7,
6,
3
] | [
"There is not a good reason to use _ in the scripts. While using from interactive interpretor if you are doing any mathematical calculation, and you want the the result of the previous expression, you can use _. Python tutorial introduces the _ in the very same context. I see that the behavior is carried over from ... | [
-2
] | [
"idioms",
"programming_languages",
"python",
"syntax"
] | stackoverflow_0004859909_idioms_programming_languages_python_syntax.txt |
Q:
Why is my MySQL stored procedure not executing when called from Python using os.system() or subprocess.Popen()?
I have a .sql file that creates and executes a stored procedure. The structure of the .sql file is like this:
delimiter $$
drop procedure if exists `myProcedure`$$
create procedure `myProcedure` (
inpu... | Why is my MySQL stored procedure not executing when called from Python using os.system() or subprocess.Popen()? | I have a .sql file that creates and executes a stored procedure. The structure of the .sql file is like this:
delimiter $$
drop procedure if exists `myProcedure`$$
create procedure `myProcedure` (
input INT
)
BEGIN
... sql statements;
END $$
call myProcedure(10);
$$
When this is executed from the shell in the fol... | [
"command = 'mysql -uuser -ppassword -hhost db_name < mysql_proc.sql'\nmysql_cmd_proc = subprocess.Popen(command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\nDon't use shell=True (it should be False, which it is by default). Also, pass the command as a list. \nDo this:\n... | [
1
] | [] | [] | [
"command_line",
"mysql",
"python",
"stored_procedures",
"subprocess"
] | stackoverflow_0004859805_command_line_mysql_python_stored_procedures_subprocess.txt |
Q:
python variable in the function call
i'm trying to create a directory/folder in linux using python. I will get date time and make a folder.
In [65]: d = datetime.datetime.now()
In [66]: a = 'date :' + str(d)
In [67]: a
Out[67]: 'date :2011-02-01 13:05:58.642704'
In [68]: os.system('mkdir a')
How should i pass... | python variable in the function call | i'm trying to create a directory/folder in linux using python. I will get date time and make a folder.
In [65]: d = datetime.datetime.now()
In [66]: a = 'date :' + str(d)
In [67]: a
Out[67]: 'date :2011-02-01 13:05:58.642704'
In [68]: os.system('mkdir a')
How should i pass the variable a in the system command??
| [
"Use string formatting to add the var a to the string:\nos.system('mkdir %s' % a)\n\n",
"Use python's own way of making directories:\nos.mkdir(a)\n\n",
"Are you sure you want to name your directory 'date :2011-02-01 13:05:58.642704' with all those colons and spaces? There is a simple way to format the date in a... | [
3,
3,
2,
1
] | [] | [] | [
"datetime",
"function",
"python",
"string"
] | stackoverflow_0004860051_datetime_function_python_string.txt |
Q:
Where can I get the source code of module __builtin__ in python?
where can I get the source code for module builtin in python ? I am interested in version 2.6.x.
A:
Go to the folder you installed the Python libraries in, check under the version\Python folder - you should find the bltinmodule.c file.
Something al... | Where can I get the source code of module __builtin__ in python? | where can I get the source code for module builtin in python ? I am interested in version 2.6.x.
| [
"Go to the folder you installed the Python libraries in, check under the version\\Python folder - you should find the bltinmodule.c file.\nSomething along the lines of C:\\python\\2.X\\Python\nOn CentOS it's...\nroot@xenos ~> locate bltinmodule.c\n/usr/src/debug/Python-2.5.1/Python/bltinmodule.c\n/usr/src/debug/Pyt... | [
4,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004858701_python.txt |
Q:
Why does dict have worst case O(n) for so many operations?
How exactly is dict implemented that it has a linear time lookup for collisions? I would assume that it is implemented as a hashtable backed by a list. I would presume that a better implementation would be O(log(n)) for various operations, using a tree to ... | Why does dict have worst case O(n) for so many operations? | How exactly is dict implemented that it has a linear time lookup for collisions? I would assume that it is implemented as a hashtable backed by a list. I would presume that a better implementation would be O(log(n)) for various operations, using a tree to back the table instead. Is there some magic happening behind the... | [
"Dict is O(1) for most operations, except for operations that touch all elements, such as iteration and copy (in which case, it's obviously O(n)).\nSee: http://wiki.python.org/moin/TimeComplexity\nIt has O(n) worst case, because you can always contrive a pathological example where all the keys have the same hash v... | [
12,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004857919_python.txt |
Q:
Programmatically creating variables in Python
Possible Duplicate:
How to programmatically set a global (module) variable?
I have a class called Variable defined as so:
class Variable():
def __init__(self, name):
self.name = name
self._value = None
def value(self):
return self._val... | Programmatically creating variables in Python |
Possible Duplicate:
How to programmatically set a global (module) variable?
I have a class called Variable defined as so:
class Variable():
def __init__(self, name):
self.name = name
self._value = None
def value(self):
return self._value
def __repr__(self):
return self.nam... | [
"from string import uppercase\n_g = globals()\nfor char in uppercase:\n _g[char] = Variable(char)\n\nWhether this is a good idea remains questionable :)\nThis only works for globals() (i.e. module level assignments), as the language definition explicitly states that modifying the dictionary returned by locals() ... | [
25,
11,
4,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004859217_python.txt |
Q:
I don't know how to make __slots__ work
How come this code runs for me?
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
I thought slots worked as a restriction. I'm running Python 2.6.6.
A:
_... | I don't know how to make __slots__ work | How come this code runs for me?
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
I thought slots worked as a restriction. I'm running Python 2.6.6.
| [
"__slots__ provides a small optimisation of memory use because it can prevent a __dict__ being allocated to store the instance's attributes. This may be useful if you have a very large number of instances.\nThe restriction you are talking about is mostly an accidental side effect of the way it is implemented. In pa... | [
9,
8
] | [] | [] | [
"python"
] | stackoverflow_0004860751_python.txt |
Q:
Tracing Journaled fileSystem
How can we trace changes going in journal of journaled filesystem like ext3/4.
Being more specific, would like to capture information of read and writes on disk using info in journal.
Will appreciate if there's a way using python.
A:
Maybe inotify is what you are looking for?
| Tracing Journaled fileSystem | How can we trace changes going in journal of journaled filesystem like ext3/4.
Being more specific, would like to capture information of read and writes on disk using info in journal.
Will appreciate if there's a way using python.
| [
"Maybe inotify is what you are looking for?\n"
] | [
1
] | [] | [] | [
"filesystems",
"operating_system",
"python"
] | stackoverflow_0004860882_filesystems_operating_system_python.txt |
Q:
Why doesn't this regular expression match in this string?
I want to be able to replace a string in a file using regular expressions. But my function isn't finding a match. So I've mocked up a test to replicate what's happening.
I have defined the string I want to replace as follows:
string = 'buf = O_strdup("ONE=0... | Why doesn't this regular expression match in this string? | I want to be able to replace a string in a file using regular expressions. But my function isn't finding a match. So I've mocked up a test to replicate what's happening.
I have defined the string I want to replace as follows:
string = 'buf = O_strdup("ONE=001&TYPE=PUZZLE&PREFIX=EXPRESS&");'
I want to replace the "TYPE=... | [
"Since the ^ sign is escaped with \\ the following part: ([\\^&]*) matches any sequence of these characters: ^, &.\nTry replacing it with ([^&]*).\n",
"In my regex tester, this does work: 'TYPE=(.*)\\&PREFIX=(.*)\\&'\n",
"Try this instead\nobj = re.search(r'TYPE=(?P<type>[^&]*?)&PREFIX=(?P<prefix>[^&]*?)&', str... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004861086_python_regex.txt |
Q:
Preserving special characters in text nodes using Python lxml module
I am editing an XML file that is provided by a third party. The XML is used to recreate and entire environment and one is able to edit the XML to propogate the changes. I was able to lookup the element I wanted to change through command line op... | Preserving special characters in text nodes using Python lxml module | I am editing an XML file that is provided by a third party. The XML is used to recreate and entire environment and one is able to edit the XML to propogate the changes. I was able to lookup the element I wanted to change through command line options and save the XML, but special characters are being escaped and I nee... | [
"The only thing I can think of is forcing the parser to treat the nodes you modify as cdata blocks (as the parser is clearly changing the xml tag closing brackets). Try val.text = etree.CDATA(Value) instead of val.text = Value.\nhttp://lxml.de/api.html#cdata\n",
"Terminology: Parsers don't write XML; they read XM... | [
1,
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004856656_lxml_python.txt |
Q:
How can I build a polynomial lambda function from an list of coefficients?
I have an list of coefficients that correspond to a polynomial expression, ie: [1,2,0] corresponds to x^2 + 2x + 0.
I would like to put an arbitrary length array of these coefficients into a lambda function.
Specifically, I am using mpmath... | How can I build a polynomial lambda function from an list of coefficients? | I have an list of coefficients that correspond to a polynomial expression, ie: [1,2,0] corresponds to x^2 + 2x + 0.
I would like to put an arbitrary length array of these coefficients into a lambda function.
Specifically, I am using mpmath and I have a list used for the polyval module that is:
polyval(ctx, coeffs, x, ... | [
"Do you really need a lambda function? Using a \"normal\" function should be easier:\ndef poly(coeffs):\n def calc(x):\n result = 0\n for c in coeffs:\n result = result*x + c\n return result\n return calc\n\nfindroot(poly([1,2,0]))\n\nAnd using that polyval() function you mention, somethi... | [
7,
1,
1,
0
] | [] | [] | [
"function",
"lambda",
"mpmath",
"numpy",
"python"
] | stackoverflow_0004859198_function_lambda_mpmath_numpy_python.txt |
Q:
Reading an xml file using element tree
I have one xml file.
Its looks like,
<root>
<Group>
<ChapterNo>1</ChapterNo>
<ChapterName>A</ChapterName>
<Line>1</Line>
<Content>zfsdfsdf</Content>
<Synonyms>fdgd</Synonyms>
<Translation>assdfsdfsdf</Translation>
</Grou... | Reading an xml file using element tree | I have one xml file.
Its looks like,
<root>
<Group>
<ChapterNo>1</ChapterNo>
<ChapterName>A</ChapterName>
<Line>1</Line>
<Content>zfsdfsdf</Content>
<Synonyms>fdgd</Synonyms>
<Translation>assdfsdfsdf</Translation>
</Group>
<Group>
<ChapterNo>1</Chapt... | [
"To parse your simple two-level data structure and assemble a dict for each group, all you need to do is this:\n>>> # what you did to get `root`\n>>> from pprint import pprint as pp\n>>> for group in root:\n... d = {}\n... for elem in group:\n... d[elem.tag] = elem.text\n... pp(d) # or whack it ... | [
2,
1,
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004861127_elementtree_python_xml.txt |
Q:
Take a list, sort by popularity and then remove duplicates
Possible Duplicate:
In python, how do I take the highest occurrence of something in a list, and sort it that way?
Hi all,
I am looking for an easy way to sort a list by popularity and then remove duplicate elements.
For example, given a list:
[8, 8, 1, 1... | Take a list, sort by popularity and then remove duplicates |
Possible Duplicate:
In python, how do I take the highest occurrence of something in a list, and sort it that way?
Hi all,
I am looking for an easy way to sort a list by popularity and then remove duplicate elements.
For example, given a list:
[8, 8, 1, 1, 5, 8, 9]
I would then end up with a list like the following:... | [
">>> lst = [1, 1, 3, 3, 5, 1, 9]\n>>> from collections import Counter\n>>> c = Counter(lst)\n>>> [i for i, j in c.most_common()]\n[1, 3, 5, 9]\n\nsee collections.Counter docs for the links to legacy versions-compatible implementations.\n",
"@SilentGhost has an excellent solution for Python 2.7+. A relatively simp... | [
13,
12
] | [] | [] | [
"python"
] | stackoverflow_0004861806_python.txt |
Q:
How can you limit the allowed execution time of specific methods in the python version of Google App Engine?
Since the signal module is not supported in the python version of Google App Engine, what is the simplest way to call a method and throw/catch an exception if the method does not return in less than 2 secon... | How can you limit the allowed execution time of specific methods in the python version of Google App Engine? | Since the signal module is not supported in the python version of Google App Engine, what is the simplest way to call a method and throw/catch an exception if the method does not return in less than 2 seconds?
| [
"If you are talking about RPC calls, such as the datastore, you can create an RPC with a deadline (see create_rpc), pass the RPC to your datastore function (db.get, db.put, etc...), then catch DeadlineExceededErrors.\n# Set a five-second timeout\nrpc = db.create_rpc(deadline=5)\n\n# A query:\nquery = YourModel.all(... | [
5,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004859734_google_app_engine_python.txt |
Q:
python processing a log file and stripping characters
I am making a quick log parse tool:
findme = 'important '
logf = file('new.txt')
newlines = []
for line in logf:
if findme in line:
line.partition("as follows: ")[2]
newlines.append(line)
outfile = file('out.txt', 'w')
out... | python processing a log file and stripping characters | I am making a quick log parse tool:
findme = 'important '
logf = file('new.txt')
newlines = []
for line in logf:
if findme in line:
line.partition("as follows: ")[2]
newlines.append(line)
outfile = file('out.txt', 'w')
outfile.writelines(newlines)
Not sure how I should go about ... | [
"Plus, I'm a little confused about the line\nline.partition(\"as follows: \")[2]\n\n. It simply does nothing. Maybe you wanted\nline = line.partition(\"as follows\")[2]\n\n? By the way, it ist better to just write each line in the for loop instead of a giant writelines at the end. Your current solution will use lot... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004862191_python.txt |
Q:
Why is lookup in dictionary much faster than two if-tests in Python?
I need to read gigabytes of text so I'm trying to optimize my code. When doing this I found that, for my problem, using a dictionary is faster than if-tests.
check = {'R':'-', 'F':'+'}
seqs = ['R', 'F']*100
def check1():
for entry in seqs:
... | Why is lookup in dictionary much faster than two if-tests in Python? | I need to read gigabytes of text so I'm trying to optimize my code. When doing this I found that, for my problem, using a dictionary is faster than if-tests.
check = {'R':'-', 'F':'+'}
seqs = ['R', 'F']*100
def check1():
for entry in seqs:
if entry == 'R':
strand = '-'
if entry == 'F':... | [
"You haven't actually proved that looking up in a dictionary is faster than two if tests. What you have shown is that looking up in that particular dictionary is faster than those two tests.\nNormally dictionary lookup needs a few steps: generate a hash from the key to find a potential match, then test the potentia... | [
7,
4,
1,
1
] | [] | [] | [
"dictionary",
"performance",
"python"
] | stackoverflow_0004861589_dictionary_performance_python.txt |
Q:
Create exchange Mailbox from python
I need to create a mailbox on an exchange 2003 server using python.
The stunt conditions are that our machines have either office 2007 and office 2010 installed and thus the cdoexm.dll is not installed on the system. Also as it is 2007/10 you cant install the ExchangeCdo as it r... | Create exchange Mailbox from python | I need to create a mailbox on an exchange 2003 server using python.
The stunt conditions are that our machines have either office 2007 and office 2010 installed and thus the cdoexm.dll is not installed on the system. Also as it is 2007/10 you cant install the ExchangeCdo as it requires certain versions of outlook. Also... | [
"OK so it wasn't a python problem in the end but did require CDOEXM.\nFirst you need to go to control panel->add/remove programs->add/remove windows components. Select Internet Information Services (IIS) and click details, tick Internet Information Services Snap-In and click OK, then next and install (you will need... | [
0
] | [] | [] | [
"com",
"exchange_server_2003",
"outlook",
"python"
] | stackoverflow_0004827758_com_exchange_server_2003_outlook_python.txt |
Q:
Automatically import models on Django shell launch
I'm tired of typing from account_import.models import ImportFile every time I open my Django shell. Is there a way to automatically run this command whenever I fire up my shell?
A:
install django-extensions, one of the commands it features (shell_plus) is provid... | Automatically import models on Django shell launch | I'm tired of typing from account_import.models import ImportFile every time I open my Django shell. Is there a way to automatically run this command whenever I fire up my shell?
| [
"install django-extensions, one of the commands it features (shell_plus) is providing the context for your models.\nhttps://github.com/django-extensions/django-extensions\nSo, instead of ./manage.py shell you can use ./manage.py shell_plus so that everything is imported.\n",
"http://docs.python.org/using/cmdline.... | [
67,
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004863301_django_python.txt |
Q:
python convert str to list
How do i convert
'[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'
to a list of strings, eg.
['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']
A:
Without knowing more details about the input (do we really need to check if the bracke... | python convert str to list | How do i convert
'[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'
to a list of strings, eg.
['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']
| [
"Without knowing more details about the input (do we really need to check if the brackets are there? commas are valid inside a field? ...) the simplest way probably is:\n>>> [s.strip() for s in input_line[1:-1].split(',')]\n['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']\n\n",
"strings... | [
8,
4,
2,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004863316_python_string.txt |
Q:
Make map() return a dictionary
I have the following function:
def heading_positions(self):
return map(
lambda h:
{'{t}.{c}'.format(t=h.table_name,c=h.column_name) : h.position },
self.heading_set.all()
)
It gives me output like this:
[{'customer.customer... | Make map() return a dictionary | I have the following function:
def heading_positions(self):
return map(
lambda h:
{'{t}.{c}'.format(t=h.table_name,c=h.column_name) : h.position },
self.heading_set.all()
)
It gives me output like this:
[{'customer.customer_number': 0L}, {'customer.name': 2L}... | [
"Yes. The basic problem is that you don't create a dictionary out of single-entry dicts, but out of a a sequence of length-two sequences (key, value).\nSo, rather than create an independent single-entry dict with the function, create a tuple and then you can use the dict() constructor:\ndict(map(lambda h: ('{t}.{c}... | [
10,
8,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004863406_python.txt |
Q:
printing elements of a list
Possible Duplicate:
Printing elements out of list
i have a lists that have N items, eg [item1,item2, item3, value ] then i would like to print
print' %s.%s.%s = %s' % (item1,item2, item3, value)
My problem is 'N' variable, and for any cases of 'N', i would like to print
print' %s.%... | printing elements of a list |
Possible Duplicate:
Printing elements out of list
i have a lists that have N items, eg [item1,item2, item3, value ] then i would like to print
print' %s.%s.%s = %s' % (item1,item2, item3, value)
My problem is 'N' variable, and for any cases of 'N', i would like to print
print' %s.%s.%s....%s (N times) = %s' % (it... | [
"Use str.join().\nprint '.'.join(str(x) for x in L[:-1]) + ' = %s' % L[-1]\n\n"
] | [
7
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004863698_list_python.txt |
Q:
Django: How to sort a ModelForm's Many2ManyField (Select Tag) according to the object's __unicode__() value?
As stated in the title.
A:
The sort would have to be done in Python since the database has no idea what you're doing in __unicode__(). So you'd have to retrieve all of the related model instances into a ... | Django: How to sort a ModelForm's Many2ManyField (Select Tag) according to the object's __unicode__() value? | As stated in the title.
| [
"The sort would have to be done in Python since the database has no idea what you're doing in __unicode__(). So you'd have to retrieve all of the related model instances into a list, sort the list using the __unicode__() value of the instances, and then use that list wherever you want.\nThe following document has ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001004202_django_python.txt |
Q:
Filtering rows withing Admin using a Queryset - Django
I'm trying to find a way to filter down rows of objects within Django Admin, using a queryset.
e.g. Person.objects.filter(Q(name='John')|Q(surname='Doe'))
I'm finding quite complicated to figure out.
Any ideas?
A:
You might be able to accomplish this by ov... | Filtering rows withing Admin using a Queryset - Django | I'm trying to find a way to filter down rows of objects within Django Admin, using a queryset.
e.g. Person.objects.filter(Q(name='John')|Q(surname='Doe'))
I'm finding quite complicated to figure out.
Any ideas?
| [
"You might be able to accomplish this by overriding the queryset() method on your modeladmin instance. See http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py?rev=15347#L196\n# untested code\nclass MyModelAdmin(admin.ModelAdmin):\n def queryset(self, request):\n qs = super(M... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0002989586_django_django_admin_django_models_django_queryset_python.txt |
Q:
Python/Twisted IRC bot logging problem
Hey. I only recently started using Python, and my friend suggested using Twisted as a means to create this IRC bot, as it will be a lot simpler. Here is the code I have so far (which is heavily based off logbot.py haha)
from twisted.internet import reactor, protocol
from twis... | Python/Twisted IRC bot logging problem | Hey. I only recently started using Python, and my friend suggested using Twisted as a means to create this IRC bot, as it will be a lot simpler. Here is the code I have so far (which is heavily based off logbot.py haha)
from twisted.internet import reactor, protocol
from twisted.words.protocols import irc
from twisted.... | [
"Define methods for joins and parts and log inside them too:\ndef userJoined(self, user, channel):\n log.msg('%s has joined %s' % (user, channel))\n\ndef userLeft(self, user, channel):\n log.msg('%s has left %s' % (user, channel))\n\ndef userQuit(self, user, quitMessage):\n log.msg('%s has quit. Reason: %s... | [
2,
1
] | [] | [] | [
"irc",
"python",
"twisted"
] | stackoverflow_0004864637_irc_python_twisted.txt |
Q:
Django checkbox want to check only the first box
another checkbox question. I have items in a list. Each item has a checkbox. What I want to do is to tick the FIRST item's checkbox in the list. Right know, it has ticked all checkbox's because of checked="checked".
{% for item in items %}
<tr class="ite... | Django checkbox want to check only the first box | another checkbox question. I have items in a list. Each item has a checkbox. What I want to do is to tick the FIRST item's checkbox in the list. Right know, it has ticked all checkbox's because of checked="checked".
{% for item in items %}
<tr class="items_table_row">
<td><input type="ch... | [
"The forloop variable set by the Django {% for %} tag is your friend here.\nPop this in:\n{% if forloop.first %} checked=\"checked\"{% endif %}\n\ni.e.\n{% for item in items %}\n <tr class=\"items_table_row\">\n <td><input type=\"checkbox\" name=\"{{item.pk}}\" value=\"{{item.pk}}\"{% if forloop.first %}... | [
1,
1
] | [] | [] | [
"checkbox",
"django",
"html",
"python",
"views"
] | stackoverflow_0004864481_checkbox_django_html_python_views.txt |
Q:
Having trouble splitting up Django models into separate files
I'm trying to split up my Django models into separate files but I apparently haven't done it right. When I try to run my Django script that I've been using without problems since I started my project, I get this:
$ ./import.py
Traceback (most recent cal... | Having trouble splitting up Django models into separate files | I'm trying to split up my Django models into separate files but I apparently haven't done it right. When I try to run my Django script that I've been using without problems since I started my project, I get this:
$ ./import.py
Traceback (most recent call last):
File "./import.py", line 6, in <module>
from mcif.mo... | [
"Is there any from django.db import models in account_address.py?\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004864898_django_python.txt |
Q:
How to build Twisted servers which are able to do hot code swap in Python?
I've developed a set of audio streaming server, all of them are using Twisted, and they are in Python, of course. They work, but a problem keeps troubling me, when I found some bugs there in the running server, or I want add something into ... | How to build Twisted servers which are able to do hot code swap in Python? | I've developed a set of audio streaming server, all of them are using Twisted, and they are in Python, of course. They work, but a problem keeps troubling me, when I found some bugs there in the running server, or I want add something into the server, I need to stop them and start. Unlike HTTP servers, it's okay to re... | [
"I gave a talk about this at PyCon 2004. There's also some effort to add more functionality to help with this to Twisted itself. \n"
] | [
5
] | [] | [] | [
"on_the_fly",
"python",
"twisted"
] | stackoverflow_0004864380_on_the_fly_python_twisted.txt |
Q:
Check if the directory content has changed with shell script or python
I have a program that create files in a specific directory.
When those files are ready, I run Latex to produce a .pdf file.
So, my question is, how can I use this directory change as a trigger
to call Latex, using a shell script or a python scr... | Check if the directory content has changed with shell script or python | I have a program that create files in a specific directory.
When those files are ready, I run Latex to produce a .pdf file.
So, my question is, how can I use this directory change as a trigger
to call Latex, using a shell script or a python script?
Best Regards
| [
"inotify replaces dnotify.\nWhy?\n\n...dnotify requires opening one file descriptor for each directory that you intend to watch for changes...\nAdditionally, the file descriptor pins the directory, disallowing the backing device to be unmounted, which causes problems in scenarios involving removable media. When usi... | [
5,
3,
3,
3,
2,
1,
0
] | [] | [] | [
"latex",
"python",
"shell"
] | stackoverflow_0004862346_latex_python_shell.txt |
Q:
Suggestions for improving my method for finding the max value
I have a set called ISET; with a long list of 3-letter elements like: USA, BRA, CHN, ....
I also have a dictionary called heights. The keys for this dictionary are the elements of SET combined with a certain YEAR string. For example: USA1991, USA1992, .... | Suggestions for improving my method for finding the max value | I have a set called ISET; with a long list of 3-letter elements like: USA, BRA, CHN, ....
I also have a dictionary called heights. The keys for this dictionary are the elements of SET combined with a certain YEAR string. For example: USA1991, USA1992, ..., BRA1991, ... ...
What is the best way of finding the max height... | [
"Suggestion, not actually measured: use a mapping heights_per_year from years to dicts mapping country codes to heights.\nyear = getuserselection()\nheights = heights_per_year[int(year)]\nmax_height = max(a.itervalues())\n\nNote the conversion to int for some extra speed (no need to compare strings).\nBetter yet, l... | [
1,
1,
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004865225_optimization_python.txt |
Q:
'No write' variable in Python
In MATLAB you have the ability to return tuples and assign to tuples of values the same as you do so in Python. In MATLAB, if a function returns a value you don't want to assign to anything, you assign it to the special variable ~. For example, say a function f() returns a tuple (1, 2... | 'No write' variable in Python | In MATLAB you have the ability to return tuples and assign to tuples of values the same as you do so in Python. In MATLAB, if a function returns a value you don't want to assign to anything, you assign it to the special variable ~. For example, say a function f() returns a tuple (1, 2), then:
~, b = f()
Assigns 2 to b... | [
"A common idiom in Python is to use _ for this purpose.\nHowever it's not necessarily a good idea because this variable is also used in the interactive interpreter for the last result and assigning to it will stop this useful feature from working.\nAlso _ is sometimes used for string translation, e.g. with gettext.... | [
13,
10
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0004865485_matlab_python.txt |
Q:
Difference between data sets
I have a two data sets as lists, for example:
xa = [1, 2, 3, 10, 1383, 0, 12, 9229, 2, 494, 10, 49]
xb = [1, 1, 4, 12, 1100, 43, 9, 4848, 2, 454, 6, 9]
Series are market data that may contain tens of thousands numbers, their length is same.
I need to find "difference" in percent... | Difference between data sets |
I have a two data sets as lists, for example:
xa = [1, 2, 3, 10, 1383, 0, 12, 9229, 2, 494, 10, 49]
xb = [1, 1, 4, 12, 1100, 43, 9, 4848, 2, 454, 6, 9]
Series are market data that may contain tens of thousands numbers, their length is same.
I need to find "difference" in percents, that shows "how much similarit... | [
"Well if you want a similarity metric for comparing two 1D vectors and that preferably returns a value between 0 and 1 (or 0 and 100%), cosine similarity satisfies those criteria (subject to the proviso at the end). (Whether it's appropriate given the context of your problem, i don't know, but you know the context,... | [
5,
3,
2,
1,
0
] | [] | [] | [
"dataset",
"math",
"numpy",
"python",
"scipy"
] | stackoverflow_0004863404_dataset_math_numpy_python_scipy.txt |
Q:
Sqlalchemy, inheritance and relationships
I have a general User object for my site built as a base class using joined tables
class User(Base):
__tablename__ = "auth_user"
id = Column(Integer, primary_key = True)
username = Column(String(100), nullable = False, unique = True, index = True)
...
... | Sqlalchemy, inheritance and relationships | I have a general User object for my site built as a base class using joined tables
class User(Base):
__tablename__ = "auth_user"
id = Column(Integer, primary_key = True)
username = Column(String(100), nullable = False, unique = True, index = True)
...
type = Column(String(1))
__mapper_args__ =... | [
"Your example uses 2 foreign keys to base class table, so SQLAlchemy can't determine 1) what foreign key should be used for inheritance join, 2) what foreign key to use for staff relationship. You have to specify hints for both cases. Former requires 'inherit_condition' option in __mapper_args__ (see this answer fo... | [
4
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004864935_python_sql_sqlalchemy.txt |
Q:
How to make Vim error list permanent using PyFlakes?
I want to use pep8 as my makeprg in order to check and fix my code compliance to PEP8 (Style guide for python code).
I used the command :set makeprg=pep8\ --repeat\ %, and when I do :make it works, the error list is populated and I can use :cn, :cp and :copen to... | How to make Vim error list permanent using PyFlakes? | I want to use pep8 as my makeprg in order to check and fix my code compliance to PEP8 (Style guide for python code).
I used the command :set makeprg=pep8\ --repeat\ %, and when I do :make it works, the error list is populated and I can use :cn, :cp and :copen to navigate and see the error list in the QuickFix window.
B... | [
"pyflakes has an option that should solve your problem, just put this in your ~/.vimrc :\nlet g:pyflakes_use_quickfix = 0\nThis actually stops pyflakes from using (and breaking) the quickfix window, that is good enough for me.\n",
"See this vim extension\n"
] | [
4,
0
] | [] | [] | [
"pep8",
"pyflakes",
"python",
"vim"
] | stackoverflow_0004814534_pep8_pyflakes_python_vim.txt |
Q:
Deepcopy on nested referenced lists created by list multiplication does not work
As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.
Why does deepcopy not work here:
>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, ... | Deepcopy on nested referenced lists created by list multiplication does not work | As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.
Why does deepcopy not work here:
>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, 0]] #should be: [[1, 0], [0, 1]]
>>>
I am using a numpy array as a workarround w... | [
"It doesn't work because you are creating an array with two references to the same array.\nAn alternative approach is:\n[[0]*2 for i in range(2)]\n\nOr the more explicit:\n[[0 for j in range(2)] for i in range(2)]\n\nThis works because it creates a new array on each iteration.\n\nAre there any more traps where it d... | [
16,
7
] | [] | [] | [
"deep_copy",
"list",
"multiplication",
"nested",
"python"
] | stackoverflow_0004865821_deep_copy_list_multiplication_nested_python.txt |
Q:
Python noob can't get class method to work
I have a method in my Customer class called save_from_row(). It looks like this:
@classmethod
def save_from_row(row):
c = Customer()
c.name = row.value('customer', 'name')
c.customer_number = row.value('customer', 'number')
c.social_security_number = row.v... | Python noob can't get class method to work | I have a method in my Customer class called save_from_row(). It looks like this:
@classmethod
def save_from_row(row):
c = Customer()
c.name = row.value('customer', 'name')
c.customer_number = row.value('customer', 'number')
c.social_security_number = row.value('customer', 'social_security_number')
c... | [
"The first argument to a classmethod is the class itself. Try\n@classmethod\ndef save_from_row(cls, row):\n c = cls()\n # ...\n return c\n\nor\n@staticmethod\ndef save_from_row(row):\n c = Customer()\n # ...\n return c\n\nThe classmethod variant will enable to create subclasses of Customer with t... | [
13,
5
] | [] | [] | [
"class_method",
"python"
] | stackoverflow_0004865897_class_method_python.txt |
Q:
Why is csv.DictReader giving me a no attribute error?
My CSV file is
200
Service
The code I'm putting into the interpreter is
snav = csv.DictReader(open("screennavigation.csv"), delimiter=',')
print snav.fieldnames
['200']
for line in snav:
... print(line)
...
{'200': 'Service'}
snav["200"]
Traceback (mo... | Why is csv.DictReader giving me a no attribute error? | My CSV file is
200
Service
The code I'm putting into the interpreter is
snav = csv.DictReader(open("screennavigation.csv"), delimiter=',')
print snav.fieldnames
['200']
for line in snav:
... print(line)
...
{'200': 'Service'}
snav["200"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>... | [
"The DictReader produces a list of dictionaries. Each line is itself a dictionary - as you show when you iterate through in your for loop.\n(OK, it's actually an iterable, not a list, but the point stands.)\n",
"snav object is DictReader instance and shouldn't be accessed as a dictionary. On iteration it produces... | [
4,
3
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004865622_csv_python.txt |
Q:
Run post-install script in a Python Egg (setuptools)
I have created a little Python egg (with setuptools) that I want to install in other machines of my LAN. I have even setup a server for the eggs and all (and the egg is properly downloaded and installed with easy_install -f http://myserver/eggrepository ) :-)
I ... | Run post-install script in a Python Egg (setuptools) | I have created a little Python egg (with setuptools) that I want to install in other machines of my LAN. I have even setup a server for the eggs and all (and the egg is properly downloaded and installed with easy_install -f http://myserver/eggrepository ) :-)
I would like to know if there's a way of running an script (... | [
"Ok... I found a workaround...\npython-packaging-custom-scripts\nIt's not as straight-forward as I would have liked, but well... \nI can put the installation process in an sh file and then, since there's going to be a Python script in the user's path, I can call it from the bash script installing the package... \n"... | [
0
] | [] | [] | [
"egg",
"linux",
"python"
] | stackoverflow_0004864342_egg_linux_python.txt |
Q:
Why doesn't this absolute import work in Python?
I've got two Python 2.6 files, /code/x/X.py:
import imp
print 'running'
logging = imp.load_source('logging', '/code/y/logging.py')
... and /code/y/logging.py:
from __future__ import absolute_import
import logging as _logging
import sys, os
print sys.path
print os.... | Why doesn't this absolute import work in Python? | I've got two Python 2.6 files, /code/x/X.py:
import imp
print 'running'
logging = imp.load_source('logging', '/code/y/logging.py')
... and /code/y/logging.py:
from __future__ import absolute_import
import logging as _logging
import sys, os
print sys.path
print os.getcwd()
print _logging
Running X.py prints:
running
... | [
"The issue turns out to be the imp.load_source command. The first argument is the name it registers the module under, and subsequent imports will first look in the loaded modules before looking in the path. Changing the line to use a different name, like:\nlogging = imp.load_source('logx', '/code/y/logging.py')\n... | [
3
] | [] | [] | [
"import",
"python",
"python_2.6"
] | stackoverflow_0004865037_import_python_python_2.6.txt |
Q:
Merging rows when counting - Django/SQL
I have the following model:
class Item(models.Model):
unique_code = models.CharField(max_length=100)
category_code = models.CharField(max_length=100)
label = models.CharField(max_length=100)
I would like to get:
the count of the different category_codes used
c... | Merging rows when counting - Django/SQL | I have the following model:
class Item(models.Model):
unique_code = models.CharField(max_length=100)
category_code = models.CharField(max_length=100)
label = models.CharField(max_length=100)
I would like to get:
the count of the different category_codes used
count of the different unique_codes used
coun... | [
"Django/SQL solution as requested:\nthe count of the different category_codes used:\ncategory_codes_cnt = Item.objects.values('category_codes').distinct().count()\n\ncount of the different unique_codes used:\nunique_codes_cnt = Item.objects.values('unique_codes').distinct().count()\n\ncount of the different combina... | [
3,
1,
0
] | [] | [] | [
"django",
"django_models",
"postgresql",
"python",
"sql"
] | stackoverflow_0004866013_django_django_models_postgresql_python_sql.txt |
Q:
Twisted python IRC logging
I'm making an IRC bot which will log the hostname of a user that just joined the channel, and then log it to a file. The method I'm trying to do this in, is perform a whois command, and eventually it will seperated the hostname, then resolve it to an IP, and also log that.
I'm fairly new... | Twisted python IRC logging | I'm making an IRC bot which will log the hostname of a user that just joined the channel, and then log it to a file. The method I'm trying to do this in, is perform a whois command, and eventually it will seperated the hostname, then resolve it to an IP, and also log that.
I'm fairly new to both Python and Twisted, and... | [
"The IRCClient.whois method always returns None. So what you're seeing is exactly what I would expect from this code. :)\nIRCClient.whois sends a WHOIS command to the server. When it returns, the result is not known because the server has not sent it yet (it very likely has not yet even received the request).\nIn... | [
2
] | [] | [] | [
"irc",
"python",
"twisted"
] | stackoverflow_0004866193_irc_python_twisted.txt |
Q:
Dynamic Django Filter with Prerequisite
I know how to typically do dynamic filters in Django using **kwargs, however since I am relatively new to python I can't figure out how to do something slightly different than some of the other related questions that have been asked here.
I want to dynamically apply the same... | Dynamic Django Filter with Prerequisite | I know how to typically do dynamic filters in Django using **kwargs, however since I am relatively new to python I can't figure out how to do something slightly different than some of the other related questions that have been asked here.
I want to dynamically apply the same filter to different model children. I realiz... | [
"A function's arguments are a dictionary.\nBuild your filter like this.\ndef filter_with_prefix( self, prefix, object ):\n\n if self.type = 'Running': \n kwargs = { '%s__%s__%s__%s' % (prefix, 'alpha', 'beta', 'gamma') : object }\n elif self.type = 'Jumping':\n kwargs = { '%s__%s__%s' % (pref... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004866612_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.