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 range occurrence in other range
How can I do something like this:
>>> xrange(4, 10) in xrange(3, 20)
TRUE
A:
How about (min1 >= min2) and (max1 <= max2) ?
(Assuming min1, max1 = 4, 10 and min2, max2 = 3, 20)
Note: You want to compare endpoints without actually making / evaluating the ranges, otherwise ... | python range occurrence in other range | How can I do something like this:
>>> xrange(4, 10) in xrange(3, 20)
TRUE
| [
"How about (min1 >= min2) and (max1 <= max2) ? \n(Assuming min1, max1 = 4, 10 and min2, max2 = 3, 20) \nNote: You want to compare endpoints without actually making / evaluating the ranges, otherwise it'll be horribly inefficient. \nedit: This also works; not better, but prettier imo: min2 <= min1 <= max1 <= max2 \... | [
5,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003236643_python.txt |
Q:
Modify python script to run on every file in a directory
so I have a python script which takes the filename as a command argument and processes that file. However, because I have 263 files which need the same processing, I was wondering whether the command argument section could be modified with a for loop to cons... | Modify python script to run on every file in a directory | so I have a python script which takes the filename as a command argument and processes that file. However, because I have 263 files which need the same processing, I was wondering whether the command argument section could be modified with a for loop to consecutively run through all the files in a folder? Cheers, Sat
E... | [
"As a practical matter, whatever shell you're using probably has some syntax that can be easily used for this. In Bash, for example:\nfor f in *; do python myscript.py $f; done\n\nTo actually do this in Python, I'd suggest structuring your program so that the main code is in a function which takes one argument, the... | [
15,
5,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003241804_python.txt |
Q:
I want to limit how often a Tkinter callback is run
I'm writing my first GUI program with Tkinter (first program in Python too, actually).
I have an Entry widget for searching, and the results go to a Listbox. I want the results to update as the user types, so I made a callback like this:
search_field.bind("<KeyRe... | I want to limit how often a Tkinter callback is run | I'm writing my first GUI program with Tkinter (first program in Python too, actually).
I have an Entry widget for searching, and the results go to a Listbox. I want the results to update as the user types, so I made a callback like this:
search_field.bind("<KeyRelease>", update_results)
The problem is that updates the... | [
"A nice way to do this is a simple caching decorator:\nimport time\ndef limit_rate( delay=1.0 ):\n \"\"\" produces a decorator that will call a function only once per `delay` \"\"\"\n def wrapper( func ): # the actual decorator\n cache = dict( next = 0 ) # cache the result and time\n def limited... | [
3,
0
] | [] | [] | [
"events",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0003232748_events_python_tkinter_user_interface.txt |
Q:
Seeing what gets written to stderr in Python web site using FastCGI
I am working on a website, hosted on DreamHost, using Python. For a while, I was using their default setup, which runs Python scripts using CGI. It worked fine, but I was worried that if I get a lot of traffic, it would run slow and use a lot of m... | Seeing what gets written to stderr in Python web site using FastCGI | I am working on a website, hosted on DreamHost, using Python. For a while, I was using their default setup, which runs Python scripts using CGI. It worked fine, but I was worried that if I get a lot of traffic, it would run slow and use a lot of memory, so I switched it over to FastCGI using this module.
Overall, it st... | [
"If something in your system is capturing file-descriptor two (the \"real\" stderr), you can assign sys.stderr to any open, writeable file object, or to a file-like object (it basically just needs to implement write) -- including a cStdIO.StdIO instance, whose value you can get at any time (before it's closed) with... | [
2
] | [] | [] | [
"fastcgi",
"python",
"stderr",
"wsgi"
] | stackoverflow_0003243474_fastcgi_python_stderr_wsgi.txt |
Q:
Python Rpy R data processing optimization
I am writing a data processing program in Python and R, bridged with Rpy2.
Input data being binary, I use Python to read data out and pass them to R, then collect results to output.
Data are organized into pieces, each being around 100 Bytes (1Byte per value * 100 values).... | Python Rpy R data processing optimization | I am writing a data processing program in Python and R, bridged with Rpy2.
Input data being binary, I use Python to read data out and pass them to R, then collect results to output.
Data are organized into pieces, each being around 100 Bytes (1Byte per value * 100 values).
They just work now, but the speed is very low.... | [
"For option 3.. getting your data in efficiently... read it all in as one long str type in python with a single read from the file. Let's assume it's called myStr.\nimport array\nmyNums = array.array('B', myStr)\n\nNow myNums is an array of each byte easily converted... see help(array.array)... in fact, looking at... | [
1,
1
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0003242670_python_r_rpy2.txt |
Q:
wxPython: Context dialog popup
In Windows dialog boxes, sometimes there is a small ? button on the upper right corner. Its usage is to click on the ?, then the cursor changes to an arrow with a ?, then click on widget inside the dialog box, which will then display a popup help balloon.
This is how my class definit... | wxPython: Context dialog popup | In Windows dialog boxes, sometimes there is a small ? button on the upper right corner. Its usage is to click on the ?, then the cursor changes to an arrow with a ?, then click on widget inside the dialog box, which will then display a popup help balloon.
This is how my class definition looks like:
class Frame(wx.Frame... | [
"Look into context help classes \n\nContextHelp\nContextHelpButton\n\nImportant thing to note is you have to initialize help provider e.g.\nprovider = wx.SimpleHelpProvider()\nwx.HelpProvider_Set(provider)\n\nand set help text for widgets e.g.\npanel.SetHelpText(\"This is a wx.Panel.\")\n\nWorking example: \nimport... | [
4
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003243495_python_wxpython.txt |
Q:
Get File Object used by a CSV Reader/Writer Object
Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:
... | Get File Object used by a CSV Reader/Writer Object | Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:
AttributeError: '_csv.writer' object has no attribute 'f... | [
"csv.writer is a \"builtin\" function. That is, it is written in compiled C code rather than Python. So its internal variables can't be accessed from Python code.\nThat being said, I'm not sure why you would need to inspect the csv.writer object to find out the file object. That object is specified when creating... | [
3,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0000198465_csv_python.txt |
Q:
Python library for HTTP support - including Content-Encoding
I have a scraper, which queries different websites. Some of them varyingly use Content-Encoding. And since I'm trying to simulate an AJAX query and need to mimic Mozilla, I need full support. There are multiple HTTP libraries for Python, but neither seem... | Python library for HTTP support - including Content-Encoding | I have a scraper, which queries different websites. Some of them varyingly use Content-Encoding. And since I'm trying to simulate an AJAX query and need to mimic Mozilla, I need full support. There are multiple HTTP libraries for Python, but neither seems complete:
httplib seems pretty low level, more like a HTTP packe... | [
"I would consider either invoking a child process of cURL or using python bindings for libcurl.\nFrom this description cURL seems to support gzip and deflate.\n"
] | [
1
] | [
"Beautiful Soup might work. Just throwing it out there.\n"
] | [
-1
] | [
"http",
"python"
] | stackoverflow_0003223335_http_python.txt |
Q:
Stop invoking of new Shell/cmd prompt , python
i have a python script which should invoke a .exe file to get some result. That .exe file is invoking a new windows command prompt(shell) . i dont need any output from the .exe file.
i 'm using
os.system('segwin.exe args') in my script where segwin is an executable.
... | Stop invoking of new Shell/cmd prompt , python | i have a python script which should invoke a .exe file to get some result. That .exe file is invoking a new windows command prompt(shell) . i dont need any output from the .exe file.
i 'm using
os.system('segwin.exe args') in my script where segwin is an executable.
now my question is : i need to stop invoking cmd pro... | [
"Try this (untested):\nimport subprocess\nCREATE_NO_WINDOW = 0x08000000\nargs = [...]\nsubprocess.check_call([\"segwin.exe\"] + args, creationflags=CREATE_NO_WINDOW)\n\nNote that check_call checks the return code of the launched subprocess and raises an exception if it's nonzero. If you don't want that, use call in... | [
1,
0
] | [] | [] | [
"operating_system",
"python",
"shell",
"system"
] | stackoverflow_0003243794_operating_system_python_shell_system.txt |
Q:
what's with a "embedded webserver in a web application" in Python?
CherryPy claims:
Your CherryPy powered web applications
are in fact stand-alone Python
applications embedding their own
multi-threaded web server. You can
deploy them anywhere you can run
Python applications. Apache is not
required, bu... | what's with a "embedded webserver in a web application" in Python? | CherryPy claims:
Your CherryPy powered web applications
are in fact stand-alone Python
applications embedding their own
multi-threaded web server. You can
deploy them anywhere you can run
Python applications. Apache is not
required, but it's possible to run a
CherryPy application behind it (or
lighttpd... | [
"Apache is a large, rich, powerful and complicated webserver -- you can configure everything and a half, there are many plug-in modules (all the various mod_this, mod_that, etc), and so forth. That's great, but of course there are niches for smaller, lighter webservers as well -- lighttpd (which your cherrypy quot... | [
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003242760_python.txt |
Q:
Limiting Access to django admin via applications
Is it possible to limit what admin pages a user is able to VIEW and modify i know it is currently possible to limit changes to them, but is it possibly to limit a user via permissions or otherwise to only the administration views for one app. If possibly i am also a... | Limiting Access to django admin via applications | Is it possible to limit what admin pages a user is able to VIEW and modify i know it is currently possible to limit changes to them, but is it possibly to limit a user via permissions or otherwise to only the administration views for one app. If possibly i am also aiming that superusers can access the standard django a... | [
"It is indeed possible using django permission system. Check out. You can easily extends this to your own views.\nAll you have to do is create a group in django admin, remove/give it permission for only those you want to allow. And then assign the desired user to this group.\nRemember, permission also limits 'add/c... | [
2
] | [] | [] | [
"authentication",
"django",
"django_admin",
"python"
] | stackoverflow_0003243241_authentication_django_django_admin_python.txt |
Q:
Tornado or Django works with CGI?
Tornado is a webserver + framework like Django but for real-time features.
On my server I don't have a python module or wsgi module so I thought
CGI.
Is there a way to get Tornado ( or Django ) works by using CGI folder ?
If yes, Could you explain me how do I do that ?
A:
Mai... | Tornado or Django works with CGI? | Tornado is a webserver + framework like Django but for real-time features.
On my server I don't have a python module or wsgi module so I thought
CGI.
Is there a way to get Tornado ( or Django ) works by using CGI folder ?
If yes, Could you explain me how do I do that ?
| [
"Main feature of Tornado is that it is high performance web-server written in Python, for creating web applications using Python programming language.\nRunning Tornado as CGI application negates the very reason it exists, because running CGI scripts is expensive in terms of performance, and most probably there is n... | [
5,
2
] | [] | [] | [
"cgi",
"django",
"python",
"tornado",
"webserver"
] | stackoverflow_0002537065_cgi_django_python_tornado_webserver.txt |
Q:
How to build pyobjc from src
I am trying to build pyobjc from src, so I checked out http://svn.red-bean.com/pyobjc/trunk
but I have no clue after that what I do to build it, I do not see any make or setup files?
Edit 1:
I tried setup.py in trunk/pyobjc/pyobjc folder but it tries to download all the required module... | How to build pyobjc from src | I am trying to build pyobjc from src, so I checked out http://svn.red-bean.com/pyobjc/trunk
but I have no clue after that what I do to build it, I do not see any make or setup files?
Edit 1:
I tried setup.py in trunk/pyobjc/pyobjc folder but it tries to download all the required modules which seem to be already in trun... | [
"Sorry. The documentation in the http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-core/Install.txt explains the process\n"
] | [
1
] | [] | [] | [
"macos",
"pyobjc",
"python"
] | stackoverflow_0003243685_macos_pyobjc_python.txt |
Q:
ksh-style left and right string stripping up to matched expression?
How can one strip the left parts and right parts off strings up to a matching expression as in ksh?
For instance:
${name##*/}
${name%/*}
(see http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html for ksh examples).
I can't seem to figure out a simp... | ksh-style left and right string stripping up to matched expression? | How can one strip the left parts and right parts off strings up to a matching expression as in ksh?
For instance:
${name##*/}
${name%/*}
(see http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html for ksh examples).
I can't seem to figure out a simple way of doing this using re module or string module but I must be missi... | [
"Ksh:\n$ s='abc/def/ghi'\n$ echo ${s%%/*}\nabc\n$ echo ${s%/*}\nabc/def\n$ echo ${s#*/}\ndef/ghi\n$ echo ${s##*/}\nghi\n\nPython:\n>>> s='abc/def/ghi'\n>>> print s[:s.find(\"/\")]\nabc\n>>> print s[:s.rfind(\"/\")]\nabc/def\n>>> print s[s.find(\"/\")+1:]\ndef/ghi\n>>> print s[s.rfind(\"/\")+1:]\nghi\n\nEdit:\nTo ha... | [
3,
2,
2,
1
] | [] | [] | [
"ksh",
"python",
"regex",
"string"
] | stackoverflow_0003238705_ksh_python_regex_string.txt |
Q:
How to remove special characters and letters from a line read from a text file in Python?
How can I remove special characters and letters from a line read from a text file while preserving the whitespaces? Let's say we have the following contents in a file:
16 ` C38# 26535 2010 4 14 2 7 7 3 8^@1 2
... | How to remove special characters and letters from a line read from a text file in Python? | How can I remove special characters and letters from a line read from a text file while preserving the whitespaces? Let's say we have the following contents in a file:
16 ` C38# 26535 2010 4 14 2 7 7 3 8^@1 2
15 100 140 30 $ 14^]
(2003 2 ! -6 �021 0 � 14 ! 2 3! 1... | [
"import re\n\noutput_string = re.sub(r'[^\\d\\s-]', '', input_string)\n\nThe pattern [^\\d\\s-] will match anything that's not a digit, dash, or whitespace - thus, replacing any match with an empty string will remove everything except the numbers (including minus signs) and whitespace.\n",
"If you want to keep ju... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003243131_python_string.txt |
Q:
No more BeautifulSoup
I have been using BeautifulSoup but as I understand it that library is no longer being maintained. So what should I use ? I have heard about Xpath but what else is there ?
A:
There was a bugfix release in April, so I'm not even sure where you get the idea that it's no longer being maintaine... | No more BeautifulSoup | I have been using BeautifulSoup but as I understand it that library is no longer being maintained. So what should I use ? I have heard about Xpath but what else is there ?
| [
"There was a bugfix release in April, so I'm not even sure where you get the idea that it's no longer being maintained. However, even if that were true, BeautifulSoup is still plenty functional and I don't really see even the current implementation breaking down anytime soon. You might start having problems with ... | [
13,
6,
4,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0003244335_parsing_python.txt |
Q:
Unit testing infrastructure for a python module
I'm writing a python module and I would like to unit test it. I am new to python and somewhat bamboozled by the options available.
Currently, I would like to write my tests as doctests as I like the declarative rather than imperative style (however, feel free to dis... | Unit testing infrastructure for a python module | I'm writing a python module and I would like to unit test it. I am new to python and somewhat bamboozled by the options available.
Currently, I would like to write my tests as doctests as I like the declarative rather than imperative style (however, feel free to disabuse me of this preference if it is misinformed). T... | [
"\nfeel free to disabuse me of this\n preference if it is misinformed\n\nI believe I used doctest more extensively (way stretching its intended use boundaries) than any other open source developer, at least within a single project -- all the tests in my gmpy project are doctests. It was brand new at the time gmpy... | [
12,
3,
2,
1,
1,
0
] | [] | [] | [
"code_coverage",
"doctest",
"python",
"unit_testing"
] | stackoverflow_0003242875_code_coverage_doctest_python_unit_testing.txt |
Q:
Can i put java files in a folder in a pydev project?
I have a .java and .class file which i put under a folder inside my pydev project in Eclipse (because im primarily using python).
Inside my python script i wanted to call the java class file using os.system.
os.system('java -mx1500m D:\\projects\\socialsense\\sr... | Can i put java files in a folder in a pydev project? | I have a .java and .class file which i put under a folder inside my pydev project in Eclipse (because im primarily using python).
Inside my python script i wanted to call the java class file using os.system.
os.system('java -mx1500m D:\\projects\\socialsense\\src\\ss\\samplefile\\test')
However it says that my class f... | [
"I expect that you can do that. However, most people would probably put the java source and python source in separate directory trees, and also not put .class and .java files in the same tree. (If you lump everything into the same place you'll cause yourself pain when you try to implement a \"clean\" rule in your... | [
0
] | [] | [] | [
"eclipse",
"java",
"pydev",
"python"
] | stackoverflow_0003244076_eclipse_java_pydev_python.txt |
Q:
Can we generate DTMF tones using python?
i am keen to know whether we can generate a DTMF tones using python? If yes then is there any library to do so? I have checked on the net there i could find sample program to decode the DTMF tones but not vice-versa. It would be great if anyone can give me some hint.
Thanks... | Can we generate DTMF tones using python? | i am keen to know whether we can generate a DTMF tones using python? If yes then is there any library to do so? I have checked on the net there i could find sample program to decode the DTMF tones but not vice-versa. It would be great if anyone can give me some hint.
Thanks,
Rupesh
| [
"You can just use samples of the dtmf tones and play them back from wav files for example. You could use this website to create the samples\n"
] | [
2
] | [] | [] | [
"python",
"telecommunication"
] | stackoverflow_0003244876_python_telecommunication.txt |
Q:
Django - How to share configuration constants within an app?
It is sometimes beneficial to share certain constants between various code files in a django application.
Examples:
- Name or location of dump file used in various modules\commands etc
- Debug mode on\off for the entire app
- Site specific configuration
... | Django - How to share configuration constants within an app? | It is sometimes beneficial to share certain constants between various code files in a django application.
Examples:
- Name or location of dump file used in various modules\commands etc
- Debug mode on\off for the entire app
- Site specific configuration
What would be the elegant\pythonic way of doing this?
| [
"There's already a project-wide settings.py file. This is the perfect place to put your own custom setttings.\n",
"you can provide settings in your settings.py like \nMY_SETTING = 'value'\n\nand in any module you can fetch it like\nfrom django.conf import settings\nsettings.MY_SETTING\n\n",
"Create a configurat... | [
6,
6,
0,
0
] | [] | [] | [
"coding_style",
"constants",
"django",
"python"
] | stackoverflow_0003244570_coding_style_constants_django_python.txt |
Q:
How can I go about securely executing a subset of python?
I need to store source code for a basic function in a database and allow it to be modified through an admin interface. This code will take several numbers and strings as parameters, and return a number or None. I know that eval is evil, so I need to impleme... | How can I go about securely executing a subset of python? | I need to store source code for a basic function in a database and allow it to be modified through an admin interface. This code will take several numbers and strings as parameters, and return a number or None. I know that eval is evil, so I need to implement a safe way to execute a very basic subset of python, or some... | [
"Restricted Python environments are hard to make really safe.\nMaybe something like lua is a better fit for you\n",
"PySandbox might help. I haven't tested it, just found it linked elsewhere.\n",
"You could use Pyparsing to implement your DSL, provided the expressions involved won't be too complex (you don't gi... | [
2,
2,
1,
0
] | [] | [] | [
"python",
"security"
] | stackoverflow_0003243583_python_security.txt |
Q:
python Qt4 How to bind action on button click
I'm trying make my first python app. I want make simple email sender form.
In qt designer create a dialog.ui, then generate dialog.py from dialog.ui
and write there function
def SendEmail(self,efrom,eto,esubj,ebody):
msg = MIMEText( ebody.encode('UTF-8'),'html', 'U... | python Qt4 How to bind action on button click | I'm trying make my first python app. I want make simple email sender form.
In qt designer create a dialog.ui, then generate dialog.py from dialog.ui
and write there function
def SendEmail(self,efrom,eto,esubj,ebody):
msg = MIMEText( ebody.encode('UTF-8'),'html', 'UTF-8')
msg['Subject'] = esubj
msg['From'] =... | [
"QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(\"clicked()\"), self.SendEmail(\"info@mysite.net\", \"test@mysite.net\", \"subject\", \"bodytext\"))\n\nIt is not how SIGNAL-SLOT system works. Your signal \"clicked()\" have no params -- so Your slot must have no params too. And You must pass reference to call... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0003245202_python.txt |
Q:
Reading an audiostream in python
Amazingly, in bash, you can do
$ curl http://mp3.streampower.be/radio1-high.mp3 > test.mp3
with an audiostream and then ^C out, and you will have a working mp3 file, leading me to believe I could have this automated in python, but I can't find how.
If i just do
file('python.mp3', ... | Reading an audiostream in python | Amazingly, in bash, you can do
$ curl http://mp3.streampower.be/radio1-high.mp3 > test.mp3
with an audiostream and then ^C out, and you will have a working mp3 file, leading me to believe I could have this automated in python, but I can't find how.
If i just do
file('python.mp3', 'w').write(urllib2.urlopen("http://mp3... | [
"You'd probably do better to save the file-like object from urllib2.urlopen() and then use its read method in a loop with a size parameter:\n#!/usr/bin/python\n\nimport urllib2\n\nf=file('python.mp3', 'w')\n\nurl=urllib2.urlopen(\"http://mp3.streampower.be/radio1-high.mp3\")\n\nwhile True:\n f.write(url.read(102... | [
9
] | [] | [] | [
"audio",
"inputstream",
"python",
"stream"
] | stackoverflow_0003245253_audio_inputstream_python_stream.txt |
Q:
Rendering dynamic images with google app engine
I am working on a Google app engine project where I have saved some images in the datastore.
Now I have to resize these images and render them to the template. I have successfully fetched the images but I am not getting,how to render them with other data dictionarie... | Rendering dynamic images with google app engine | I am working on a Google app engine project where I have saved some images in the datastore.
Now I have to resize these images and render them to the template. I have successfully fetched the images but I am not getting,how to render them with other data dictionaries to the template. I am using App engine patch with G... | [
"Solution 1:\nAdd a generic view to get images e.g. /images/image-id should return image for that ID\n\ndef get_image(request, image_id):\n ....\npicture = get from id\nreturn HttpResponse(picture, mimetype=\"image/jpeg\")\n\n\nNow use image URLs inside your forum.html template, like you would use any normal i... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003245451_google_app_engine_python.txt |
Q:
Downloading files using Python
I need to download files from the internet. For that I am using subprocess and calling wget. Is this the right way? The files are hosted on static links and there is no need to log in or anything.
I glanced over urllib but I could not find any example of it being used to download fi... | Downloading files using Python | I need to download files from the internet. For that I am using subprocess and calling wget. Is this the right way? The files are hosted on static links and there is no need to log in or anything.
I glanced over urllib but I could not find any example of it being used to download files of other types.
Any suggestions?... | [
"Other than what?\nurllib.urlretrieve(url)\n\nshould work fine for any filetype. You will often want to specify a filename, rather than use a temp file (the default):\nurllib.urlretrieve(url, filename)\n\nThere are several other libraries too, but this is fine for basic uses.\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0003245807_python.txt |
Q:
how to make a script be active for only on every hour on the half hour?
I have a script and I want to code it so that it becomes active every hour on the half hour. This is the code I have so far.
from ConfigParser import *
import emailModule
from datetime import datetime
import time
configuration = ConfigParser... | how to make a script be active for only on every hour on the half hour? | I have a script and I want to code it so that it becomes active every hour on the half hour. This is the code I have so far.
from ConfigParser import *
import emailModule
from datetime import datetime
import time
configuration = ConfigParser()
configuration.read('Email.conf')
email = emailModule.emailModule(configur... | [
"You can use cron jobs. Schedule it for every 1 hr. starting at 00:30:00.\n",
"If you are using linux, or any other system with a cronlike daemon, you could ask the system to run your script every hour on the half hour by putting a line like this in your crontab: 30 * * * * /path/to/script\n"
] | [
2,
2
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0003245873_performance_python.txt |
Q:
URL updating on login using django
I have started using django very recently . I am building a service with user login.
Login , I am sending as POST service. There is a template to render , once the user is logged in.
But the browser address is not getting updated.
eg : abc.com the root my form would be ... | URL updating on login using django | I have started using django very recently . I am building a service with user login.
Login , I am sending as POST service. There is a template to render , once the user is logged in.
But the browser address is not getting updated.
eg : abc.com the root my form would be something like
"form action="/logi... | [
"In you use login view, on successful login you should redirect to the page you want user to land on e.g.\ndef login_view(request):\n if not correct_login:\n pass#return response with errors\n else\n return HttpResponseRedirect(\"/welcome\")\n\nsee HttpResponseRedirect or use redirect shortcut.\... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003245184_django_python.txt |
Q:
In web2py, can I specify an existing named field as the autonumber ID in a legacy database?
I have dozens of tables in an existing MSSQL database all with
autonumber ID primary keys, but none that are named 'id'. They are
instead named PropertyID, ClientID, etc. The official documentation
seems to suggest renami... | In web2py, can I specify an existing named field as the autonumber ID in a legacy database? | I have dozens of tables in an existing MSSQL database all with
autonumber ID primary keys, but none that are named 'id'. They are
instead named PropertyID, ClientID, etc. The official documentation
seems to suggest renaming each of these fields to 'id':
Legacy Databases
web2py can connect to legacy databases under s... | [
"That statement is obsolete. There are three cases supported by web2py:\n\na table has a auto-increment field called 'id' (default)\na table has a auto-increment field not called 'id', define the table with\ndb.define_table('name',Field('id_name','id'),...other fields...)\na table has a different primary key\ndb.de... | [
4,
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0003230504_python_web2py.txt |
Q:
Visualize data and clustering
i am currently writing a python script to find the similarity between documents.I have already calculated the similarities score for each document pairs and store them in dictionaries. It looks something like this:
{(8328, 8327): 1.0, (8313, 8306): 0.12405229825691289, (8329, 8328): 1... | Visualize data and clustering | i am currently writing a python script to find the similarity between documents.I have already calculated the similarities score for each document pairs and store them in dictionaries. It looks something like this:
{(8328, 8327): 1.0, (8313, 8306): 0.12405229825691289, (8329, 8328): 1.0, (8322, 8321): 0.999999999999999... | [
"I'm not sure what the term for that type of graph would be (minimum weight spanning tree?), but check out Graphviz. There are some Python bindings for it as well, but failing that you could simply generate an input file for it, or pipe data directly in.\n",
"I think you have to use MDS \nhttp://en.wikipedia.org... | [
1,
1,
0,
0,
0
] | [] | [] | [
"cluster_analysis",
"python",
"visualization"
] | stackoverflow_0003240658_cluster_analysis_python_visualization.txt |
Q:
How can I set UVs to a Mesh in Blender Python?
Using Blender 2.49's Python API I'm creating a mesh.
I have a list of vertices and a list of face indices.
e.g.
mesh = bpy.data.meshes.new('mesh')
mesh.verts.extend(mVerts)
mesh.faces.extend(mFaces)
I've noticed MVert's uvco property and MFace's uv
property, and add... | How can I set UVs to a Mesh in Blender Python? | Using Blender 2.49's Python API I'm creating a mesh.
I have a list of vertices and a list of face indices.
e.g.
mesh = bpy.data.meshes.new('mesh')
mesh.verts.extend(mVerts)
mesh.faces.extend(mFaces)
I've noticed MVert's uvco property and MFace's uv
property, and added some random values, but I can't see any
change wh... | [
"Try simply replacing this line:\no = ob.getData()\n\nwith\no = ob.getData(mesh=True)\n\nDue to the historic development of Blender Python API, an ordinary call to blender_object.getData gives you a copy of an object's mesh data, that while can be modified, is not \"live\" on the displayed object. (Actually it is e... | [
2
] | [] | [] | [
"blender",
"bpy",
"bpython",
"python",
"uvw"
] | stackoverflow_0003246100_blender_bpy_bpython_python_uvw.txt |
Q:
Connecting to MSSQL through Web service. Python. Suds. SOAP
I'm connecting to web service using suds.
from suds.client import Client
client=Client(url)
#then i'm using web servise methods to get table. It is very big table.
big_table=client.service.GetVeryBigTable()
#nd trying read every row
for row in b... | Connecting to MSSQL through Web service. Python. Suds. SOAP | I'm connecting to web service using suds.
from suds.client import Client
client=Client(url)
#then i'm using web servise methods to get table. It is very big table.
big_table=client.service.GetVeryBigTable()
#nd trying read every row
for row in big_table:
print row.Id + row.Nmae + row.Description + row.It... | [
"So, no one know answer on this question. I figured out it by my own. \nWhen method gives answer it is loading all the data in my local memory in XML format. So when I try to get big result. For example Some big table than it broke the connection an i gives me Error: that remote server close connection. \nOnly way ... | [
0
] | [] | [] | [
"python",
"soap",
"suds",
"web_services"
] | stackoverflow_0003223948_python_soap_suds_web_services.txt |
Q:
java-applet gui testing with python
is there any frame-work or tool to test java-applets in python
A:
I don't understand exactly what you mean or why you want to test Java in Python but Jython may be helpful.
| java-applet gui testing with python | is there any frame-work or tool to test java-applets in python
| [
"I don't understand exactly what you mean or why you want to test Java in Python but Jython may be helpful.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003246506_python.txt |
Q:
how to process an audio file using python
how to process an audio file using python
A:
Use an audio module.
A:
In addition to an audio module (I've used PyAudio before FWIW), if you want to add effects or various filters (chopping out frequencies, etc), use Numpy as well; the matrix transforms there make it p... | how to process an audio file using python | how to process an audio file using python
| [
"Use an audio module.\n",
"In addition to an audio module (I've used PyAudio before FWIW), if you want to add effects or various filters (chopping out frequencies, etc), use Numpy as well; the matrix transforms there make it pretty painless to apply whatever digital filter you like.\n"
] | [
2,
1
] | [] | [] | [
"audio",
"file",
"python"
] | stackoverflow_0003245583_audio_file_python.txt |
Q:
Django: Save to a many-to-many field in a ModelForm's save() method?
I'm writing a webblog app in Django. I currently have 2 models Post and PostMeta. Post is a standard post style model with fields such as author, title, content etc. It also contains a single many-to-many field called post_meta which is associate... | Django: Save to a many-to-many field in a ModelForm's save() method? | I'm writing a webblog app in Django. I currently have 2 models Post and PostMeta. Post is a standard post style model with fields such as author, title, content etc. It also contains a single many-to-many field called post_meta which is associated with my second model PostMeta. PostMeta is a simple name/value model wit... | [
"The most immediate issue in your code is that when the save() method is called by the Django admin, the commit argument is almost always False. However, if you simply ignore the value of commit, you will not be able to do model.post_meta.add(pm) for newly created Posts, since the model will not have been created i... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003246118_django_python.txt |
Q:
Parsing .c/.cpp/.py source files in Python to get a list of the functions contained
I'm trying to learn about parsers, for Python, C and C++ source (on my own, not for a school project). Here is a summary of what i want to do:
1) read .c/.cpp/.py source files in Python
2) get a list of all the functions in the s... | Parsing .c/.cpp/.py source files in Python to get a list of the functions contained | I'm trying to learn about parsers, for Python, C and C++ source (on my own, not for a school project). Here is a summary of what i want to do:
1) read .c/.cpp/.py source files in Python
2) get a list of all the functions in the source files, and the span of their definitions in terms of line numbers.
So to illustrat... | [
"If you're really interested in learning about parsing C, you might want to look into pycparsing. It's built on PLY, so you can probably leverage what you learn from it for parsing lots of things.\nParsing C++, though, is way more complicated than parsing C or Python, so you may want to explore Python and C before ... | [
3,
1,
0,
0
] | [] | [] | [
"c",
"c++",
"parsing",
"python"
] | stackoverflow_0003246494_c_c++_parsing_python.txt |
Q:
Using lxml to find order of text and sub-elements
Let's say I have the following HTML:
<div>
text1
<div>
t1
</div>
text2
<div>
t2
</div>
text3
</div>
I know of how to get the text and subelements of the enclosing div using lxml.html. But is there a way to access both text and sub elements in an iterative man... | Using lxml to find order of text and sub-elements | Let's say I have the following HTML:
<div>
text1
<div>
t1
</div>
text2
<div>
t2
</div>
text3
</div>
I know of how to get the text and subelements of the enclosing div using lxml.html. But is there a way to access both text and sub elements in an iterative manner, that preserves order? In other words, I want to k... | [
"The elementtree interface, which lxml also offers, supports that -- e.g. with the built-in element tree in Python 2.7:\n>>> from xml.etree import ElementTree as et\n>>> x='''<div>\n... text1\n... <div>\n... t1\n... </div>\n... text2\n... <div>\n... t2\n... </div>\n... text3\n... </div>'''\n>>> t=et.fromstring(... | [
2
] | [] | [] | [
"html",
"lxml",
"python",
"xml"
] | stackoverflow_0003246815_html_lxml_python_xml.txt |
Q:
Approach to upgrade application configuration
My application has a xml based configuration. It has also a xsd file. Before my application starts, xmllint will check the configuration against the xsd file.
With the growth of my application, the configuration structure has changed a bit. Now I have to face this pro... | Approach to upgrade application configuration | My application has a xml based configuration. It has also a xsd file. Before my application starts, xmllint will check the configuration against the xsd file.
With the growth of my application, the configuration structure has changed a bit. Now I have to face this problem: When I provide a new version of my applicatio... | [
"For all configuration settings that remain the same between configurations, have your installation script copy those over from the old config file if it exists. For the rest, just have some defaults that the user can change if necessary, as usual for a config file. Unless I've misunderstood the question, it sounds... | [
1
] | [] | [] | [
"configuration",
"python",
"upgrade",
"xml",
"xsd"
] | stackoverflow_0003247516_configuration_python_upgrade_xml_xsd.txt |
Q:
Cheking added file to upload python, pylons?
I try to upload file, how can i check if file is upload
when i send empty input witch file upload i get
AttributeError: 'unicode' object has no attribute 'filename'
How can i check added file?
A:
be sure to set multipart=True and to omit method="POST"
${h.form(c.form... | Cheking added file to upload python, pylons? | I try to upload file, how can i check if file is upload
when i send empty input witch file upload i get
AttributeError: 'unicode' object has no attribute 'filename'
How can i check added file?
| [
"be sure to set multipart=True and to omit method=\"POST\"\n${h.form(c.formUrl, multipart=True)}\n\n",
"I don't understand the question, but here you have full examples on how to handle file upload on pylons.\n",
"\nuploaded_file = request.params['fieldname']\nif uploaded_file:\n print uploaded_file.filename... | [
1,
0,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002813100_pylons_python.txt |
Q:
python twisted threading
Hi can you please tell me how use different functions in different thread using thread pool
in twisted...say
I have a list of ids x=[1,2,3,4] where 1,2,...etc are ids(I got from data base and each one contains python script in some where disk).
what I want to do is
scanning of x traverse ... | python twisted threading | Hi can you please tell me how use different functions in different thread using thread pool
in twisted...say
I have a list of ids x=[1,2,3,4] where 1,2,...etc are ids(I got from data base and each one contains python script in some where disk).
what I want to do is
scanning of x traverse on list and run every script i... | [
"Threads in Twisted are primarily used via twisted.internet.threads.deferToThread. Alternatively, there's a new interface which is slightly more flexible, twisted.internet.threads.deferToThreadPool. Either way, the answer is roughly the same, though. Iterate over your data and use one of these functions to dispa... | [
14
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003243431_python_twisted.txt |
Q:
Where's the primary key of the object I want to update in django using modelform?
I'm using modelform in django to insert and update objects in my database, but when I try to update I cannot see the primary key/id of the object being updated:
My model:
class Category(models.Model):
name = models.CharField(max_... | Where's the primary key of the object I want to update in django using modelform? | I'm using modelform in django to insert and update objects in my database, but when I try to update I cannot see the primary key/id of the object being updated:
My model:
class Category(models.Model):
name = models.CharField(max_length=20, db_index = True)
and my form:
class CategoryForm(ModelForm):
class Meta... | [
"Where is cat_id coming from in your view? I guess you receive it in url, like so:\nurl( r'categories/(\\d+)/edit/', your_view, {} ),\n\nin urls.py somewhere. Now in your view you can read it from appropriate view function argument:\ndef your_view( request, cat_id ):\n\nNow you can obtain object with proper id, whi... | [
4,
4,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003247625_django_python.txt |
Q:
stdiodemo and command history
While playing and extending stdiodemo.py,
a came up with a thought of adding command line history.
Is this possible?
Any hints?
Thanks
Antonis K.
A:
It's certainly possible. History can be dealt with somewhat independently of input, so ideally you could have an object representing ... | stdiodemo and command history | While playing and extending stdiodemo.py,
a came up with a thought of adding command line history.
Is this possible?
Any hints?
Thanks
Antonis K.
| [
"It's certainly possible. History can be dealt with somewhat independently of input, so ideally you could have an object representing your history with methods like addLine and previousLine and so on. Then you'd glue this to a user-interface of your choice, be it an input box in a Gtk application or something on ... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003246841_python_twisted.txt |
Q:
Merging Multiple KML Files
I cannot find a script to easily merge kml files; any ideas?
Ideally I'd like something along the lines of kmlmerge $file $file, as I'm already working on a shell script for managing multiple kismet drone nodes.
A:
There is xml-cat of the xml-coreutils package (or xmlstarlet) to merge ... | Merging Multiple KML Files | I cannot find a script to easily merge kml files; any ideas?
Ideally I'd like something along the lines of kmlmerge $file $file, as I'm already working on a shell script for managing multiple kismet drone nodes.
| [
"There is xml-cat of the xml-coreutils package (or xmlstarlet) to merge XML files.\nsee: Extracting Nodes from multiple xml files\n"
] | [
5
] | [] | [] | [
"bash",
"kml",
"merge",
"python",
"xml"
] | stackoverflow_0003242704_bash_kml_merge_python_xml.txt |
Q:
Guide to install xampp with zope-plone on the same linux machine?
Is there a good step by step online guide to install xampp (apache server,mysql server) together with zope-plone on the same linux machine and make it play nicely or do I have to go through their confusing documentations?
Or how can I install this c... | Guide to install xampp with zope-plone on the same linux machine? | Is there a good step by step online guide to install xampp (apache server,mysql server) together with zope-plone on the same linux machine and make it play nicely or do I have to go through their confusing documentations?
Or how can I install this configuration in the best way? I can install and use both seperately but... | [
"Do you mean something like this?\nBy the way, I think this question belongs on superuser.com (administrative questions), not stackoverflow.com (programming questions).\n",
"sorry for wrong site but I just figured out that it was not a problem at all. I installed XAMPP (a snap) and downloaded and ran the plone in... | [
0,
0
] | [] | [] | [
"apache",
"plone",
"python",
"xampp",
"zope"
] | stackoverflow_0003233246_apache_plone_python_xampp_zope.txt |
Q:
Python: Range() maximum size; dynamic or static?
I'm quite new to python, so I'm doing my usual of going through Project Euler to work out the logical kinks in my head.
Basically, I need the largest list size possible, ie range(1,n), without overflowing.
Any ideas?
A:
Look at get_len_of_range and get_len_of_ran... | Python: Range() maximum size; dynamic or static? | I'm quite new to python, so I'm doing my usual of going through Project Euler to work out the logical kinks in my head.
Basically, I need the largest list size possible, ie range(1,n), without overflowing.
Any ideas?
| [
"Look at get_len_of_range and get_len_of_range_longs in the builtin module source\nSummary: You'll get an OverflowError if the list has more elements than can be fit into a signed long. On 32bit Python that's 2**31 - 1, and on 64 bit Python that's 2**63 - 1. Of course, you will get a MemoryError even for values jus... | [
8,
0
] | [] | [] | [
"overflow",
"python",
"range"
] | stackoverflow_0003247973_overflow_python_range.txt |
Q:
Test for Python module dependencies being installed
How could one test whether a set of modules is installed, given the names of the modules. E.g.
modules = set(["sys", "os", "jinja"])
for module in modules:
# if test(module exists):
# do something
While it's possible to write out the tests as:
try:
impo... | Test for Python module dependencies being installed | How could one test whether a set of modules is installed, given the names of the modules. E.g.
modules = set(["sys", "os", "jinja"])
for module in modules:
# if test(module exists):
# do something
While it's possible to write out the tests as:
try:
import sys
except ImportError:
print "No sys!"
This is a b... | [
"You can use the __import__() function like this::\nfor module in modules:\n try:\n __import__(module)\n except ImportError:\n do_something()\n\nYou can also use imp.find_module to determine whether a module can be found without importing it::\nimport imp\nfor module in modules:\n try:\n ... | [
8,
6,
5,
2
] | [] | [] | [
"import",
"module",
"python",
"python_module",
"reflection"
] | stackoverflow_0000768504_import_module_python_python_module_reflection.txt |
Q:
Self Extract ZIP?
I need help creating a self extracting zip file that does not display anything. I just need it to extract the files to a given place in the background. Everything I have found displays a dialog, but I need it to just run in the background.
A:
If you don't mind using a command line program, you... | Self Extract ZIP? | I need help creating a self extracting zip file that does not display anything. I just need it to extract the files to a given place in the background. Everything I have found displays a dialog, but I need it to just run in the background.
| [
"If you don't mind using a command line program, you can try here:\nhttp://www.info-zip.org/UnZip.html\nIt's based on ZLib, a free (BSD-like) zip and unzip library.\n",
"I recommend using 7Zip. It can handle more than just zip format, has a command line making it easy to integrate with python or vb scripts.\n",
... | [
1,
0,
0
] | [] | [] | [
"background",
"python",
"self_extracting",
"vbscript",
"zip"
] | stackoverflow_0003247664_background_python_self_extracting_vbscript_zip.txt |
Q:
How to check arguments of the function?
I have function defined this way:
def f1 (a, b, c = None, d = None):
.....
How do I check that a, b are not equal to some value. E.g. I want to check they are not empty strings like, "" or " "
Thinking about something like.
arguments = locals()
for item in arguments:
... | How to check arguments of the function? | I have function defined this way:
def f1 (a, b, c = None, d = None):
.....
How do I check that a, b are not equal to some value. E.g. I want to check they are not empty strings like, "" or " "
Thinking about something like.
arguments = locals()
for item in arguments:
check_attribute(item, arguments[item])
And... | [
"A typical approach would be:\nimport sys\n\n...\n\ndef check_attribute(name, value):\n \"\"\"Gives warnings on stderr if the value is an empty or whitespace string.\n\n All other values, including None, are OK and give no warning.\n \"\"\"\n if isinstance(value, basestring) and (not value or value.i... | [
8,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0003247833_python.txt |
Q:
slicing python array elements with a vector similar to matlab/R
I'm new to python and wanted to do something I normally do in matlab/R all the time, but couldn't figure it out from the docs.
I'd like to slice an array not as 0:3 which includes elements 0,1,2 but as an explicit vector of indices such as 0,3
For ex... | slicing python array elements with a vector similar to matlab/R | I'm new to python and wanted to do something I normally do in matlab/R all the time, but couldn't figure it out from the docs.
I'd like to slice an array not as 0:3 which includes elements 0,1,2 but as an explicit vector of indices such as 0,3
For example, say I had this data structure
a = [1, 2, 3, 4, 5]
I'd like th... | [
"I believe you want numpy.take:\nnewA = numpy.take(a, [1,3])\n\n",
"NumPy allows you to use lists as indices:\nimport numpy\na = numpy.array([1, 2, 3, 4, 5])\na[[1, 3]]\n\nNote that this makes a copy instead of a view.\n"
] | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003248559_python.txt |
Q:
Is it possible to add a single row to a Django form?
I have a form along the lines of:
class aForm(forms.Form):
input1 = forms.CharField()
input2 = forms.CharField()
input3 = forms.CharField()
What I'm hoping to do is add an additional input3 to the form when the user clicks an "add another input3".
I've re... | Is it possible to add a single row to a Django form? | I have a form along the lines of:
class aForm(forms.Form):
input1 = forms.CharField()
input2 = forms.CharField()
input3 = forms.CharField()
What I'm hoping to do is add an additional input3 to the form when the user clicks an "add another input3".
I've read a bunch of ways that let me add new forms using formset... | [
"I would define input3 in your form definition, not require it, and then hide it by default. The user can then show the input using JavaScript.\nIf you want to allow the user to add an undefined amount of additional inputs, I would look further into formsets.\n",
"for adding dynamic fields overwrite the init meth... | [
2,
2,
0
] | [] | [] | [
"django",
"django_forms",
"forms",
"python"
] | stackoverflow_0003247295_django_django_forms_forms_python.txt |
Q:
Python's enum equivalent
Possible Duplicate:
What’s the best way to implement an ‘enum’ in Python?
What is the Python idiom for a list of differently indexed names (like Enum in C/C++ or Java)?
Clarification: I want a property of a value to be set to a restricted range, such as card suites Heart, Club, Spade, Di... | Python's enum equivalent |
Possible Duplicate:
What’s the best way to implement an ‘enum’ in Python?
What is the Python idiom for a list of differently indexed names (like Enum in C/C++ or Java)?
Clarification: I want a property of a value to be set to a restricted range, such as card suites Heart, Club, Spade, Diamond. I could represent it w... | [
"class Suite(object): pass\n\nclass Heart(Suite): pass\nclass Club(Suite): pass\n\netc.\nA class in python is an object. So you can write \nx=Heart\n\netc.\n",
"here is very same popular question on stackoverflow\nEdit:\nclass Suite(set):\n def __getattr__(self, name):\n if name in self:\n re... | [
16,
8
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0003248851_enums_python.txt |
Q:
Unable to use sorted() on a list of Model classes
After running a query on the datastore, I copy the results to a new list as I interrogate, merge and prune the results. When I'm finished, I'd like to sort the new list, but I'm seeing the following error...
TypeError: 'LiveRouteStatus' object is unsubscriptable
Li... | Unable to use sorted() on a list of Model classes | After running a query on the datastore, I copy the results to a new list as I interrogate, merge and prune the results. When I'm finished, I'd like to sort the new list, but I'm seeing the following error...
TypeError: 'LiveRouteStatus' object is unsubscriptable
LiveRouteStatus is a Model class that I query, and while ... | [
"itemgetter('time') is like saying ['time']. \nYou want attrgetter('time'), which is like .time.\n",
"You are querying LiveRouteStatus and the class you declared is called LiveVehicleStatus.\nNot sure if this could be the reason tho !\n"
] | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003249012_google_app_engine_python.txt |
Q:
Python - How to PYTHONPATH with a complex directory structure?
Consider the following file\directory structure:
project\
| django_project\
| | __init__.py
| | django_app1\
| | | __init__.py
| | | utils\
| | | | __init__.py
| | | | bar1.py
| | | | ...
| | | ...
| | django_app2\
| | | ... | Python - How to PYTHONPATH with a complex directory structure? | Consider the following file\directory structure:
project\
| django_project\
| | __init__.py
| | django_app1\
| | | __init__.py
| | | utils\
| | | | __init__.py
| | | | bar1.py
| | | | ...
| | | ...
| | django_app2\
| | | __init__.py
| | | bar2.py
| | | ...
| | ...
| scripts\
| |... | [
"Using relative paths would be much more desirable for portability reasons. \nAt the top of your foo.py script add the following:\nimport os, sys\nPROJECT_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)\nsys.path.append(PROJECT_ROOT)\n\n# Now you can import from the django_project packag... | [
3,
1
] | [] | [] | [
"python",
"python_import",
"pythonpath"
] | stackoverflow_0003249006_python_python_import_pythonpath.txt |
Q:
Quick and dirty reports based on a SQL query
I never thought I'd ever say this but I'd like to have something like the report generator in Microsoft Access. Very simple, just list data from a SQL query.
I don't really care what language is used as long as I can get it done fast.
C#,C++,Python,Javascript...
I want... | Quick and dirty reports based on a SQL query | I never thought I'd ever say this but I'd like to have something like the report generator in Microsoft Access. Very simple, just list data from a SQL query.
I don't really care what language is used as long as I can get it done fast.
C#,C++,Python,Javascript...
I want to know the quickest (development sense) way to d... | [
"Depends on the database -- with [sqlite][1], for example, ...:\n$ sqlite3 databasefile 'select foo, bar from baz'\n\nis all it takes (see the URL I pointed to for more options you can use, e.g. to change the output format, etc). Mysql has a similar command-line client (see e.g. here), so does PostgreSQL (see here... | [
0,
0
] | [] | [] | [
"c#",
"database",
"javascript",
"python",
"sql"
] | stackoverflow_0003242448_c#_database_javascript_python_sql.txt |
Q:
How to easy_install egg plugin and load it without restarting application?
I'm creating an app that downloads and installs its own egg plugins, but I have a problem loading the egg after easy_install extracts it into place. This is how it works now:
App downloads egg into temp folder
Installs egg with setuptools.... | How to easy_install egg plugin and load it without restarting application? | I'm creating an app that downloads and installs its own egg plugins, but I have a problem loading the egg after easy_install extracts it into place. This is how it works now:
App downloads egg into temp folder
Installs egg with setuptools.command.easy_install.main() into ~/.app/plugins folder (which is pointed by a pt... | [
"After some browsing of the documentation I think what you need to do is\npkg_resources.get_distribution(name).activate()\n\nwhere name is the name of the package you just installed.\n"
] | [
5
] | [] | [] | [
"egg",
"python",
"setuptools"
] | stackoverflow_0003231011_egg_python_setuptools.txt |
Q:
How do I use repoze.who/repoze.what with SPNEGO?
I'm trying to do single sign-on (SSO) with an intranet web application written in Pylons and I'd like to use repoze.what for authorization. I have Apache configured with mod_sspi and it correctly authenticates the user and sets the REMOTE_USER environment variable.... | How do I use repoze.who/repoze.what with SPNEGO? | I'm trying to do single sign-on (SSO) with an intranet web application written in Pylons and I'd like to use repoze.what for authorization. I have Apache configured with mod_sspi and it correctly authenticates the user and sets the REMOTE_USER environment variable. However, I can't figure out how to convince repoze.wh... | [
"When the REMOTE_USER variable is set beforehand (e.g., by the web server), repoze.who won't do anything, not even call the registered plugins.\nAs for repoze.what v1, because it is set up from a repoze.who plugin, this means the repoze.what credentials won't be available and therefore the user would always be anon... | [
1
] | [] | [] | [
"pylons",
"python",
"repoze.who"
] | stackoverflow_0003242545_pylons_python_repoze.who.txt |
Q:
Why does django complain that I have not set my ENGINE yet?
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'djangobb', # Or path to database file if using sqlite3.
'... | Why does django complain that I have not set my ENGINE yet? | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'djangobb', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
... | [
"I set mine the old way and the new way, so that it's not django-version-specific:\nDATABASE_ENGINE = 'django.db.backends.sqlite3'\nDATABASE_NAME = '/path/to/db/foo.sqlite3'\nDATABASE_USER = ''\nDATABASE_PASSWORD = ''\nDATABASE_HOST = ''\nDATABASE_PORT = ''\n\nDATABASES = {\n 'default': {\n 'E... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003249142_django_python.txt |
Q:
Possible Data Schemes for Achievements on Google App Engine
I'm building a flash game website using Google App Engine. I'm going to put achievements on it, and am scratching my head on how exactly to store this data. I have a (non-google) user model. I need to know how to store each kind of achievement (name, desc... | Possible Data Schemes for Achievements on Google App Engine | I'm building a flash game website using Google App Engine. I'm going to put achievements on it, and am scratching my head on how exactly to store this data. I have a (non-google) user model. I need to know how to store each kind of achievement (name, description, picture), as well as link them with users who earn them.... | [
"Unless your users will be adding achievements dynamically (as in something like Kongregate where users can upload their own games, etc), your achievement list will be static. That means you can store the (name, description, picture) list in your main python file, or as an achievements module or something. You can ... | [
3,
3
] | [] | [] | [
"achievements",
"google_app_engine",
"python",
"web"
] | stackoverflow_0001583808_achievements_google_app_engine_python_web.txt |
Q:
"BadValueError: Filtering on Text properties is not supported" on a StringProperty using AppEngine
I am running AppEngine locally. I use some filters on the following attribute of my object:
class Blah(db.Model):
access_code = db.StringProperty()
Then I run my filter in the view:
cac = Blah.all().filter(
... | "BadValueError: Filtering on Text properties is not supported" on a StringProperty using AppEngine | I am running AppEngine locally. I use some filters on the following attribute of my object:
class Blah(db.Model):
access_code = db.StringProperty()
Then I run my filter in the view:
cac = Blah.all().filter(
'access_code =', 'value_to_find').fetch(1)
When doing so, I get the following error: BadValueError: Fi... | [
"Was the access_code field ever a TextProperty at some point in your application's life? Even if you changed you model definition, any entities that were added to the datastore while it was a Text will remain a Text. You can use the Admin console's data store viewer to look up the specific entity that is causing th... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003248987_google_app_engine_python.txt |
Q:
python data types
I wrote a script to take files of data that is in columns and plot it depending on which column the user wants to view. Well, I noticed that the plots look crazy, and have all the wrong numbers because python is ignoring the exponential.
My numbers are in the format: 1.000000E+1 OR 1.000000E-1
... | python data types | I wrote a script to take files of data that is in columns and plot it depending on which column the user wants to view. Well, I noticed that the plots look crazy, and have all the wrong numbers because python is ignoring the exponential.
My numbers are in the format: 1.000000E+1 OR 1.000000E-1
What dtype is that? I ... | [
"In [55]: type(1.000000E+1)\nOut[55]: <type 'float'>\n\nWhat does your input data look like, it's fair possible that it's in the wrong input format but it's also sure that it's fairly easy to convert it to the right format.\n",
"Numbers in the form 1.0000E+1 can be parsed by float(), so I'm not sure what the prob... | [
1,
1,
0
] | [] | [] | [
"python",
"types"
] | stackoverflow_0003249350_python_types.txt |
Q:
Error!!! cant concatenate the tuple to non float
stack = []
closed = []
currNode = problem.getStartState()
stack.append(currNode)
while (len(stack) != 0):
node = stack.pop()
if problem.isGoalState(node):
print "true"
closed.append(node)
else:
child = problem.getSucce... | Error!!! cant concatenate the tuple to non float | stack = []
closed = []
currNode = problem.getStartState()
stack.append(currNode)
while (len(stack) != 0):
node = stack.pop()
if problem.isGoalState(node):
print "true"
closed.append(node)
else:
child = problem.getSuccessors(node)
if not child == 0:
st... | [
"Change this:\nnextx, nexty = int(x + dx), int(y + dy)\n\nto this:\nprint x, y, dx, dy, state\nnextx, nexty = int(x + dx), int(y + dy)\n\nI guarantee you will see () around something besides state. That means your value is a tuple:\nint(x + dx), int(y + dy)\nYou cannot concatenate a float and a tuple and convert th... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003249216_python.txt |
Q:
Python convert string object into dictionary
I have been working to build a complex data structure which would return a dictionary. Currently that class return string object of the form
{
cset : x,
b1 : y,
b2 : z,
dep : {
cset : x1,
b1 : y1,
... | Python convert string object into dictionary | I have been working to build a complex data structure which would return a dictionary. Currently that class return string object of the form
{
cset : x,
b1 : y,
b2 : z,
dep : {
cset : x1,
b1 : y1,
b2 : z1,
dep : {
... | [
"Don't use eval. If you are sure that the string will always contain a valid Python dict, use ast.literal_eval. This works pretty much like eval, but it only evaluates if the expression is a valid dict,list, etc. and throws an exceptions if it isn't. This is way safer than trying to evaluate strings that may contai... | [
8,
1,
0
] | [
"You probably do want to use Pickle:\nhttp://docs.python.org/library/pickle.html#pickle.dumps\nIt can also return the value as a string, rather than writing to a file.\n"
] | [
-1
] | [
"dictionary",
"python",
"string"
] | stackoverflow_0003249345_dictionary_python_string.txt |
Q:
python QThread.run parameters - changed between versions?
In my code (python2.6, PyQt4) I do something like this:
def myRun():
doStuff
thread = QtCore.QThread()
thread.run = myRun
thread.start()
On my gentoo machine, this works perfectly. On a ubunut (9.10, Karmic Koala) it does not work, it says:
Type Error:... | python QThread.run parameters - changed between versions? | In my code (python2.6, PyQt4) I do something like this:
def myRun():
doStuff
thread = QtCore.QThread()
thread.run = myRun
thread.start()
On my gentoo machine, this works perfectly. On a ubunut (9.10, Karmic Koala) it does not work, it says:
Type Error: myRun() takes no arguments (1 given)
Did something change in Q... | [
"I'm not sure how that ever worked; you're supposed to subclass QThread and override the run() method. The \"takes no arguments\" error is because the QT runtime is trying to pass \"self\" as the first argument of a class method. The following is closer to what you need:\ndef myThread(QtCore.QThread):\n def run(... | [
2
] | [] | [] | [
"pyqt4",
"python",
"qthread"
] | stackoverflow_0003249845_pyqt4_python_qthread.txt |
Q:
Using Python version 2.6.4 how to program excels filter function
Thanks in advance. Using Excel in the data tab there is a filter option. I wish to implement that into a program I have been working on. It may be as simple as 1 line. If you know anything or if it is not possible in this version/programming language... | Using Python version 2.6.4 how to program excels filter function | Thanks in advance. Using Excel in the data tab there is a filter option. I wish to implement that into a program I have been working on. It may be as simple as 1 line. If you know anything or if it is not possible in this version/programming language please let me know
Thanks!
For more information: I want to use the s... | [
"There is a filter function in Python, however I am not too familiar with filter in Excel. Perhaps it is the same type of thing.\nYou can filter out items from a list based on if they satisfy a certain criteria. For example:\ndef want(s):\n return s in ('dog', 'cat', 'fish') # return true if the string is dog, c... | [
0,
0
] | [] | [] | [
"excel",
"filter",
"formatting",
"python"
] | stackoverflow_0003247546_excel_filter_formatting_python.txt |
Q:
How to reload a file in python?
If I have a script that writes 1000 lines to file and then continues regular expressions against that file, however only the last 100 lines of text written will be available. One way around this is to close and reopen the file. Is there a way to reload a file after being written to ... | How to reload a file in python? | If I have a script that writes 1000 lines to file and then continues regular expressions against that file, however only the last 100 lines of text written will be available. One way around this is to close and reopen the file. Is there a way to reload a file after being written to or should I just make a write close o... | [
"This is just a hunch, but maybe a logfile.seek(0) after the writing is finished may help. A possible explanation is given in the documentation of file.next:\n\nHowever, using seek() to reposition the file to\n an absolute position will flush the read-ahead buffer.\n\n",
"logfile.flush()\n\nThis should do the sa... | [
6,
0
] | [
"As the comments point out, this is the wrong way to go about this. seek(0) is the right way.\nThis had quite an obvious answer, I don't need to close the file or anything, I can just open it again and it acts the same as a reload would. So:\n>>> the_page = 'some large site opened through urllib'\n>>> logfile = ope... | [
-1
] | [
"file_io",
"python"
] | stackoverflow_0003249866_file_io_python.txt |
Q:
Extract specific text lines?
I have a large several hudred thousand lines text file. I have to extract 30,000 specific lines that are all in the text file in random spots. This is the program I have to extract one line at a time:
big_file = open('C:\\gbigfile.txt', 'r')
small_file3 = open('C:\\small_file3.txt', 'w... | Extract specific text lines? | I have a large several hudred thousand lines text file. I have to extract 30,000 specific lines that are all in the text file in random spots. This is the program I have to extract one line at a time:
big_file = open('C:\\gbigfile.txt', 'r')
small_file3 = open('C:\\small_file3.txt', 'w')
for line in big_file:
if 'S0... | [
"Aha! So your real problem is how to test many conditions per line and if one of them is satisfied, to output that line. Easiest will be using regular expression, me thinks:\nimport re\nkeywords = ['S0414', 'GT213', 'AT3423', 'PR342'] # etc - you probably get those from some source\npattern = re.compile('|'.join(ke... | [
7,
2,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003248395_python.txt |
Q:
How to print a string of variables without spaces in Python (minimal coding!)
I have something like : print "\n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"
It prints with spaces for each variable.
| 1 | john | h | johnny | mba |
I want something like this :
|1|john|h|johnny|mba|
I have 20 variables that I ha... | How to print a string of variables without spaces in Python (minimal coding!) | I have something like : print "\n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"
It prints with spaces for each variable.
| 1 | john | h | johnny | mba |
I want something like this :
|1|john|h|johnny|mba|
I have 20 variables that I have to print and I hate use sys.stdout.write(var) for each one of them. Thanks Pytho... | [
"For a variable number of values:\nprint '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])\n\n",
"Try using join:\nprint \"\\n\"+'|'.join([id,var1,var2,var3,var4])\n\nor if the variables aren't already strings:\nprint \"\\n\"+'|'.join(map(str,[id,var1,var2,var3,var4]))\n\nThe benefit of this approac... | [
7,
6,
5,
2
] | [] | [] | [
"printing",
"python",
"stdout"
] | stackoverflow_0003249949_printing_python_stdout.txt |
Q:
Does python have a non-lazy version of itertools.groupby?
I don't need the laziness of itertools.groupby. I just want to group my list into a dict of lists as such:
dict([(a, list(b)) for a,b in itertools.groupby(mylist, mykeyfunc)])
Is there a standard function that already does this?
A:
No, there's not a func... | Does python have a non-lazy version of itertools.groupby? | I don't need the laziness of itertools.groupby. I just want to group my list into a dict of lists as such:
dict([(a, list(b)) for a,b in itertools.groupby(mylist, mykeyfunc)])
Is there a standard function that already does this?
| [
"No, there's not a function included in the standard library to do this.\n"
] | [
4
] | [
"It sounds like you have a one-line function already that does what you want. Use it.\n"
] | [
-2
] | [
"python",
"python_itertools"
] | stackoverflow_0003249741_python_python_itertools.txt |
Q:
Python feedparser not using atom/WordPress namespace?
I'm trying to use feedparser (an excellent library) to parse WordPress export files, and a (minor) inconsistency between WordPress version is causing me a huge headache.
WordPress 2.x doesn't include atom:link tags in the XML output (without_atom_tags.xml). Wh... | Python feedparser not using atom/WordPress namespace? | I'm trying to use feedparser (an excellent library) to parse WordPress export files, and a (minor) inconsistency between WordPress version is causing me a huge headache.
WordPress 2.x doesn't include atom:link tags in the XML output (without_atom_tags.xml). When parsed, namespaced elements are available without the pr... | [
"Could you add the missing namespaces (atom/wp) to the global list of supported namespaces in feedparser.py directly?\n"
] | [
0
] | [] | [] | [
"atom_feed",
"feedparser",
"python",
"wordpress",
"xml"
] | stackoverflow_0003249799_atom_feed_feedparser_python_wordpress_xml.txt |
Q:
Using Deque.popleft as args for function
I am attempting to store a list of commands to send down a serial cable using deque in Python.
My function "send_command" accepts 3 values; The command, an int. pause and a boolean wait. its definition is as follows.
def send_command(self, command, pause=0, wait=False):
Wh... | Using Deque.popleft as args for function | I am attempting to store a list of commands to send down a serial cable using deque in Python.
My function "send_command" accepts 3 values; The command, an int. pause and a boolean wait. its definition is as follows.
def send_command(self, command, pause=0, wait=False):
What I would like to do is, rather than calling ... | [
"probably you need something like:\nobj.send_command(*CommandList.popleft())\n\nThat is, call popleft and use the result as an argument list for send_command. self argument suggests this is a member function, so you need to call it on an object\nAnother way, as I wrote in the comment, is to store prepared functions... | [
3,
1,
0
] | [] | [] | [
"deque",
"list",
"python",
"tuples"
] | stackoverflow_0003250138_deque_list_python_tuples.txt |
Q:
get_or_create() question
From the official documentation I can't understand what is default parameter.
obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)}
Does it mean that it will look for fields which match both John and L... | get_or_create() question | From the official documentation I can't understand what is default parameter.
obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)}
Does it mean that it will look for fields which match both John and Lennon parameter and birthday w... | [
"It's quite obvious - if get_or_create finds queried object, the defaults keword does nothing. But if it creates object, then instance stored in obj has birthday field (in your example) filled with according value. You can pass any dictionary as defaults, as long as its keys are valid field names for model you're q... | [
4,
1,
0
] | [] | [] | [
"django_models",
"python",
"save"
] | stackoverflow_0003225855_django_models_python_save.txt |
Q:
Minimizing, maximizing exe's
How do I maximize, minimize, check whether the program is minimized ?
A:
Flip through the win32gui module (part of the PyWin32 extensions). Most of the functions in it are fairly thin wrappers of standard Windows API calls.
If you want to blindly control something, this question.
C... | Minimizing, maximizing exe's | How do I maximize, minimize, check whether the program is minimized ?
| [
"Flip through the win32gui module (part of the PyWin32 extensions). Most of the functions in it are fairly thin wrappers of standard Windows API calls.\nIf you want to blindly control something, this question.\nChecking if your target program is maximized/fullscreen could likely be accomplished by win32gui.GetFore... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003250213_python.txt |
Q:
How do I modify program files in Python?
In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
A:
Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? Yo... | How do I modify program files in Python? | In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
| [
"Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? You can't go back and edit what those previous commands did (as they have been executed), but you can hit the up arrow to flip through those commands to edit and reexecute them.\nIf you're doing anything very long, the be... | [
2,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003250393_python.txt |
Q:
Visualize and clustering
Earlier on i post a question about visualization and clustering. I guess my question was not quite clear enough so I post it again. I hope i make a better explanation this time . I also apologize for not "accept answer" for my old questions. I didn't know i can do that until a guy point it... | Visualize and clustering | Earlier on i post a question about visualization and clustering. I guess my question was not quite clear enough so I post it again. I hope i make a better explanation this time . I also apologize for not "accept answer" for my old questions. I didn't know i can do that until a guy point it out. I will definitely do it... | [
"Have you tried GraphViz? I use it for situations like this. I haven't tried altering the length of the node connections, you'll have to tease that one out. Check out the list of example graphs as a starting point.\n",
"http://www.graphviz.org/\nIn particular, the neato package:\n$ cat similar.dot\ngraph g {\n ... | [
2,
1,
0
] | [] | [] | [
"cluster_analysis",
"python",
"visualization"
] | stackoverflow_0003250328_cluster_analysis_python_visualization.txt |
Q:
How do I get tags/keywords from a webpage/feed?
I have to build a tag cloud out of a webpage/feed. Once you get the word frequency table of tags, it's easy to build the tagcloud. But my doubt is how do I retrieve the tags/keywords from the webpage/feed?
This is what I'm doing now:
Get the content -> strip HTML ->... | How do I get tags/keywords from a webpage/feed? | I have to build a tag cloud out of a webpage/feed. Once you get the word frequency table of tags, it's easy to build the tagcloud. But my doubt is how do I retrieve the tags/keywords from the webpage/feed?
This is what I'm doing now:
Get the content -> strip HTML -> split them with \s\n\t(space,newline,tab) -> Keyword... | [
"What you have is a rough 1st order approximation. I think if you then go back through the data and search for frequency of 2-word phrases, then 3 word phrases, up till the total number of words that can be considered a tag, you'll get a better representation of keyword frequency.\nYou can refine this rough search ... | [
0
] | [] | [] | [
"keyword",
"python",
"tags",
"visualization"
] | stackoverflow_0003083784_keyword_python_tags_visualization.txt |
Q:
Django form does not display when only one field is being used
I have a django model and model form that look like this:
-models.py
class Menu_Category(models.Model):
merchant = models.ForeignKey(Merchant, related_name='menu_categories')
name = models.CharField(max_length=64)
test_field = models.CharFi... | Django form does not display when only one field is being used | I have a django model and model form that look like this:
-models.py
class Menu_Category(models.Model):
merchant = models.ForeignKey(Merchant, related_name='menu_categories')
name = models.CharField(max_length=64)
test_field = models.CharField(max_length=20)
def __unicode__(self):
return self.name... | [
"You have been bitten by a common Python gotcha. \nIn this line:\nfields = ('name')\n\nthe variable you have created is not a single-element tuple containing the single string \"name\". Instead, it is a single string, which is iterable, so when Django tries to iterate through it to get the names of the fields, it w... | [
9
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003250775_django_django_forms_python.txt |
Q:
How to efficiently output dictionary as csv file using Python's csv module? Out of memory error
I am trying to serialize a list of dictionaries to a csv text file using Python's CSV module. My list has about 13,000 elements, each is a dictionary with ~100 keys consisting of simple text and numbers. My function "... | How to efficiently output dictionary as csv file using Python's csv module? Out of memory error | I am trying to serialize a list of dictionaries to a csv text file using Python's CSV module. My list has about 13,000 elements, each is a dictionary with ~100 keys consisting of simple text and numbers. My function "dictlist2file" simply calls DictWriter to serialize this, but I am getting out of memory errors.
My ... | [
"DictWriter.writerows(...) takes all the dicts you pass in to it and creates (in memory) an entire new list of lists, one for each row. So if you have a lot of data, I can see how a MemoryError would pop up. Two ways you might proceed:\n\nIterate over the list yourself and call DictWriter.writerow once for each ... | [
3,
1,
0,
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0003250236_csv_dictionary_python.txt |
Q:
extract from a list of lists
How can I extract elements in a list of lists and create another one in python. So, I want to get from this:
all_list = [['1 2 3 4','2 3 4 5'],['2 4 4 5', '3 4 5 5' ]]
a new list like this:
list_of_lists = [[('3','4'),('4','5')], [('4','5'),('5','5')]]
Following is what I did, and it... | extract from a list of lists | How can I extract elements in a list of lists and create another one in python. So, I want to get from this:
all_list = [['1 2 3 4','2 3 4 5'],['2 4 4 5', '3 4 5 5' ]]
a new list like this:
list_of_lists = [[('3','4'),('4','5')], [('4','5'),('5','5')]]
Following is what I did, and it doesn't work.
for i in xrange(len... | [
"You could use a nested list comprehension. (This assumes you want the last two \"scores\" out of each string):\n[[tuple(l.split()[-2:]) for l in list] for list in all_list]\n\n",
"It could work almost as-is if you filled in the value for mylist -- right now its undefined. \nHint: use the split function on the st... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003250974_python.txt |
Q:
How can I use PIL with Netbeans 6.8 (Python version 2.6.5)
I have installed Python Imaging Library (PIL) version 1.1.7 on a Windows 7 computer. I have configured Netbeans to use Python (instead of Jython). I added a reference to C:\Python26\Lib\site-packages\PIL to the project but when I attempt this code:
import ... | How can I use PIL with Netbeans 6.8 (Python version 2.6.5) | I have installed Python Imaging Library (PIL) version 1.1.7 on a Windows 7 computer. I have configured Netbeans to use Python (instead of Jython). I added a reference to C:\Python26\Lib\site-packages\PIL to the project but when I attempt this code:
import Image, ImageDraw
img = Image.new("RGB", (100,150),(255,255,255)... | [
"Solved. Project was incorrectly using Jython instead of Python. Although I configured Python as the default Python instance in the main Netbeans settings, that change didn't propagate to my project. Setting it in the projects properties fixed it. Jython is known to have issues with PIL.\n"
] | [
0
] | [] | [] | [
"image_processing",
"netbeans",
"python"
] | stackoverflow_0003250871_image_processing_netbeans_python.txt |
Q:
Missing or invalid primary key
I create my trac enviromnets using a sqlite database, it works very well.
Now i want to get some information directly from the database and i'm using C# to do it using System.Data.SQLite. The problem i have is an error in the designer cause the tables don't have primary keys.
After g... | Missing or invalid primary key | I create my trac enviromnets using a sqlite database, it works very well.
Now i want to get some information directly from the database and i'm using C# to do it using System.Data.SQLite. The problem i have is an error in the designer cause the tables don't have primary keys.
After get this error i went and noticed tha... | [
"You may want to look at the Trac Database API. It's written in Python, but you could probably rewrite it in C# fairly easily. At the very least it'll give you a starting point for finding your solution.\nhttp://trac.edgewall.org/wiki/TracDev/DatabaseApi\n"
] | [
0
] | [] | [] | [
"python",
"sqlite",
"trac"
] | stackoverflow_0002834975_python_sqlite_trac.txt |
Q:
Value Error: Too many values to unpack
When I execute it, it is giving me an eror i.e too many values to unpack?
How do i make it to work properly.
stack = util.Stack()
closed = []
child = []
index = 0
currNode = problem.getStartState()
node = currNode
stack.push(node)
while not stack.isEmpty():
... | Value Error: Too many values to unpack | When I execute it, it is giving me an eror i.e too many values to unpack?
How do i make it to work properly.
stack = util.Stack()
closed = []
child = []
index = 0
currNode = problem.getStartState()
node = currNode
stack.push(node)
while not stack.isEmpty():
node = stack.pop()
if problem.isGoa... | [
"First, it's unlikely that's the whole getSuccessors method, since there's no return value.\nTo guess, I'd say getSuccessors returns a list of tuples: (nextState, action, cost). You're storing each of those as nodes, which will fail when you pass one back into the method, and it tries to unpack the three values a... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003251122_python.txt |
Q:
Python: Simulate re.findall in Pexpect module
Is it possible to simulate re.findall in the pexpect module?
I currently have a script that ssh's into a server using pexpect. I then have it send a command to the server which returns a bunch of lines in p.before (p being a pexpect spawn):
JUNK JUNK JUNK IP ADDRESS 1... | Python: Simulate re.findall in Pexpect module | Is it possible to simulate re.findall in the pexpect module?
I currently have a script that ssh's into a server using pexpect. I then have it send a command to the server which returns a bunch of lines in p.before (p being a pexpect spawn):
JUNK JUNK JUNK IP ADDRESS 10.0.0.1 JUNK JUNK
JUNK IP ADDRESS 10.0.0.3 JUNK JUNK... | [
"I think you could hack what you're looking for by subclassing searcher_re and using an expect_loop call with an instance of your subclass, which overrides the search method.\nIn your override, before performing the main search for whatever you're using now, you can do a findall on the buffer for an IP-identifying ... | [
0
] | [] | [] | [
"pexpect",
"python",
"regex"
] | stackoverflow_0003251135_pexpect_python_regex.txt |
Q:
Using Jython, I need to randomize a string keeping the words in tact
This is the problem:
Function Name: randomSentenceRedux
Parameters:
1.string – a string object to manipulate
Return Value:
A transformed string where the words from the original sentence are in a random order.
Test Case(s):
>>>print randomSentenc... | Using Jython, I need to randomize a string keeping the words in tact | This is the problem:
Function Name: randomSentenceRedux
Parameters:
1.string – a string object to manipulate
Return Value:
A transformed string where the words from the original sentence are in a random order.
Test Case(s):
>>>print randomSentenceRedux("My name is Sally Sue")
My is name Sue Sally
>>>print randomSente... | [
"You should look at Wikipedia's article on the Fisher-Yates shuffle. It's efficient and simple. Here's the psuedo-code they give:\nTo shuffle an array a of n elements:\nfor i from n - 1 downto 1 do\n j ← random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n\nIt should be easy enough to convert to Python.... | [
2,
1,
1,
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0003249515_java_python.txt |
Q:
Understanding behavior of django model save
When using the shell, this confused me (the permissions did not reflect changes):
>>> user = User.objects.get(username='test')
>>> user.get_all_permissions()
set([])
>>> p = Permission.objects.get(codename="add_slide")
>>> user.user_permissions.add(p)
>>> user.save()
>>>... | Understanding behavior of django model save | When using the shell, this confused me (the permissions did not reflect changes):
>>> user = User.objects.get(username='test')
>>> user.get_all_permissions()
set([])
>>> p = Permission.objects.get(codename="add_slide")
>>> user.user_permissions.add(p)
>>> user.save()
>>> user.get_all_permissions()
set([])
>>> user = Us... | [
"Django doesn't update in-memory objects when on-disk objects change. Your first user still looks as it does when it was read from disk.\n",
"This is happening because User has a many2many relationship with Permission, so when you do user.user_permissions.add(p), the \"auth_user\" table does not get updated. Ins... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003249792_django_python.txt |
Q:
Problem with python packages and tests
I have a directory struture like that:
project
| __init__.py
| project.py
| src/
| __init__.py
| class_one.py
| class_two.py
| test/
| __init__.py
| test_class_one.py
Which project.py just instantiate ClassOne and run it.
My problem is in the tests, I do... | Problem with python packages and tests | I have a directory struture like that:
project
| __init__.py
| project.py
| src/
| __init__.py
| class_one.py
| class_two.py
| test/
| __init__.py
| test_class_one.py
Which project.py just instantiate ClassOne and run it.
My problem is in the tests, I don't know how to import src classes. I've tri... | [
"It all depends on your python path. The easiest way to achieve what you're wanting to do here is to set the PYTHONPATH environment variable to where the \"project\" directory resides. For example, if your source is living in:\n/Users/crocidb/src/project/\n\nI would:\nexport PYTHONPATH=/Users/crocidb/src\n\nand t... | [
1,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003251275_python_unit_testing.txt |
Q:
Regex help in python
I am trying to parse an output of about a hundred lines. The format of this output is as such:
<random text> STATION "STATION_NAME_ONE": <random text>
<random text> IP Address: 0.0.0.0 <random text>
<SEVERAL LINES OF RANDOM TEXT>
<random text> STATION "STATION_NAME_TWO": <random text>
<random... | Regex help in python | I am trying to parse an output of about a hundred lines. The format of this output is as such:
<random text> STATION "STATION_NAME_ONE": <random text>
<random text> IP Address: 0.0.0.0 <random text>
<SEVERAL LINES OF RANDOM TEXT>
<random text> STATION "STATION_NAME_TWO": <random text>
<random text> IP Address: 1.1.1.1... | [
"STATION\\s*\"(.*?)\":\\s*.*?(?:\\r|\\n)<.*?>\\s*IP Address:\\s*IPHERE\\s*<\n\nReplace IPHERE with the IP address and to get the station name, extract the first matching group.\n",
"Try /STATION\\s*?\"(.*?)\"\\s*?:.*?IP Address:\\s*?%s/\nThe trick is not to be greedy about matching. After matching this regex, th... | [
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003251511_python_regex.txt |
Q:
How do I tell what type of data is inside python variable?
I have a list of variables.. inside the list are strings, numbers, and class objects. I need to perform logic based on each different type of data. I am having trouble detecting class objects and branching my logic at that point.
if(type(lists[listname][0]... | How do I tell what type of data is inside python variable? | I have a list of variables.. inside the list are strings, numbers, and class objects. I need to perform logic based on each different type of data. I am having trouble detecting class objects and branching my logic at that point.
if(type(lists[listname][0]).__name__ == 'str'): # <--- this works for strings
elif(type(li... | [
"FYI: it also makes a difference if its a new-style class or not:\n# python\ntype(1).__name__\n'int'\ntype('1').__name__\n'str'\nclass foo(object):\n pass\ntype(foo()).__name__\n'foo'\nclass bar:\n pass\ntype(bar()).__name__\n'instance'\n\nIf you can make sure they're all new-style classes, your method will deter... | [
4,
2,
2
] | [
"If you are only interested in handling two types specifically, you could test for them explicitly using isinstance and then handle the leftovers:\nimport numbers\n\nfor item in list:\n if isinstance(item, basestring): # (str, unicode)\n do_string_thing(item)\n elif isinstance(item, numbers.Real): # (i... | [
-1
] | [
"detection",
"python",
"types"
] | stackoverflow_0003251036_detection_python_types.txt |
Q:
inserting text with python
Possible Duplicate:
How do I modify program files in Python?
I need to insert some text at the beginnnig and the end of each line of a text file. how can I use python to do this?
A:
First, open the input and output files...
infile = open('inputfile', 'r')
outfile = open('outputfile',... | inserting text with python |
Possible Duplicate:
How do I modify program files in Python?
I need to insert some text at the beginnnig and the end of each line of a text file. how can I use python to do this?
| [
"First, open the input and output files...\ninfile = open('inputfile', 'r')\noutfile = open('outputfile', 'w')\n\n...then loop thru the lines...\nfor line in infile:\n\n...add your content at the beginning...\n newline = \"stuff for beginning of line\" + line\n\n...then write the line to the output...\n outfi... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003250611_python.txt |
Q:
How do you add Python Imaging Library (PIL) documentation (code completion, etc.) to Netbeans?
I am using Netbeans 6.8 as my Python IDE. I can use PIL (1.1.7) in my Python programs, but the code completion features are not working. I just downloaded the Source Kit edition of PIL, but I am unsure if it contains doc... | How do you add Python Imaging Library (PIL) documentation (code completion, etc.) to Netbeans? | I am using Netbeans 6.8 as my Python IDE. I can use PIL (1.1.7) in my Python programs, but the code completion features are not working. I just downloaded the Source Kit edition of PIL, but I am unsure if it contains documentation/code completion entries that Netbeans can use.
Does anyone know how to use the PIL docum... | [
"I did notice this issue concerning NB 6.7, autocompletion and PILs... so you may want to update that issue if the info from the previous SO entry doesn't lead to a solution.\n"
] | [
0
] | [] | [] | [
"netbeans",
"python"
] | stackoverflow_0003251357_netbeans_python.txt |
Q:
Drawback to catch-all exception (at highest program level, followed by re-raising, just to log before exiting?)
I have a long-running program on a remote machine and want to be sure that (1) I have a record of any exception that causes it to terminate and (2) someone is notified if it terminates. Does anyone see d... | Drawback to catch-all exception (at highest program level, followed by re-raising, just to log before exiting?) | I have a long-running program on a remote machine and want to be sure that (1) I have a record of any exception that causes it to terminate and (2) someone is notified if it terminates. Does anyone see drawbacks to the method I am using? (or have recommendations for a better one?)
I've read the Python docs and many exc... | [
"There is no specific drawback, but there is an excellent alternative -- sys.excepthook.\nIn your specific version, consider using a bare except:, and sys.exc_info() to get the exception information; that will ensure you do catch everything -- even in the weird case where some module raises something else than an i... | [
7,
4,
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0003182935_exception_python.txt |
Q:
Pylons: Webhelpers: missing secure_form module
I installed Pylons 0.9.7 using the go-pylons.py script.
I have a line of python:
from webhelpers.html.secure_form import secure_form
When I try to serve my application I get the error: no module secure_form.
I've tried writing import webhelpers.html.tags and other ... | Pylons: Webhelpers: missing secure_form module | I installed Pylons 0.9.7 using the go-pylons.py script.
I have a line of python:
from webhelpers.html.secure_form import secure_form
When I try to serve my application I get the error: no module secure_form.
I've tried writing import webhelpers.html.tags and other modules from webhelpers and those work. I'm wonderin... | [
"if your webhelpers version is 1.0b4 or above, secure_form is under webhelpers.pylonslib, ie.\nfrom webhelpers.pylonslib import secure_form\n\n",
"I just ran into this as well.\nIn case the other posts aren't obvious to get the old version of webhelpers you can run:\neasy_install webhelpers==0.6.4\n\n",
"ugh, s... | [
7,
2,
1,
1
] | [] | [] | [
"module",
"pylons",
"python"
] | stackoverflow_0002219316_module_pylons_python.txt |
Q:
Automatically recognize patterns in images
Recently I downloaded some flags from the CIA world factbook. Now I want to "classify them.
Get the colors
Get some shapes (stars, moons etc.)
While browsing I came across the Python Image Library which allows me to extract the colors (i.e. for Austria:
#!/usr/bin/env p... | Automatically recognize patterns in images | Recently I downloaded some flags from the CIA world factbook. Now I want to "classify them.
Get the colors
Get some shapes (stars, moons etc.)
While browsing I came across the Python Image Library which allows me to extract the colors (i.e. for Austria:
#!/usr/bin/env python
import Image
bild = Image.open("au-lgflag.... | [
"The Python Imaging Library - PIL just does basic image manipulation - opening, some transforms or filters, and saving to other formats.\nPattern recognition, is part of an advanced image processign field and evolving -- it deos use algorithms far different than those present in PIL.\nThere are some libraries and f... | [
8,
7
] | [] | [] | [
"algorithm",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0003251069_algorithm_image_processing_python_python_imaging_library.txt |
Q:
How can Twisted Deferred errors without errbacks be tested with trial?
I have some Twisted code which creates multiple chains of Deferreds. Some of these may fail without having an errback which puts them back on the callback chain. I haven't been able to write a unit test for this code - the failing Deferred ca... | How can Twisted Deferred errors without errbacks be tested with trial? | I have some Twisted code which creates multiple chains of Deferreds. Some of these may fail without having an errback which puts them back on the callback chain. I haven't been able to write a unit test for this code - the failing Deferred causes the test to fail after the test code has completed. How can I write a ... | [
"There are two important things about trial related to this question.\nFirst, a test method will not pass if a Failure is logged while it is running. Deferreds which are garbage collected with a Failure result cause the Failure to be logged.\nSecond, a test method which returns a Deferred will not pass if the Defe... | [
17
] | [] | [] | [
"python",
"testing",
"twisted",
"unit_testing"
] | stackoverflow_0003250168_python_testing_twisted_unit_testing.txt |
Q:
if statement in python
I can not figure out why my code is not working,
key_one= raw_input("Enter key (0 <= key <= 127): ")
if key_one in range(128):
bin_key_one=bin(key_one)[2:]
print bin_key_one
else:
print "You have to enter key (0 <= key <= 127)"
when i enter a number between 0 and... | if statement in python | I can not figure out why my code is not working,
key_one= raw_input("Enter key (0 <= key <= 127): ")
if key_one in range(128):
bin_key_one=bin(key_one)[2:]
print bin_key_one
else:
print "You have to enter key (0 <= key <= 127)"
when i enter a number between 0 and 127, it keeps on going to t... | [
"raw_input returns a string and \"93\" is NOT in range(128).\nTo make sure you compare apples to apples, cast key_one to int:\nkey = int(raw_input(\"Enter key (0 <= key <= 127): \"))\nif key in range(128)\n # if condition\nelse\n # else condition\n\nEDIT: Python documentation is awesome, so if you have question... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003252383_python.txt |
Q:
How can we retrieve data from datastore?
How can we retrieve data from datastore where we want to use one element of list property as parameter in google app engine?
A:
If I read you correctly: you need to retrieve the whole element containing that particular list property (with either a qgl query or explicit fi... | How can we retrieve data from datastore? | How can we retrieve data from datastore where we want to use one element of list property as parameter in google app engine?
| [
"If I read you correctly: you need to retrieve the whole element containing that particular list property (with either a qgl query or explicit filtering), then access on that element the attribute name of that property.\nFor an alternate reading: if you want an element whose list property in question contains a cer... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003252408_google_app_engine_google_cloud_datastore_python.txt |
Q:
GAE: Why does this code crash the devserver?
I'm using GAE 1.3.5 devserver SDK with Python. When I uncomment this line of code, GAEUnit hangs every time I try to run my test suite:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
#problem line
modelutils.applyToResultsOfQ... | GAE: Why does this code crash the devserver? | I'm using GAE 1.3.5 devserver SDK with Python. When I uncomment this line of code, GAEUnit hangs every time I try to run my test suite:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
#problem line
modelutils.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTai... | [
"fetch(1000) will always return the first 1000 results.\nYou may want to try using cursors, something like this:\nresults = dep_arc_tail_q.fetch(1000) \nwhile results: \n for tail in results: \n modelutils.removeCourseFromTail(course, tail) \n results = dep_arc_tail_q.with_cursor(dep_arc_tail_q.cursor(... | [
4
] | [] | [] | [
"gaeunit",
"google_app_engine",
"python"
] | stackoverflow_0003252348_gaeunit_google_app_engine_python.txt |
Q:
python delete function not working in apache
I am using the s3cmd linux utility to delete files from our amazon s3 bucket. I have created a function in python which calls the s3cmd command line utility and access and deletes the files amazon s3 bucket.
command= 's3cmd -c .s3cfg del s3://project-bucket/images/testi... | python delete function not working in apache | I am using the s3cmd linux utility to delete files from our amazon s3 bucket. I have created a function in python which calls the s3cmd command line utility and access and deletes the files amazon s3 bucket.
command= 's3cmd -c .s3cfg del s3://project-bucket/images/testimage.jpg'
os.system(command)
When I run the proje... | [
"Make sure the apache user has permission to write for all the images and folders you are deleting from.\n",
"the issue is resolved. gave 777 permissions to the .s3cfg file and now i am able to list the image as well as delete the image.\n"
] | [
0,
0
] | [] | [] | [
"amazon_s3",
"apache",
"django",
"python"
] | stackoverflow_0003252483_amazon_s3_apache_django_python.txt |
Q:
List formation in python
I need to put 3 items in the list.
state..eg(1,2)
action...eg..west
cost....5
list=[(state,action,cost), (state,action,cost).........]
how can i make it in a form of list. For a particular state , action and cost is there. Moreover, if i need only state from the list, i should be able to... | List formation in python | I need to put 3 items in the list.
state..eg(1,2)
action...eg..west
cost....5
list=[(state,action,cost), (state,action,cost).........]
how can i make it in a form of list. For a particular state , action and cost is there. Moreover, if i need only state from the list, i should be able to extract it from the list.same... | [
"Your wording is pretty obscure. Right now you have a list of tuples (horribly named list, which robs the use of the built-in name from the rest of that scope -- please don't reuse built-in names as your own identifiers... call them alist or mylist, if you can't think of a more meaningful and helpful name!). If y... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003252725_python.txt |
Q:
trouble parsing XML in python
I'm trying to query a database, then convert the file-like object it returns to an XML document. Here's what I've been doing:
>>> import urllib, xml.dom.minidom
>>> query = "http://sbol.bhi.washington.edu/openrdf-sesame/repositories/sbol_test?query=select%20distinct%20%3Fname%20%3Ffea... | trouble parsing XML in python | I'm trying to query a database, then convert the file-like object it returns to an XML document. Here's what I've been doing:
>>> import urllib, xml.dom.minidom
>>> query = "http://sbol.bhi.washington.edu/openrdf-sesame/repositories/sbol_test?query=select%20distinct%20%3Fname%20%3Ffeaturename%20where%20%7B%3Fpart%20%3C... | [
"Any chance you could post the XML snippet? The parser is indicating that the error is happening at the very first line. My guess is the formatting is off or reporting incorrectly, which is causing EXPAT to pitch an exception right off the bat. \nMy guess is that first line violates something in the \"well formed X... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"xml",
"xmlhttprequest"
] | stackoverflow_0003252779_python_xml_xmlhttprequest.txt |
Q:
What is the dominant reason for Python's popularity as a systems and application programming language?
Coming from an enterprise systems background (think Java and Windows) - I'm surprised at the popularity of python as a prototyping language and am trying to put my finger on the precise reason for this. Examples ... | What is the dominant reason for Python's popularity as a systems and application programming language? | Coming from an enterprise systems background (think Java and Windows) - I'm surprised at the popularity of python as a prototyping language and am trying to put my finger on the precise reason for this. Examples include being listed as one of the four languages Google uses. Possible reasons include:
enables rapid syst... | [
"\nHighly expressive language. People often say, \"Python works the way my brain does\".\nDynamic typing means you spend zero time appeasing the compiler.\nA large standard library means you often have the tools you need at your fingertips.\nAn even larger stable of third-party packages (PIL, Numpy, NLTK, Django) ... | [
19,
6,
4,
2,
0
] | [] | [] | [
"programming_languages",
"prototype",
"python"
] | stackoverflow_0003227789_programming_languages_prototype_python.txt |
Q:
How to simulate sys.argv[1:] on web based python
I have a Python program where the initiation script looks like this:
if __name__ == "__main__":
main(sys.argv[1:])
To run this, I have to use Shell or Terminal like this:
myscript somefile.xml
The script accepts a file and then does all the rest of the work.
N... | How to simulate sys.argv[1:] on web based python | I have a Python program where the initiation script looks like this:
if __name__ == "__main__":
main(sys.argv[1:])
To run this, I have to use Shell or Terminal like this:
myscript somefile.xml
The script accepts a file and then does all the rest of the work.
Now, I am trying to run this program on a web server.
S... | [
"Write the uploaded file contents to a temporary file (using tempfile.mkstemp()) and pass the filename of the temporary file into main() wrapped in a list.\nFor example (untested):\nimport os\nimport tempfile \n\nfd, temp_filename = tempfile.mkstemp()\ntry:\n with os.fdopen(fd, \"wb\") as f:\n # Copy f... | [
1
] | [] | [] | [
"file_upload",
"python"
] | stackoverflow_0003253081_file_upload_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.