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 it'll be horribly inefficient.
edit: This also works; not better, but prettier imo: min2 <= min1 <= max1 <= max2
A:
If you're looking for one set being contained in another set, try:
>>> set(xrange(4, 10)).issubset(set(range(3,20))
If you're looking to compare endpoints since you'll always use ranges for this, than you can just compare the endpoints like @zoli2k.
[EDIT] An edit was requested.
A:
>>>min(xrange(4, 10)) > min(range(3, 20)) and max(xrange(4, 10)) < max(range(3, 20))
True
A:
Given two ranges, you can do this:
>>> a = range(10)
>>> b = range(5,15)
>>> c = range(15,25)
>>> any(x in a for x in b)
True
>>> any(x in a for x in c)
False
This is slightly inefficient, and if have very large (100+ elements) ranges to inspect, it is better for the type of a to be 'set' instead of list. i.e.:
>>> a = set(range(10))
Sets don't have order, but the in operator is much faster.
| 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 consecutively run through all the files in a folder? Cheers, Sat
EDIT:
The code for the system argument is here:
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'r:vo:A:Cp:U:eM:')
except getopt.GetoptError, msg:
print 'prepare_receptor4.py: %s' %msg
usage()
sys.exit(2)
with 'r' being the name of the file needing to be processed and the others are optional arguments. I'm not sure how to modify this with a for loop.
A:
As a practical matter, whatever shell you're using probably has some syntax that can be easily used for this. In Bash, for example:
for f in *; do python myscript.py $f; done
To 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 filename.
def process(filename):
...code goes here...
Then you can invoke this function like so,
for f in os.listdir(folder):
process(f)
folder could be passed as a command-line argument, or just written into the script (if it's not something you'd be reusing).
EDIT: In response to your edit, I'd suggest just giving the filenames as regular command-line arguments, without using the -r option, so that they'll wind up in args. Then you can do
for f in args:
process(f)
or if you would rather pass the directory name as the command-line argument,
for d in args:
for f in os.listdir(d):
process(f)
Alternatively, I suppose you could pass multiple instances of the -r option, and then do
for opt, arg in opt_list:
if opt == '-r':
process(arg)
A:
When I am working on multiple files/folders, I usually use os.walk:
import os
for root, dirs, files in os.walk(dir):
for fname in files:
do_something(fname)
Get your directory from getopt or optparse.
Also, you can build up absolute path with the os.path.abspath if you need it.
current_file = "%s%s%s" % (os.path.abspath(root), os.path.sep, fname)
do_something(current_file)
A:
os.walk() sounds like it might work here.
def traverse_and_touch(directory, touch):
'''
General function for traversing a local directory. Walks through
the entire directory, and touches all files with a specified function.
'''
for root, dirs, files in os.walk(directory):
for filename in files:
touch(os.path.join(root, filename))
return
Now, all you need to do is pass in the directory you'd like to traverse and a function and it'll perform the code on every file.
os.walk() also traverses all sub-directories.
A:
I suggest your 'main' should process each file given after the options. That is, in the "args" variable. Don't pass paths in with "-r ", this limits your flexibility. If you use os.walk() etc in the program you're requiring the system to work only on trees of files, which makes it more difficult to customize and develop.
If the program works with a list of paths, it's very easy to use in different ways. For example, you can list one data file for testing. To process a directory do "myprogram dir/*.dat". To process a tree of files use backquotes:
myprogram `find . -name "*.dat"`
Lastly you can do very cheap parallel processing. Something like:
find . -name '*.dat' | xargs -P 5 myprogram
Five copies of your program are run in parallel. No locking or forks or threads or other synchronization necessary.
(Above assumes you're on a Linux/OSX type system.)
A:
Yes, you could modify it like that. Loop through the arguments rather than indexing the first element.
| 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
EDIT:
The code for the system argument is here:
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'r:vo:A:Cp:U:eM:')
except getopt.GetoptError, msg:
print 'prepare_receptor4.py: %s' %msg
usage()
sys.exit(2)
with 'r' being the name of the file needing to be processed and the others are optional arguments. I'm not sure how to modify this with a for loop.
| [
"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("<KeyRelease>", update_results)
The problem is that updates the search many times in a row. Since the results will be coming from a database query, that generates a lot of unnecessary traffic. What I really want is for it to update every second or so, or to wait a second after the user stops typing and then search. What's the easiest way to do that?
Thanks
UPDATE: That works great for what I described, but now I've realized that I also need to trigger an update after the user stops typing. Otherwise, the last few characters are never included in the search. I think I have to un-accept the answer in order for this to go back into the list of questions...
A:
A nice way to do this is a simple caching decorator:
import time
def limit_rate( delay=1.0 ):
""" produces a decorator that will call a function only once per `delay` """
def wrapper( func ): # the actual decorator
cache = dict( next = 0 ) # cache the result and time
def limited( *args, **kwargs):
if time.time() > cache['next']: # is it time to call again
cache['result'] = func( *args, **kwargs) # do the function
cache['next'] = time.time() + delay # dont call before this time
return cache['result']
return limited
return wrapper
It works like this:
@limit_rate(1.5)
def test():
print "Called test()"
time.sleep( 1 )
return int(time.time())
print [test() for _ in range(5)] # test is called just once
You would simply add this decorator somewhere and decorate your update_results function with it.
A:
Figured it out. I call the decorated function with a delay using any_widget.after(delay_in_ms, function).
| 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 search many times in a row. Since the results will be coming from a database query, that generates a lot of unnecessary traffic. What I really want is for it to update every second or so, or to wait a second after the user stops typing and then search. What's the easiest way to do that?
Thanks
UPDATE: That works great for what I described, but now I've realized that I also need to trigger an update after the user stops typing. Otherwise, the last few characters are never included in the search. I think I have to un-accept the answer in order for this to go back into the list of questions...
| [
"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 memory, so I switched it over to FastCGI using this module.
Overall, it still works fine, but there is one major annoyance: I can't seem to be able to see anything that gets written to the standard error stream. If anything goes wrong, my usual source of useful clues for what to do about it no longer works. Before, I used to see stuff sent to standard error in my Apache error log. Now, it just seems to disappear.
I tried making a test script, and writing strings using sys.stderr.write (from various places), and environ["wsgi.errors"].write (from within my app, where environ is the first parameter passed to the app by the WSGI/FastCGI wrapper). Either way, I couldn't find them. Does anyone know why, or how to access this data?
Keep in mind that this is my first time ever using FastCGI, so please let me know if I am making a bad choice by using this fcgi module.
A:
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 a call to its .getvalue() method.
To capture any uncaught exception just before it terminates your code, assign to sys.excepthook a function of yours in which you get the information and emit it in any way of your choice; or, to get and emit anything that was written to sys.stderr even without an exception (if that's what you want -- I'm not sure, from your question), use atexit to
register your grab-info-and-emit-it function.
| 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 still works fine, but there is one major annoyance: I can't seem to be able to see anything that gets written to the standard error stream. If anything goes wrong, my usual source of useful clues for what to do about it no longer works. Before, I used to see stuff sent to standard error in my Apache error log. Now, it just seems to disappear.
I tried making a test script, and writing strings using sys.stderr.write (from various places), and environ["wsgi.errors"].write (from within my app, where environ is the first parameter passed to the app by the WSGI/FastCGI wrapper). Either way, I couldn't find them. Does anyone know why, or how to access this data?
Keep in mind that this is my first time ever using FastCGI, so please let me know if I am making a bad choice by using this fcgi module.
| [
"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).
They just work now, but the speed is very low. Here are some of my test on 1GB size (that is, 10^7 pieces) of data:
If I disable Rpy2 calls to make a dry run, it takes about 90min for Python to loop all through on a Intel(R) Xeon(TM) CPU 3.06GHz using one single thread.
If I enable full functionality and multithreading on that Xeon dual core, it (will by estimation) take ~200hrs for the program to finish.
I killed the Python program several times the call stack is almost alwarys pointing to Rpy2 function interface. I also did profiling, which gives similar results.
All these observations indicates the R part called by Rpy2 is the bottleneck. So I profiled a standalone version of my R program, but the profiling summary points to "Anonymous". I am still pushing my way to see which part of my R script is the most time consuming one. ****updated, see my edit below*****
There are two suspicious candidates through, one being a continuous wavelets transformation (CWT) and wavelets transformation modulus maxima (WTMM) using wmtsa from cran[1], the other being a non-linear fitting of ex-gaussion curve.
What come to my mind are:
for fitting, I could substitute R routing with inline C code? there are many fitting library available in C and fortran... (idea from the net; I never did that; unsure)
for wavelet algorithms.... I would have to analyze the wmtsa package to rewrite hotspots in C? .... reimplementing the entire wmtsa package using C or fortran would be very non-trivial for me. I have not much programming experience.
the data piece in file is organized in 20 consecutive Bytes, which I could map directly to a C-like char* array? at present my Python program just read one Byte at a time and append it to a list, which is slow. This part of code takes 1.5 hrs vs. ~200 hrs for R, so not that urgent.
This is the first time I meet program efficiency in solving real problems . I STFW and felt overwhelmed by the informations. Please give me some advice for what to do next and how.
Cheers!
footnotes:
http://cran.r-project.org/web/packages/wmtsa/index.html
* Update *
Thanks to proftools from cran, I managed to create a call stack graph. And I could see that ~56% of the time are spent on wmtsa, code snippet is like:
W <- wavCWT(s,wavelet="gaussian1",variance=1/p) # 1/4
W.tree <-wavCWTTree(W) # 1/2
holderSpectrum(W.tree) # 1/4
~28% of time is spent on nls:
nls(y ~ Q * dexGAUS(x, m, abs(s), abs(n)) + B, start = list(Q = 1000, m = h$time[i], s = 3, n = 8, B = 0), algorithm="default", trace=FALSE)
where evaluation of dexGAUS from gamlss.dist package takes the majority of time.
remaining ~10% of R time are spent on data passing/split/aggregation/subset.
A:
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.
import array
myNums = array.array('B', myStr)
Now myNums is an array of each byte easily converted... see help(array.array)... in fact, looking at that it looks like you can get it directly from a file that way through the array.
That should get rid of 1.4 hours of your data reading.
A:
My understanding is that you have:
python code that uses rpy2 in places
performance issues that can be traced to calls to rpy2
the performance issues do not currently appear to have much to do with rpy2 itself, as the underlying R is largely responsible for the running time
a part of your R code was reading bytes one at a time and append them to a list, which you improved by moving that part to Python
It is somehow hard to try helping without seeing the actual code and you may want to consider:
a buffering strategies for reading bytes (as this was already answered by John).
work on optimizing your R code
consider trivial parallelization (and eventually rent compute space on the cloud)
| 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. Here are some of my test on 1GB size (that is, 10^7 pieces) of data:
If I disable Rpy2 calls to make a dry run, it takes about 90min for Python to loop all through on a Intel(R) Xeon(TM) CPU 3.06GHz using one single thread.
If I enable full functionality and multithreading on that Xeon dual core, it (will by estimation) take ~200hrs for the program to finish.
I killed the Python program several times the call stack is almost alwarys pointing to Rpy2 function interface. I also did profiling, which gives similar results.
All these observations indicates the R part called by Rpy2 is the bottleneck. So I profiled a standalone version of my R program, but the profiling summary points to "Anonymous". I am still pushing my way to see which part of my R script is the most time consuming one. ****updated, see my edit below*****
There are two suspicious candidates through, one being a continuous wavelets transformation (CWT) and wavelets transformation modulus maxima (WTMM) using wmtsa from cran[1], the other being a non-linear fitting of ex-gaussion curve.
What come to my mind are:
for fitting, I could substitute R routing with inline C code? there are many fitting library available in C and fortran... (idea from the net; I never did that; unsure)
for wavelet algorithms.... I would have to analyze the wmtsa package to rewrite hotspots in C? .... reimplementing the entire wmtsa package using C or fortran would be very non-trivial for me. I have not much programming experience.
the data piece in file is organized in 20 consecutive Bytes, which I could map directly to a C-like char* array? at present my Python program just read one Byte at a time and append it to a list, which is slow. This part of code takes 1.5 hrs vs. ~200 hrs for R, so not that urgent.
This is the first time I meet program efficiency in solving real problems . I STFW and felt overwhelmed by the informations. Please give me some advice for what to do next and how.
Cheers!
footnotes:
http://cran.r-project.org/web/packages/wmtsa/index.html
* Update *
Thanks to proftools from cran, I managed to create a call stack graph. And I could see that ~56% of the time are spent on wmtsa, code snippet is like:
W <- wavCWT(s,wavelet="gaussian1",variance=1/p) # 1/4
W.tree <-wavCWTTree(W) # 1/2
holderSpectrum(W.tree) # 1/4
~28% of time is spent on nls:
nls(y ~ Q * dexGAUS(x, m, abs(s), abs(n)) + B, start = list(Q = 1000, m = h$time[i], s = 3, n = 8, B = 0), algorithm="default", trace=FALSE)
where evaluation of dexGAUS from gamlss.dist package takes the majority of time.
remaining ~10% of R time are spent on data passing/split/aggregation/subset.
| [
"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 definition looks like:
class Frame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
style=(wx.DEFAULT_FRAME_STYLE | wx.WS_EX_CONTEXTHELP) ^
(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX),
pos=(20, 20))
self.SetExtraStyle(wx.FRAME_EX_CONTEXTHELP)
self.createOtherStuffHere()
self.Show()
How do I tell a widget that its help balloon should say: "This button cooks spam, ham, and eggs"
A:
Look into context help classes
ContextHelp
ContextHelpButton
Important thing to note is you have to initialize help provider e.g.
provider = wx.SimpleHelpProvider()
wx.HelpProvider_Set(provider)
and set help text for widgets e.g.
panel.SetHelpText("This is a wx.Panel.")
Working example:
import wx
class Frame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
style=(wx.DEFAULT_FRAME_STYLE | wx.WS_EX_CONTEXTHELP) ,
pos=(20, 20))
self.SetExtraStyle(wx.FRAME_EX_CONTEXTHELP)
self.CreateStatusBar()
self.createOtherStuffHere()
self.Show()
def createOtherStuffHere(self):
panel = wx.Panel(self)
panel.SetHelpText("This is a wx.Panel.")
self.label = wx.StaticText(panel, style=wx.WS_EX_CONTEXTHELP, label="Click me I may provide some help?", size=(200,30))
self.label.SetHelpText("This is the help though not so helpful!")
self.edit = wx.TextCtrl(panel, pos=(20,50))
self.edit.SetHelpText("i am a edit box")
self.helpButton = wx.ContextHelpButton(panel, pos=(20,100))
provider = wx.SimpleHelpProvider()
wx.HelpProvider_Set(provider)
app = wx.PySimpleApp()
frame = Frame(None, "Test")
app.SetTopWindow(frame)
app.MainLoop()
| 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):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
style=(wx.DEFAULT_FRAME_STYLE | wx.WS_EX_CONTEXTHELP) ^
(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX),
pos=(20, 20))
self.SetExtraStyle(wx.FRAME_EX_CONTEXTHELP)
self.createOtherStuffHere()
self.Show()
How do I tell a widget that its help balloon should say: "This button cooks spam, ham, and eggs"
| [
"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:
AttributeError: '_csv.writer' object has no attribute 'fileobj'
A:
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.
That 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 the object:
w = csv.writer(fileobj, dialect, ...)
So if you need to access that object later, just save it in another variable.
A:
From what I can tell, there is no straightforward way to get the file object back out once you put it into a csv object. My approach would probably be to subclass the csv writer and readers you're using so they can carry that data around with them. Of course, this assumes the ability to be able to directly access the types of classes the factory function makes (among other things).
| 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 'fileobj'
| [
"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 seems complete:
httplib seems pretty low level, more like a HTTP packet sniffer really.
urllib2 is some sort of elaborate hoax. There are a dozen handlers for various web client functions, but mandatory HTTP features like Content-Encoding appearantly aren't.
mechanize: is nice, already somehwat overkill for my tasks, but only supports CE 'gzip'.
httplib2: sounded most promising, but actually fails on 'deflate' encoding, because of the disparity of raw deflate and zlib streams.
So are there any other options? I can't believe I'm expected to reimplement workarounds for above libraries. And it's not a good idea to distribute patched versions alongside my application, because packagers might remove it again if the according library is available as separate distribution package.
I almost don't dare to say, but the http functions API in PHP is much nicer. And besides Content-Encoding:*, I might somewhen need multipart/form-data too. So, is there a comprehensive 3rd party library for http retrieval?
A:
I would consider either invoking a child process of cURL or using python bindings for libcurl.
From this description cURL seems to support gzip and deflate.
| 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 packet sniffer really.
urllib2 is some sort of elaborate hoax. There are a dozen handlers for various web client functions, but mandatory HTTP features like Content-Encoding appearantly aren't.
mechanize: is nice, already somehwat overkill for my tasks, but only supports CE 'gzip'.
httplib2: sounded most promising, but actually fails on 'deflate' encoding, because of the disparity of raw deflate and zlib streams.
So are there any other options? I can't believe I'm expected to reimplement workarounds for above libraries. And it's not a good idea to distribute patched versions alongside my application, because packagers might remove it again if the according library is available as separate distribution package.
I almost don't dare to say, but the http functions API in PHP is much nicer. And besides Content-Encoding:*, I might somewhen need multipart/form-data too. So, is there a comprehensive 3rd party library for http retrieval?
| [
"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.
now my question is : i need to stop invoking cmd prompt
kudos to all
sag
A:
Try this (untested):
import subprocess
CREATE_NO_WINDOW = 0x08000000
args = [...]
subprocess.check_call(["segwin.exe"] + args, creationflags=CREATE_NO_WINDOW)
Note 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 instead.
In general, avoid os.system() and use the subprocess module whenever possible. os.system() always starts a shell, which is nonportable unnecessary on most cases.
A:
This is actually specific to Windows. Windows has decided that segwin.exe is a console-based application (uses the Console subsystem from the Windows C interface).
I know how to invoke an prompt for apps that don't necessarily want one, but not the reverse, you could try using this, or this.
| 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 prompt
kudos to all
sag
| [
"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, but it's possible to run a
CherryPy application behind it (or
lighttpd, or IIS). CherryPy
applications run on Windows, Linux,
Mac OS X and any other platform
supporting Python.
Having come from PHP and wanting to learn Python, I came upon a thread here in SO while looking for a webserver I can setup to start Python web development. However, after almost googling myself to death, I can't still find one. I came across entries like "Django has its own lightweight webserver" and the aforementioned Cherrypy.
What I am confused about is this :I was used to using XAMPP, where I have a web server, a database server and my application and I can't visualize the idea of a "web server inside the application itself". How do I connect to my database server then? How do I configure stuff like custom urls and directory protection (much like what I do in Apache)?
Thanks in advance guys!
A:
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 quote mentions) is an example of one, focusing on speed and simplicity; cherrypy is another, focusing on simplicity and Python support.
Of course you can still configure several aspects, see the tutorial section about the configuration files for a short overview, the reference for more details -- but it won't be anywhere as rich as Apache (hey, few webservers are, except maybe IIS;-). Probably some configuration options that you may feel are missing may be easily compensated with Python code, but not all -- that's why you may want to run cherrypy "behind" other servers!
The way you code your Python web apps need not be constrained by the web server you're using: just program to the WSGI standard (and that's what just about all web app frameworks these days support), and your deployment options are boundless -- from cherrypy, or even just the reference wsgi implementation that comes with the Python standard library (only recommended for development!-), all the way to Apache with mod_wsgi, IIS, even Google App Engine (it supports WSGI, too!-).
A:
How do I connect to my database server then? How do I configure stuff like custom urls and directory protection (much like what I do in Apache)?
You still have a separate database server, like Postgres or MySQL. Your interface can be either one of the Python database interfaces or an ORM, like in PHP. Doing stuff like custom URLs is handled by the framework. I can't comment on CherryPy but in Pylons there is a class that configures routing, configured in routing.py.
Think about the difference like this:
A PHP framework like Symfony expects to be entered when *.php is invoked by your web server. That's the interface to your application: Symfony creates an index.php which, when invoked, initializes the different framework services such as routing and the ORM. It parses the URI and figures out which controller/action pair should receive the request.
A Python framework, like Pylons, comes with a web server -- an application which listens for HTTP requests on a configured port. That server, when it receives a request, does the same thing. It creates a database connection and uses the routing map configured for your application to figure out where to send the request. Unlike the PHP framework, it also will check to see if the URI references a static file and returns that instead if it's configured to do so. In the LAMP environment that's the purview of Apache.
A:
You can use something like mod_wsgi to connect httpd to your Python applications, but Python itself is powerful enough to write a web server (and even a database) in, and the Python standard library even includes a few simple servers that can be used or expanded upon.
A:
"web server inside the application itself" -- all that is meant by this is that the same python process handles both the traditional web server role of server static files (HTML, CSS, images, etc) as well as generating dynamic content produced by the application. Thus the python process itself listens for browser connections to port 80, for example, as opposed to having a separate web server process handle that part of the overall web application functionality.
A:
I think that if you'd go through the Django tutorial, it would be a little bit more clear.
Essentially, there is a built-in web server that you use for development. You can then move your project to a "real" environment without having to make changes to it (or at least very few). Same thing goes for databases, you can start out using sqlite and when you want to deploy you application, you can change to another database like for example MySQL. This is done easily with only a few configuration changes.
| 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, or IIS). CherryPy
applications run on Windows, Linux,
Mac OS X and any other platform
supporting Python.
Having come from PHP and wanting to learn Python, I came upon a thread here in SO while looking for a webserver I can setup to start Python web development. However, after almost googling myself to death, I can't still find one. I came across entries like "Django has its own lightweight webserver" and the aforementioned Cherrypy.
What I am confused about is this :I was used to using XAMPP, where I have a web server, a database server and my application and I can't visualize the idea of a "web server inside the application itself". How do I connect to my database server then? How do I configure stuff like custom urls and directory protection (much like what I do in Apache)?
Thanks in advance guys!
| [
"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 aiming that superusers can access the standard django admin
Looking around in the docs it looks like AdminSite is where i should be headed
A:
It is indeed possible using django permission system. Check out. You can easily extends this to your own views.
All 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.
Remember, permission also limits 'add/change/delete' separately. But works only to limit permissions on type of objects as a whole and not on particular objects.
Happy Coding.
| 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 admin
Looking around in the docs it looks like AdminSite is where i should be headed
| [
"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:
Main feature of Tornado is that it is high performance web-server written in Python, for creating web applications using Python programming language.
Running 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 no way to run Tornado as CGI script.
A:
flup provides a CGI-to-WSGI adapter, but you really should consider using something like FastCGI instead.
| 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 modules which seem to be already in trunk/pyobjc e.g. it says (if I switch off my internet)
No local packages or download links
found for
pyobjc-framework-XgridFoundation==2.3b1
but trunk/pyobjc has pyobjc-framework-XgridFoundation
A:
Sorry. The documentation in the http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-core/Install.txt explains the process
| 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 trunk/pyobjc e.g. it says (if I switch off my internet)
No local packages or download links
found for
pyobjc-framework-XgridFoundation==2.3b1
but trunk/pyobjc has pyobjc-framework-XgridFoundation
| [
"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 simple way of doing this using re module or string module but I must be missing something.
A:
Ksh:
$ s='abc/def/ghi'
$ echo ${s%%/*}
abc
$ echo ${s%/*}
abc/def
$ echo ${s#*/}
def/ghi
$ echo ${s##*/}
ghi
Python:
>>> s='abc/def/ghi'
>>> print s[:s.find("/")]
abc
>>> print s[:s.rfind("/")]
abc/def
>>> print s[s.find("/")+1:]
def/ghi
>>> print s[s.rfind("/")+1:]
ghi
Edit:
To handle the case in which the pattern is missing, as pointed out by ΤΖΩΤΖΙΟΥ:
>>> s='abc/def/ghi'
>>> t='no slash here'
>>> print s[:s.find("/") % (len(s) + 1)]
abc
>>> print t[:t.find("/") % (len(t) + 1)]
no slash here
>>> print s[:s.rfind("/") % (len(s) + 1)]
abc/def
>>> print t[:t.rfind("/") % (len(t) + 1)]
no slash here
>>> print s[s.find("/")+1:]
def/ghi
>>> print t[t.find("/")+1:]
no slash here
>>> print s[s.rfind("/")+1:]
ghi
>>> print t[t.rfind("/")+1:]
no slash here
A:
${name##*/}
Is equivalent to:
re.match(".*?([^/]*)$")[1]
${name%/*}
Is equivalent to:
re.match("(.*?)[^/]*$")[1]
A:
There is no special status for "strip to the left", "strip to the right", etc. The one general method is re.sub -- for example, to "strip everything up to the last slash included" ("to the left" as ksh conceptualizes it):
name = re.sub(r'(.*/)(.*)', r'\2', name)
and to strip "the last slash and everything following" ("to the right" per ksh):
name = re.sub(r'(.*)/.*', r'\1', name)
These match as much as possible because the * in RE patterns is greedy; use *? instead for non-greedy matching ("as little as possible") instead.
A:
>>> def strip_upto_max(astring, pattern):
"${astring##*pattern}"
return astring.rpartition(pattern)[2]
>>> def strip_from_max(astring, pattern):
"${astring%%pattern*}"
return astring.partition(pattern)[0]
>>> def strip_upto(astring, pattern):
"${astring#*pattern}"
return astring.partition(pattern)[2]
>>> def strip_from(astring, pattern):
"${astring%pattern*}"
return astring.rpartition(pattern)[0]
>>> strip_from("hello there", " t")
'hello'
>>> strip_upto("hello there", " t")
'here'
>>> text= "left/middle/right"
>>> strip_from(text, "/")
'left/middle'
>>> strip_upto(text, "/")
'middle/right'
>>> strip_upto_max(text, "/")
'right'
>>> strip_from_max(text, "/")
'left'
But if your intention is to use it with paths, check whether the os.path.dirname (${name%/*}) and os.path.basename (${name##*/}) functions have the functionality you require.
| 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 missing something.
| [
"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
15 100 140 30 $ 14^]
(2003 2 ! -6 �021 0 � 14 ! 2 3! 1 0 35454
0$ ^@0 0 0 "0 "63 194 (56 188 26 27" 24 0 0 10� 994! 8 58
0 0 " � 0 0 32�47 32767 32767 ! 1
The output basically should be:
16 38 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 0 35454
0 0 0 0 0 63 194 56 188 26 27 24 0 0 10 994 8 58
0 0 0 0 32 47 32767 32767 1
What's the most straightforward way to do this?
A:
import re
output_string = re.sub(r'[^\d\s-]', '', input_string)
The 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.
A:
If you want to keep just digits, plus and minus signs, and all whitespace, simplest might be
import re
...
line = re.sub(r'[^\d\s+-]+', '', line)
which reads "replace each sequence of one or more non-digit non-whitespace with nothing".
Faster would be the translate method of strings, but it is quite a bit less simple to set up, so, since you ask for "straightforward", I suggest the re approach (now brace for the sure-to-come screeches of the re-haters...;-).
A:
''.join([x for x in s if x in string.digits+string.whitespace])
or if what you really want is a list of the numbers:
import re
re.findall('\d+',s)
A:
LOL @Alex's regex comment... hopefully there aren't too many haters. With that said however, although they're faster because they're executed in C, regexes aren't my first choice... perhaps i've been biased by the famous jwz quote: '''Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.'''
I will say that solving this homework exercise is tricky because solutions are fraught with errors, as seen in the existing solutions so far. Perhaps this is serendipity because it requires the OP to debug and correct those suggestions instead of just cutting-and-pasting them verbatim into their assignment solution.
As far as the problems go, they include but are not limited to:
leaving successive spaces
removing negative signs, and
merging multiple numbers together
Bottom line... which solutions do I like best? I would start one of the following and debug from there:
For regex, i'll pick:
@Alex's solution or @Matt's if I want just the data instead of the "golden" string
For string processing, I'll modify @Matt's solution to:
keep = set(string.whitespace+string.digits+'+-')
line = ''.join(x for x in line if x in keep)
Finally, @Greg has a good point. Without a clear spec, these are just partial solutions.
| 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 0 35454
0$ ^@0 0 0 "0 "63 194 (56 188 26 27" 24 0 0 10� 994! 8 58
0 0 " � 0 0 32�47 32767 32767 ! 1
The output basically should be:
16 38 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 0 35454
0 0 0 0 0 63 194 56 188 26 27 24 0 0 10 994 8 58
0 0 0 0 32 47 32767 32767 1
What's the most straightforward way to do this?
| [
"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 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 HTML 5 in the next 2 years (although there are far fewer quirks so it's easier to parse, at least so far), but there's no particular reason not to use BeautifulSoup. The community is still active with support, etc. on the google group, and obviously the source code is available to you to enhance as you require.
A:
I would steer clear of lxml, its too fussy for my taste. I'd try html5lib if I were you. It not only parses html, but deals robustly with the sort of errors you see in the tag soup known as invalid html.
It even has a BeautifulSoup emulation mode, producing a parse tree in the Beautiful Soup form to ease porting old code across:
import html5lib
from html5lib import treebuilders
f = open("mydocument.html")
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup"))
minidom_document = parser.parse(f)
A:
Try lxml lib: http://codespeak.net/lxml/
A:
Well, if you're not duty-bound to python, you could always use a TagSoup parser. It's a Java library, but it gives very good results. You could also just use Tidy to clean your input before trying to parse it.
| 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 disabuse me of this preference if it is misinformed). This raises a few questions, however:
Where should I put the tests? In the same file as the code they are testing (or in docstrings for doctests)? Or is it considered better to separate them out into their own directory?
How can I run all the tests in the whole module from the command-line in one go?
How can I report the code coverage of the test suite?
Any other best-practices I should be aware of for unit testing in python?
A:
feel free to disabuse me of this
preference if it is misinformed
I 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 was starting, it seemed a great little trick, and if something is worth doing it's worth doing in excess -- right?-)
Wrong. Except for gmpy, where redoing everything as proper unit tests would be too much rework, I've never made that mistake again: these days, I use unit tests as unit tests, and doctests just to check my docs, as they've always been meant to be used. What doctests do (compare an expected with an actual result for equality -- that's all) is just not a good or sound basis to build a solid test suite on. It was never intended otherwise.
I would recommend you look at nose. The unittest module in the new Python 2.7 is much richer and nicer, and if you're stuck on 2.4, 2.5 or 2.6 you can still use the new features with the unittest2 which you can download and install; nose complements unittest quite well.
If you can't stand unittest (but -- give it a try, it grows on you!-), maybe try py.test, an alternative package with a pretty different philosophy.
But, please, don't stretch doctest to test stuff other than examples in docs! The exact-equality comparison will stand in your way far too often, as I've had to learn at my (metaphorical;-) expense in gmpy...
A:
I don't like doctests for these reasons:
You can't run a subset of the tests. When a test fails, it's useful to run just one test. Doctest provides no way to do that.
If a failure happens in the middle of the doctest, the whole thing stops. I'd rather see all the results to decide how to tackle a breakage.
The coding style is stylized, and has to have printable results.
Your code is executed in a special way, so it's harder to reason about how it will be executed, harder to add helpers, and harder to program around the tests.
This list was taken from my blog post Things I don't like about doctest, where there's more, and a long thread of comments debating the points.
About coverage: I don't believe there's a coverage tool for Python that will measure coverage within doctests. But since they are simply long lists of statements with no branches or loops, is that a problem?
A:
I have this suspicion that Alex might be a fair bit ahead of me on the programmer's curve, but if you want the perspective of somebody with some Python experience (as a "user" rather than an expert or evangelist), yet not in the same league, my findings about unit testing have been pretty much the same.
Doctests might sound great for simple testing in the beginning, and I went in that direction for some personal project at home because it had been recommended elsewhere.
At work we use nose (although so canned and wrapped up I was under the impression we'd been using pyUnit until not long ago), and a few months back I moved to nose at home too.
The initial setup time and management overhead, and the separation from the actual code, might seem unnecessary in the beginning, especially when you're testing something that isn't that large a codebase, but in the long run I've found doctests getting in the way of every single refactoring or restructuring I wanted to do, rather hard to maintain, practically impossible to scale, and offsetting the initial savings very quickly. And yes, I'm aware that unit testing isn't the same as integration testing, but doctests tend to define your units for you rather too strictly.
They're also not well suited to unit based agile if you ever decide it's a valid sketching tool or dev model.
It might take you a bit to plan and then refine your unit tests the way pyUnit or nose steer you towards, but chances are that even in the short term you'll find it's actually helping you out on many levels. I know it did for me, and I'm relatively new to the complexity and scale of the codebase I'm working on these days. Just have to clench your teeth for the first few weeks.
A:
For coverage, check out the excellent coverage.py.
Otherwise, everything Alex Martelli wrote is very much on point.
A:
doctests are great for quick, minor unit tests that describe what some of the basic usages of the objects in question, (as they show up in docstrings, and hence help(whatever), etc).
I've personally found extensive and more thorough testing to be more effective using the unittest module, and now the 2.7 module (back ported to unittest2) has even more handy assertions. You can set up test suites and as complex a scenario as you like with the unit testing framework and cover whole swaths of different tests in one go (command-line wise)
coverage.py, by Ned Batchelder and as @bstpierre mentions will work with either of these, and I recommend it for seeing what you've got tested of the code and what doesn't. You can add it into a CI system (i.e. Hudson or whatever you like to use) to keep up on what's covered and not, and the HTML reports are fantastic for seeing what hasn't been hit with testing coverage. Coverage supports Junit xml output, which many CI systems know how to provide charted on-going results to let you see the build getting better or worse over time.
A:
I agree with all the above points raised about doctest not scaling and I prefer to stick with unittest.
One tip I can contribute is to invoke the unit tests from the code handling __name__ == "__main__ so if the test file is run as a script it will run its tests.
eg:
#!/usr/bin/env python
"""
Unit tests for the GetFiles.py utility
"""
import unittest
from FileUtilities import getTree
class TestFileUtilities(unittest.TestCase):
def testGetTree(self):
"""
Tests that a known tree is found and incidentally confirms
that we have the tree we expected to use for our current
sample extraction.
"""
found = getTree('./anzmeta-dtd', '.pen')
expected_path_tail = ['ISOdia.pen',
'ISOgrk1.pen',
'ISOtech.pen']
for i, full_path in enumerate(found):
assert full_path.endswith( expected_path_tail[i] ), expected_path_tail[i]
# other tests elided
if __name__ == "__main__":
# When this module is executed from the command-line, run all its tests
unittest.main()
| 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). This raises a few questions, however:
Where should I put the tests? In the same file as the code they are testing (or in docstrings for doctests)? Or is it considered better to separate them out into their own directory?
How can I run all the tests in the whole module from the command-line in one go?
How can I report the code coverage of the test suite?
Any other best-practices I should be aware of for unit testing in python?
| [
"\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\\src\\ss\\samplefile\\test')
However it says that my class file is not found. What is wrong?
A:
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 build file ... or when you want to check your project into version control.)
Your immediate problem is that you've got the command syntax for the java command wrong. The name of the entry point class is specified by giving a fully qualified class name, not a pathname. And you probably need to use the -cp option as well.
For details on how to do this right, refer to the java manual page.
| 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 file is not found. What is wrong?
| [
"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,
Rupesh
A:
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
| 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
What would be the elegant\pythonic way of doing this?
A:
There's already a project-wide settings.py file. This is the perfect place to put your own custom setttings.
A:
you can provide settings in your settings.py like
MY_SETTING = 'value'
and in any module you can fetch it like
from django.conf import settings
settings.MY_SETTING
A:
Create a configuration module.
Configuration.py: (in your project/app source directory)
MYCONST1 = 1
MYCONST2 = "rabbit"
Import it from other source files:
from Configuration import MYCONST1,MYCONST2
...
A:
Django apps are meant to be (more or less) pluggable. Therefore, you are not supposed to hack into the code of an app in order to parametrize what you want (it would be quite a mess if you had to do this ! Imagine you want to upgrade an app you downloaded on internet... you would have to re-hack into the code of the new version ?!?).
For this reason you shouldn't add app-level settings at the app level, but rather put them together somewhere in your project-wide settings.py.
| 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 implement a safe way to execute a very basic subset of python, or something syntactically similar at least, from within a python based web-app.
The obvious answer is to implement a DSL (Domain Specific Language), however, I have no experience with that, nor do I have any idea where to begin, and a lot of the resources available seem to go a little over my head. I'm hoping that maybe there is something already out there which will allow me to essentially generate a secure python-callable function from a string in a database. the language really only needs to support assignment, basic math, if/else, and case insensitive string comparisons. any other features are a bonus, but I think most things can be done with just that, no need for complex data structures, classes, functions, etc.
If no such thing currently exists, I'm willing to look into the possibility of creating one, but as I said, I have no idea how to go about that, and any advice in that regard would be appreciated as well.
A:
Restricted Python environments are hard to make really safe.
Maybe something like lua is a better fit for you
A:
PySandbox might help. I haven't tested it, just found it linked elsewhere.
A:
You could use Pyparsing to implement your DSL, provided the expressions involved won't be too complex (you don't give full details on that but you imply the requirements are pretty simple). See the examples page including specifically fourFn.py or simpleCalc.py.
A:
You could implement a subset of Python by using the ast module to parse Python code into an abstract syntax tree then walk the tree checking that it only uses the subset of Python that you allow. This will only work in Python 2.x since Python 3 has removed the ast module.
However even using this method it will be hard to create something that is 100% secure, since even the most innocuous code could allow the user to write something that could blow up your application, e.g. by allocating more memory than you have available or putting the program into an infinite loop using all the CPU.
| 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 something syntactically similar at least, from within a python based web-app.
The obvious answer is to implement a DSL (Domain Specific Language), however, I have no experience with that, nor do I have any idea where to begin, and a lot of the resources available seem to go a little over my head. I'm hoping that maybe there is something already out there which will allow me to essentially generate a secure python-callable function from a string in a database. the language really only needs to support assignment, basic math, if/else, and case insensitive string comparisons. any other features are a bonus, but I think most things can be done with just that, no need for complex data structures, classes, functions, etc.
If no such thing currently exists, I'm willing to look into the possibility of creating one, but as I said, I have no idea how to go about that, and any advice in that regard would be appreciated as well.
| [
"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', 'UTF-8')
msg['Subject'] = esubj
msg['From'] = efrom
msg['To'] = eto
s = smtplib.SMTP()
s.connect("mail.driversoft.net", 25)
s.login("info@mysite.net", "1234567")
s.sendmail(efrom, [eto], msg.as_string())
s.quit()
and try connect to the slot
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext"))
when I try start this app, I don't see a form, on my email revive message, and in console
Traceback (most recent call last):
File "C:\Documents and Settings\a.ivanov\My Documents\Aptana Studio Workspace\test1\src\wxtest.py", line 61, in <module>
ui.setupUi(Dialog)
File "C:\Documents and Settings\a.ivanov\My Documents\Aptana Studio Workspace\test1\src\wxtest.py", line 33, in setupUi
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysqite.net", "test@mysite.net", "subject", "bodytext"))
TypeError: arguments did not match any overloaded call:
QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 2 has unexpected type 'bytes'
How can I do a form i wich I wrote subject and text then press Send button and get message by email?
Thanks!
full code
from PyQt4 import QtCore, QtGui
import smtplib
from email.mime.text import MIMEText
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 330)
self.textEdit = QtGui.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(10, 70, 381, 221))
self.textEdit.setObjectName("textEdit")
self.subjEdit = QtGui.QLineEdit(Dialog)
self.subjEdit.setGeometry(QtCore.QRect(10, 30, 371, 20))
self.subjEdit.setObjectName("subjEdit")
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(100, 300, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtGui.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(210, 300, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(10, 10, 46, 13))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(11, 53, 46, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), Dialog.close)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext"))
QtCore.QMetaObject.connectSlotsByName(Dialog)
#this is my function
def SendEmail(self,efrom,eto,esubj,ebody):
msg = MIMEText( ebody.encode('UTF-8'),'html', 'UTF-8')
msg['Subject'] = esubj
msg['From'] = efrom
msg['To'] = eto
s = smtplib.SMTP()
s.connect("mail.driversoft.net", 25)
s.login("info@mysite.net", "1234567")
s.sendmail(efrom, [eto], msg.as_string())
s.quit()
#print("done")
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Dialog", "Send", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("Dialog", "Close", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Subject", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Email text", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
A:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext"))
It 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 callback, not call that function in connect.
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.pushButtonClicked)
def pushButtonClicked(self):
self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext")
| 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'] = efrom
msg['To'] = eto
s = smtplib.SMTP()
s.connect("mail.driversoft.net", 25)
s.login("info@mysite.net", "1234567")
s.sendmail(efrom, [eto], msg.as_string())
s.quit()
and try connect to the slot
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext"))
when I try start this app, I don't see a form, on my email revive message, and in console
Traceback (most recent call last):
File "C:\Documents and Settings\a.ivanov\My Documents\Aptana Studio Workspace\test1\src\wxtest.py", line 61, in <module>
ui.setupUi(Dialog)
File "C:\Documents and Settings\a.ivanov\My Documents\Aptana Studio Workspace\test1\src\wxtest.py", line 33, in setupUi
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysqite.net", "test@mysite.net", "subject", "bodytext"))
TypeError: arguments did not match any overloaded call:
QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 2 has unexpected type 'bytes'
How can I do a form i wich I wrote subject and text then press Send button and get message by email?
Thanks!
full code
from PyQt4 import QtCore, QtGui
import smtplib
from email.mime.text import MIMEText
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 330)
self.textEdit = QtGui.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(10, 70, 381, 221))
self.textEdit.setObjectName("textEdit")
self.subjEdit = QtGui.QLineEdit(Dialog)
self.subjEdit.setGeometry(QtCore.QRect(10, 30, 371, 20))
self.subjEdit.setObjectName("subjEdit")
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(100, 300, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtGui.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(210, 300, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(10, 10, 46, 13))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(11, 53, 46, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), Dialog.close)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.SendEmail("info@mysite.net", "test@mysite.net", "subject", "bodytext"))
QtCore.QMetaObject.connectSlotsByName(Dialog)
#this is my function
def SendEmail(self,efrom,eto,esubj,ebody):
msg = MIMEText( ebody.encode('UTF-8'),'html', 'UTF-8')
msg['Subject'] = esubj
msg['From'] = efrom
msg['To'] = eto
s = smtplib.SMTP()
s.connect("mail.driversoft.net", 25)
s.login("info@mysite.net", "1234567")
s.sendmail(efrom, [eto], msg.as_string())
s.quit()
#print("done")
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Dialog", "Send", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("Dialog", "Close", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Subject", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Email text", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
| [
"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', 'w').write(urllib2.urlopen("http://mp3.streampower.be/radio1-high.mp3").read())
it doesn't even read the stream.
Is there something like BufferedInputReader from java in python or can anyone give me some pointers as to how I would go about doing this? Reading an audiostream and getting it to stop reading after a while.
Thanks
A:
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:
#!/usr/bin/python
import urllib2
f=file('python.mp3', 'w')
url=urllib2.urlopen("http://mp3.streampower.be/radio1-high.mp3")
while True:
f.write(url.read(1024))
Your code was calling read without a size parameter -- which tries to read the whole thing. It's a stream, so that will be a while. If the stream ever closes, then your call to write could proceed, and you'd go from no file to a huge file in no time.
My sample code here will build you an mp3 file nice and slow. You may need to tweak the 1024 if the streams are sending much faster than typical mp3 bitrates, but this should be fine. (A 128kbps stream would involve 16 system calls per second to write(2), which shouldn't be any stress at all. But at 10mbit speeds or higher, it'd hurt, and you should use a larger read size.)
| 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.streampower.be/radio1-high.mp3").read())
it doesn't even read the stream.
Is there something like BufferedInputReader from java in python or can anyone give me some pointers as to how I would go about doing this? Reading an audiostream and getting it to stop reading after a while.
Thanks
| [
"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 dictionaries to the template. I am using App engine patch with GAE.
Following is a code snippet that I am using in my view:
def getData(request,key):
forum = Topic.get(key)
picData = forum.creator.portfolio_set
response = ''
if picData:
picture = picData[0].userpic
response = HttpResponse(picture, mimetype="image/jpeg")
#response['Content-Type'] = 'image/jpeg'
response['Content-Disposition'] = 'inline'
return render_to_response(request,"forum.html",{"forum":forum,"pic":response })
Now, I am able to render the data within forum variable but not getting how to render the image associated with it. What should I modify in my views file and what should I use in my template to display the image rendered by the views file.
Please suggest.
Thanks in advance.
A:
Solution 1:
Add a generic view to get images e.g. /images/image-id should return image for that ID
def get_image(request, image_id):
....
picture = get from id
return HttpResponse(picture, mimetype="image/jpeg")
Now use image URLs inside your forum.html template, like you would use any normal image URL.
Solution 2: You can directly embed image using data:image see http://en.wikipedia.org/wiki/Data_URI_scheme
so try this
import base64
def getData(request,key):
forum = Topic.get(key)
picData = forum.creator.portfolio_set
pictureSrc = ''
if picData:
picture = picData[0].userpic
pictureSrc = "data:image;base64,%s"%base64.b64encode(picture)
return render_to_response(request,"forum.html",{"forum":forum,"pic":pictureSrc })
| 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 GAE.
Following is a code snippet that I am using in my view:
def getData(request,key):
forum = Topic.get(key)
picData = forum.creator.portfolio_set
response = ''
if picData:
picture = picData[0].userpic
response = HttpResponse(picture, mimetype="image/jpeg")
#response['Content-Type'] = 'image/jpeg'
response['Content-Disposition'] = 'inline'
return render_to_response(request,"forum.html",{"forum":forum,"pic":response })
Now, I am able to render the data within forum variable but not getting how to render the image associated with it. What should I modify in my views file and what should I use in my template to display the image rendered by the views file.
Please suggest.
Thanks in advance.
| [
"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 files of other types.
Any suggestions?
A:
Other than what?
urllib.urlretrieve(url)
should work fine for any filetype. You will often want to specify a filename, rather than use a temp file (the default):
urllib.urlretrieve(url, filename)
There are several other libraries too, but this is fine for basic uses.
| 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()
configuration.read('Email.conf')
email = emailModule.emailModule(configuration)
while(True):
if (datetime.now().minute > 28 and datetime.now().minute < 32):
email.emailWeather()
time.sleep(3000)
I am just wondering is there a better way of doing this in python? IE a more efficient way or more reliable way of doing things.
A:
You can use cron jobs. Schedule it for every 1 hr. starting at 00:30:00.
A:
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
| 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(configuration)
while(True):
if (datetime.now().minute > 28 and datetime.now().minute < 32):
email.emailWeather()
time.sleep(3000)
I am just wondering is there a better way of doing this in python? IE a more efficient way or more reliable way of doing things.
| [
"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 something like
"form action="/login" .....>"
Once user press the login button browser URL wil be abc.com/login. After login I want the
url to be "abc.com" again .
Pls help me .
A:
In you use login view, on successful login you should redirect to the page you want user to land on e.g.
def login_view(request):
if not correct_login:
pass#return response with errors
else
return HttpResponseRedirect("/welcome")
see HttpResponseRedirect or use redirect shortcut.
A:
If you use the built-in Django authentication, you can redirect after login or logout by using the built-in functions. You can redirect to a specific page or you can redirect them to the page they were trying to access.
For example, the doc above uses the following example in using the login_required decorator:
from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name='redirect_to')
def my_view(request):
...
I highly recommend checking out the above doc. When I first setup Django's authentication, I was impressed that it only took me about 30 minutes to set it up the way I wanted it, and most of that time was reading the above page.
| 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="/login" .....>"
Once user press the login button browser URL wil be abc.com/login. After login I want the
url to be "abc.com" again .
Pls help me .
| [
"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 renaming each of these fields to 'id':
Legacy Databases
web2py can connect to legacy databases under some
conditions:
Each table must have a unique
auto-increment integer field called
"id"
Records must be referenced
exclusively using the "id" field.
If
these conditions are not met, it is
necessary to manually ALTER TABLE to
conform them to these requirements, or
they cannot be accessed by web2py.
This should not be thought of as a
limitation, but rather, as one of the
many ways web2py encourages you to
follow good practices.
However, that would require breaking hundreds of existing queries in other
applications that use this database. Surely there must be some way to
specify a name for an existing autonumber field to be used instead of
'id'.
This seems to be an area where Django got it right and web2py got it horribly wrong. Or am I just missing something? Seems I was just missing something...
A:
That statement is obsolete. There are three cases supported by web2py:
a table has a auto-increment field called 'id' (default)
a table has a auto-increment field not called 'id', define the table with
db.define_table('name',Field('id_name','id'),...other fields...)
a table has a different primary key
db.define_table('name',...fields..., primarykey=[....])
The primarykey is a list of field names.
Option 3 does not work with all supported databases but it can easily be extended. We just did not get much request for it so we do not have enough testers for all the possible options. Please move this discussion on the web2py mailing list and we'll be happy to help you more.
A:
Apparently this has not made it into the current web2py book, but it looks like this has in fact been implemented. From the web2py google group: web2py and keyed tables.
NOTE: I found this by browsing New features not documented in PDF book (2 ed)
| 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 some
conditions:
Each table must have a unique
auto-increment integer field called
"id"
Records must be referenced
exclusively using the "id" field.
If
these conditions are not met, it is
necessary to manually ALTER TABLE to
conform them to these requirements, or
they cannot be accessed by web2py.
This should not be thought of as a
limitation, but rather, as one of the
many ways web2py encourages you to
follow good practices.
However, that would require breaking hundreds of existing queries in other
applications that use this database. Surely there must be some way to
specify a name for an existing autonumber field to be used instead of
'id'.
This seems to be an area where Django got it right and web2py got it horribly wrong. Or am I just missing something? Seems I was just missing something...
| [
"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.0, (8322, 8321): 0.99999999999999989, (8328, 8329): 1.0, (8306, 8316): 0.12405229825691289, (8320, 8319): 0.67999999999999989, (8337, 8336): 1.0000000000000002, (8319, 8320): 0.67999999999999989, (8313, 8316): 0.99999999999999989, (8321, 8322): 0.99999999999999989, (8330, 8328): 1.0}
My final goal is to cluster the similar documents together. The data above can be viewed in another way. Let's say the document pair (8313,8306). The similarity score is 0.12405. I can specified that the inverse of the score will be the distance between document 8313 and 8306. Therefore, similar documents will cluster closer together while not-so-similar documents will be further apart based on their distance.
My question is, IS there any open source visualization tool that can help me to achieve this?
A:
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.
A:
I think you have to use MDS
http://en.wikipedia.org/wiki/Multidimensional_scaling
A:
I think Weka can do this. You might have to massage the input file to a different format first. Weka also has an API, though it's in Java, not Python.
A:
There are lots of tools you can use to do this.
There have been other mentions, but you could fairly easily do something like this in Tkinter, PyGTK+, PyQT, matplotlib, or really any graphical lib.
However, a polar plot in matplotlib would be fairly simple:
(untested):
import math
from matplotlib.pyplot import figure, show
# assign your data here
fig = figure()
ax = fig.add_subplot(111, polar=True)
for pair in data:
ax.plot(0, data[pair], 'o')
show()
That should give you a rudimentary visualization. You could also change it around to
ax.plot(pair*math.pi, 1, 'o')
For a different style of visualization.
The matplotlib docs are very good and they have plenty of examples.
A:
Maybe Networkx may help. This example could be a good starting point:
http://networkx.lanl.gov/examples/drawing/knuth_miles.html
| 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.99999999999999989, (8328, 8329): 1.0, (8306, 8316): 0.12405229825691289, (8320, 8319): 0.67999999999999989, (8337, 8336): 1.0000000000000002, (8319, 8320): 0.67999999999999989, (8313, 8316): 0.99999999999999989, (8321, 8322): 0.99999999999999989, (8330, 8328): 1.0}
My final goal is to cluster the similar documents together. The data above can be viewed in another way. Let's say the document pair (8313,8306). The similarity score is 0.12405. I can specified that the inverse of the score will be the distance between document 8313 and 8306. Therefore, similar documents will cluster closer together while not-so-similar documents will be further apart based on their distance.
My question is, IS there any open source visualization tool that can help me to achieve this?
| [
"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 added some random values, but I can't see any
change when I render.
Regarding uvco, the documentation mentions:
Note: These are not seen in the UV editor and they are not a part of UV a UVLayer.
I tried this with the new mesh selected:
import Blender
from Blender import *
import random
scn = Scene.GetCurrent()
ob = scn.objects.active
o = ob.getData()
for v in o.verts:
v.uvco = (random.random(),random.random(),random.random())
print v.uvco
for f in o.faces:
r = (random.random(),random.random())
for i in range(0,4):
f.uv.append(r)
print f.uv
I can see the values change in Terminal, but I don't see any change when I render.
If I reselect the object, the previous face uvs are gone.
Can anyone explain how are UVs set using the Blender 2.49 Python API ?
Thanks
A:
Try simply replacing this line:
o = ob.getData()
with
o = ob.getData(mesh=True)
Due 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 even an "NMesh" - a class that differs from the living "Mesh" class).
With the optional parameter "mesh=True" passed to the getData method you get back the living mesh of the object, and changes therein have effect (that can be seen upon an update forced with after a Blender.Redraw()).
I never tried UV things, however, so there might be more things to it, but I believe this is your issue.
| 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 when I render.
Regarding uvco, the documentation mentions:
Note: These are not seen in the UV editor and they are not a part of UV a UVLayer.
I tried this with the new mesh selected:
import Blender
from Blender import *
import random
scn = Scene.GetCurrent()
ob = scn.objects.active
o = ob.getData()
for v in o.verts:
v.uvco = (random.random(),random.random(),random.random())
print v.uvco
for f in o.faces:
r = (random.random(),random.random())
for i in range(0,4):
f.uv.append(r)
print f.uv
I can see the values change in Terminal, but I don't see any change when I render.
If I reselect the object, the previous face uvs are gone.
Can anyone explain how are UVs set using the Blender 2.49 Python API ?
Thanks
| [
"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 big_table:
print row.Id + row.Nmae + row.Description + row.Item1 +......
the question is - When i'm reading row, is it goes from my local memory, or it read every time from remote webservise?
I mean variable big_table contain link to all table in my memory or it take it every time from remote like iterator?
A:
So, no one know answer on this question. I figured out it by my own.
When 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.
Only way in my case is to get IDs first, than make request for every row Using iteration of IDs.
| 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.Item1 +......
the question is - When i'm reading row, is it goes from my local memory, or it read every time from remote webservise?
I mean variable big_table contain link to all table in my memory or it take it every time from remote like iterator?
| [
"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 pretty painless to apply whatever digital filter you like.
| 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 associated with my second model PostMeta. PostMeta is a simple name/value model with two fields, meta_key and meta_value.
What I'm trying to do is customize the Post model's form in the admin interface to be more intuitive. Specifically I want to abstract the creation of PostMeta associations rather than see the unintuitive select box which is redered by default for the admin. I want to instead show a text field in place of this select box where the user can enter a comma separated list of tags associated with the post. When the form is submitted I want to split the tag field's input into individual tags and save each as a PostMeta where meta_key will be set to "TAG" and meta_value will be one of the comma separated strings.
The problem I am having is I can't seem to get it to save correctly. I'm not sure if there is a problem with my syntax (I'm relativly new to python) or if there is somthing else I need to do which I may have missed. Here is a snippet of my admin.py:
class PostAdminForm(forms.ModelForm):
tags = forms.CharField(max_length=200)
class Meta:
model = Post
def save(self, commit=True):
model = super(PostAdminForm, self).save(commit=False)
if commit:
model.save()
splitTags = self.cleaned_data['tags'].split(',')
for tag in splitTags:
pm = PostMeta(meta_key="TAG", meta_value=tag)
pm.save()
model.post_meta.add(pm)
return model
class PostAdmin(admin.ModelAdmin):
model = Post
form = PostAdminForm
admin.site.register(Post, PostAdmin)
Any advice or suggestions on how to make this work would be great. Still learning :\
A:
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 in the database yet (and hence cannot be referred to in the Post to PostMeta m2m table).
See my answer to a different post, which I think is also applicable in your case, and has quite a bit of code that you may find useful.
| 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 with two fields, meta_key and meta_value.
What I'm trying to do is customize the Post model's form in the admin interface to be more intuitive. Specifically I want to abstract the creation of PostMeta associations rather than see the unintuitive select box which is redered by default for the admin. I want to instead show a text field in place of this select box where the user can enter a comma separated list of tags associated with the post. When the form is submitted I want to split the tag field's input into individual tags and save each as a PostMeta where meta_key will be set to "TAG" and meta_value will be one of the comma separated strings.
The problem I am having is I can't seem to get it to save correctly. I'm not sure if there is a problem with my syntax (I'm relativly new to python) or if there is somthing else I need to do which I may have missed. Here is a snippet of my admin.py:
class PostAdminForm(forms.ModelForm):
tags = forms.CharField(max_length=200)
class Meta:
model = Post
def save(self, commit=True):
model = super(PostAdminForm, self).save(commit=False)
if commit:
model.save()
splitTags = self.cleaned_data['tags'].split(',')
for tag in splitTags:
pm = PostMeta(meta_key="TAG", meta_value=tag)
pm.save()
model.post_meta.add(pm)
return model
class PostAdmin(admin.ModelAdmin):
model = Post
form = PostAdminForm
admin.site.register(Post, PostAdmin)
Any advice or suggestions on how to make this work would be great. Still learning :\
| [
"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 source files, and the span of their definitions in terms of line numbers.
So to illustrate my question, consider the following code in a file "helloWorld.cpp" (read this in python):
//start
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
string str = "Hello World";
cout << str << endl;
return 0;
}
//end
What i want to get is something along:
list of functions:
int main(int argc, char** argv)
start: line 7
end: line 12
Any ideas on how to achieve this (some code examples would be greatly appreciated)?
A:
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.
Parsing C++, though, is way more complicated than parsing C or Python, so you may want to explore Python and C before you start digging into C++.
A:
Pygments might be a good place to start. It is a generic code highlighter written in python with all the languages and lots more that you were trying to parse.
You can find it here:
http://dev.pocoo.org/projects/pygments/wiki
A:
It is possible to implement python bindings to Clang, or, alternatively, you could just parse and analyse XML AST dumps from Clang with Python.
A:
For C and especially C++ - if you have a real-world project, I would recommend staying as close to a canonical parser implementation as possible. C++ parsing is not for the light-hearted (and usually not done right - even by commercial compilers). I have used gcc-xml in the past just for this reason. It uses gcc to parse the code and then translates gcc's internal representation to a referential XML representation of the code that is a little easier to grok. It may not teach you about parsing, but it will give you some insight into the language grammar in a familiar XML data model.
For Python code you can make use of the parser and/or ast modules. I have never personally used them myself however.
| 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 illustrate my question, consider the following code in a file "helloWorld.cpp" (read this in python):
//start
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
string str = "Hello World";
cout << str << endl;
return 0;
}
//end
What i want to get is something along:
list of functions:
int main(int argc, char** argv)
start: line 7
end: line 12
Any ideas on how to achieve this (some code examples would be greatly appreciated)?
| [
"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 manner, that preserves order? In other words, I want to know where the "free text" of the div appears relative to the images. I would like to be able to know that "text1" appears before the first inner-div, and that text2 appears between the two inner-divs, etc.
A:
The elementtree interface, which lxml also offers, supports that -- e.g. with the built-in element tree in Python 2.7:
>>> from xml.etree import ElementTree as et
>>> x='''<div>
... text1
... <div>
... t1
... </div>
... text2
... <div>
... t2
... </div>
... text3
... </div>'''
>>> t=et.fromstring(x)
>>> for el in t.iter():
... print '%s: %r, %r' % (el.tag, el.text, el.tail)
...
div: '\ntext1\n', None
div: '\n t1\n', '\ntext2\n'
div: '\n t2\n', '\ntext3\n'
Depending on your version of lxml/elementtree, you may need to spell the iterator method .getiterator() instead of .iter().
If you need a single generator that will yields tags and texts in order, for example:
def elements_and_texts(t):
for el in t.iter():
yield 'tag', el.tag
if el.text is not None:
yield 'text', el.text
if el.tail is not None:
yield 'tail', el.tail
This basically removes the Nones and yields two-tuples with a first item of 'tag', 'text', or 'tail', to help you distinguish. I imagine this is not your ideal format, but it should not be hard to mold it into something more to your liking;-).
| 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 know where the "free text" of the div appears relative to the images. I would like to be able to know that "text1" appears before the first inner-div, and that text2 appears between the two inner-divs, etc.
| [
"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 problem: When I provide a new version of my application to customer, I have to upgrade the existing configuration.
How to make this done easy and clever?
My idea is to build a configuration object using python, and then read configuration v1 from file and save it as v2. But if later the structure is changed again, I have to build another configuration object model.
A:
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 like you're making a bigger deal out of this than it needs to be.
By the way, you'd really only need one "updater" script, because you could parametrize the XML tagging such that it go through your new config file/config layout file, and then just check the tags in the old file against that and copy the data from the ones that are present in the new file. I haven't worked with XSD files before, so I don't know the specifics of working with them, but I don't think it should be that difficult.
| 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 application to customer, I have to upgrade the existing configuration.
How to make this done easy and clever?
My idea is to build a configuration object using python, and then read configuration v1 from file and save it as v2. But if later the structure is changed again, I have to build another configuration object model.
| [
"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.formUrl, multipart=True)}
A:
I don't understand the question, but here you have full examples on how to handle file upload on pylons.
A:
uploaded_file = request.params['fieldname']
if uploaded_file:
print uploaded_file.filename
| 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 on list and run every script in different thread until they completed
Thanx Calderone, your code helped me a lot.
I have few doubts like I can resize threadpool size by this way.
from twisted.internet import reactor
reactor.suggestThreadPoolSize(30)
say all 30 available threads are busy & there is still some ids in list(dict or tuple)
1-In this situation all ids will be traversed? I mean as soon as thread is free next tool(id)
will be assigned to freed thread?
2-there is also some cases one tools must be executed before second tool & one tool output will be used by another tool,how will it be managed in twisted thread. 3
A:
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 dispatch it to a thread. You get back a Deferred from either which will tell you what the result is, when it is available.
from twisted.internet.threads import deferToThread
from twisted.internet.defer import gatherResults
from twisted.internet import reactor
def double(n):
return n * 2
data = [1, 2, 3, 4]
results = []
for datum in data:
results.append(deferToThread(double, datum))
d = gatherResults(results)
def displayResults(results):
print 'Doubled data:', results
d.addCallback(displayResults)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
You can read more about threading in Twisted in the threading howto.
| 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 in different thread until they completed
Thanx Calderone, your code helped me a lot.
I have few doubts like I can resize threadpool size by this way.
from twisted.internet import reactor
reactor.suggestThreadPoolSize(30)
say all 30 available threads are busy & there is still some ids in list(dict or tuple)
1-In this situation all ids will be traversed? I mean as soon as thread is free next tool(id)
will be assigned to freed thread?
2-there is also some cases one tools must be executed before second tool & one tool output will be used by another tool,how will it be managed in twisted thread. 3
| [
"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_length=20, db_index = True)
and my form:
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = ['name']
and in my template I got:
{% csrf_token %}
{{ category_form.as_p }}
In my view I do
cat = Category.objects.get(pk = cat_id)
data['category_form'] = CategoryForm(instance = cat)
and pass the data to my template, which renders the form ok, but the id of the object I about to update is nowhere in the html source. How can the code then now what object to update?
I feel stupid asking this since it should be pretty basic, but I've followed all the tutorials and looked thru the django docs, googled and search this site without luck.
Thanks in advance.
A:
Where is cat_id coming from in your view? I guess you receive it in url, like so:
url( r'categories/(\d+)/edit/', your_view, {} ),
in urls.py somewhere. Now in your view you can read it from appropriate view function argument:
def your_view( request, cat_id ):
Now you can obtain object with proper id, which you do here:
cat = Category.objects.get(pk = cat_id)
...and instantiate ModelForm passing it cat object if you want to edit existing object, or don't pass it, if you want an empty form for object creation.
A:
The explanation for this can be found in the django docs here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
While trying to update already saved entity you must provide an instance parameter when you recreate the form. Otherwise django will try to insert a new entity.
foo_form = FooForm(request.POST, instance=foo)
A:
The ID doesn't need to be in the HTML, because you've passed the instance into the form object when you instantiate it. Django simply updates that instance when you do form.save().
A:
The primary key is an attribute called "id" on your instance object "cat". The form itself, and in your example represented by "cat_id". The Model form should takes care to track the primary key - all you should need to do is pass the resulting "request.POST" data back into CategoryForm, valid the data with is_valid() and then save it.
i.e.
form_with_post = CategoryForm(request.POST)
if form_with_post.is_valid():
form_with_post.save()
else:
... return the form_with_post through the context to display the errors
| 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:
model = Category
fields = ['name']
and in my template I got:
{% csrf_token %}
{{ category_form.as_p }}
In my view I do
cat = Category.objects.get(pk = cat_id)
data['category_form'] = CategoryForm(instance = cat)
and pass the data to my template, which renders the form ok, but the id of the object I about to update is nowhere in the html source. How can the code then now what object to update?
I feel stupid asking this since it should be pretty basic, but I've followed all the tutorials and looked thru the django docs, googled and search this site without luck.
Thanks in advance.
| [
"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 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 stdio.
As part of an (unfinished) IRC client, I've written something like this: https://github.com/exarkun/invective/blob/master/invective/history.py
And actually, in the same project, you'll find LineInputWidget which hooks this up to stdio, and also implements things like emacs-style kill and yank, forwards- and backwards-word, etc.
stdiodemo.py can't handle things like up arrow and down arrow, though, which you'll probably want for sensible history navigation. Instead, you need to handle stdio in raw mode with some code that knows how to interpret terminal control sequences. If you've ever run "cat" and hit up arrow or any other function key, then you know there's a special sequence of bytes for each of these. Something in your program needs to interpret these sequences and turn them into something sensible. This is what twisted.conch.insults.insults.ServerProtocol does. It turns a byte transport connected to a terminal into a different, richer kind of transport: a transport that can tell you when bytes have arrived, but also when various special keys are pressed. You can see an example of running a line-based protocol with input history by running:
python -m twisted.conch.stdio
This runs a Python REPL using ServerProtocol and one of the input history classes in Twisted itself (the special thing about this REPL is that it has the reactor running simultaneously with handling your input, something that's challenge to do in the normal Python REPL).
You can find the source for this in twisted/conch/stdio.py. The important stdio hookup code is in the runWithProtocol class. See how it instantiates a ServerProtocol and connects it to stdio with StandardIO (so it's just building more on top of what stdiodemo.py does). ServerProtocol only interprets the bytes from the terminal, though. It doesn't have your application logic. So you need to give it a class that implements your application logic. And that's exactly what invective does.
| 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 XML files.
see: Extracting Nodes from multiple xml files
| 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 configuration in the best way? I can install and use both seperately but in tandem is an issue for me. Any help is appreciated.
A:
Do you mean something like this?
By the way, I think this question belongs on superuser.com (administrative questions), not stackoverflow.com (programming questions).
A:
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 install script. Both sites XAMPP on port 80 and zope/plone on 8080 are working without problems. Just to let everyone know. I don't know why I got nervous about this :)
| 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 in tandem is an issue for me. Any help is appreciated.
| [
"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_range_longs in the builtin module source
Summary: 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 just under that.
A:
The size of your lists is only limited by your memory. Note that, depending on your version of Python, range(1, 9999999999999999) needs only a few bytes of RAM since it always only creates a single element of the virtual list it returns.
If you want to instantiate the list, use list(range(1,n)) (this will copy the virtual list).
| 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:
import sys
except ImportError:
print "No sys!"
This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?
I've tried eval("import %s"%module) but that complained of a compile error.
I'm grateful for your thoughts and suggestions. Thank you.
A:
You can use the __import__() function like this::
for module in modules:
try:
__import__(module)
except ImportError:
do_something()
You can also use imp.find_module to determine whether a module can be found without importing it::
import imp
for module in modules:
try:
imp.find_module(module)
except ImportError:
do_something()
Oh, and the reason you can't use eval() is because import is a statement, not an expression. You can use exec if you really want to, though I wouldn't recommend it::
for module in modules:
try:
exec 'import ' + module
except ImportError:
do_something()
A:
What's wrong with this?
modules = set(["sys", "os", "jinja"])
for m in modules:
try:
__import__(m)
except ImportError:
# do something
The above uses the __import__ function. Also, it is strictly testing whether it exists or not - its not actually saving the import anywhere, but you could easily modify it to do that.
A:
It's worth understanding the tradeoffs between the find_module approach and the __import__ approach:
__import__('foo') will trigger any side effects of loading the module, regardless of whether you save a reference to the imported module. That might be OK, or not.
find_module('foo') won't trigger any side effects, so it should always be safe.
neither approach works well if the module is found but has other problems at load time (eg. SyntaxError, NameError, ...)
Depending on how you handle failures, simply wrapping __import__('foo') in a try/except will give you misleading results if foo is found but foo imports bar which is not found.
find_module() can't handle dotted names, so if you need to check whether 'foo.bar.bat.baz' can be imported, you have to use multiple calls to find_module and load_module as per the docs.
A:
modules = set(["sys", "os", "jinja"])
try:
for module in modules:
__import__(module)
doSomething()
except ImportError, e:
print e
| 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 bit cumbersome for what I'm doing. Is there a dynamic way to do this?
I've tried eval("import %s"%module) but that complained of a compile error.
I'm grateful for your thoughts and suggestions. Thank you.
| [
"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 can try here:
http://www.info-zip.org/UnZip.html
It's based on ZLib, a free (BSD-like) zip and unzip library.
A:
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.
A:
you can use python's zipfile module, and call extract or extractAll method with specified directory....
| 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:
check_attribute(item, arguments[item])
And then check if arguments are not "", " ". But in this case it will also try to check None values (what I don't want to do).
A:
A typical approach would be:
import sys
...
def check_attribute(name, value):
"""Gives warnings on stderr if the value is an empty or whitespace string.
All other values, including None, are OK and give no warning.
"""
if isinstance(value, basestring) and (not value or value.isspace()):
print>>sys.stderr, "Invalid value %r for argument %r" % (value, name)
or, of course, you could issue warnings, or raise exceptions if the problem is very serious according to your application's semantics.
One should probably delegate all of the checking to a single function, instead of looping in the function whose args you're checking (the latter would be sticking "checking code" smack in the middle of application logic -- better keep it out or the way...):
def check_arguments(d):
for name, value in d.iteritems():
check_attribute(name, value)
and the function would be just:
def f1 (a, b, c=None, d=None):
check_arguments(locals())
...
You could, alternatively, write a decorator in order to be able to code
@checked_arguments
def f1 (a, b, c=None, d=None):
...
(to get checking code even more "out of the way"), but this might be considered overkill unless you really have a lot of functions requiring exactly this kind of checks!
Argument-name introspection (while feasible, thanks to module inspect) is far less simple in a decorator than within the function itself, which is why my favorite design approach would be to eschew the decorator approach in this case (simplicity is seriously good;-).
Edit -- showing how to implement a decorator, since the OP explicitly asked for one (though without clarifying why).
The main problem (in Python 2.6 and earlier) is for the wrapper to construct a mapping equivalent to the locals() which Python makes for you, but needs to be done explicitly in a generic wrapper.
But -- if you use the new 2.7, inspect.getcallargs does it for you! So, the problem becomes much simpler, and the decorator perhaps worth doing in many more cases (if you're in 2.6 or earlier, I still recommend eschewing the decorator approach, which would be substantially more complicated, for such specialized uses).
So, here is all you need, in Python 2.7 (reusing the check_arguments function I defined above):
import functools
import inspect
def checked_arguments(f):
@functools.wraps(f)
def wrapper(*a, **k):
d = inspect.getcallargs(f, *a, **k)
check_arguments(d)
return f(*a, **k)
return wrapper
The difficulty in pre-2.7 versions comes entirely from the difficulty of implementing the equivalent of inspect.getcallargs -- so, I hope that, if you really need decorators of this kind, you can simply download Python 2.7 from www.python.org and install it on your box!-)
(If you do, you'll also get many more goodies besides, as well as a longer support cycle than just about any previous Python version, since 2.7 is slated to be the last release in the Python 2.* line).
A:
Why can't you refer to the values by their names?
def f1 (a, b, c=None, d=None):
if not a.strip():
print('a is not empty')
If you have many arguments it is worth changing function signature to:
def f2 (*args, c=None, d=None):
for var in args:
if not var.strip():
raise ValueError('all elements should be non-empty')
A:
for key, value in locals().items():
if value is not None:
check_attribute(key, value)
Though as others have said already, you can just check the arguments directly by name.
| 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 then check if arguments are not "", " ". But in this case it will also try to check None values (what I don't want to do).
| [
"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 example, say I had this data structure
a = [1, 2, 3, 4, 5]
I'd like the second and third element
so I thought something like this would work
a[list(1,3)]
but that gives me this error
TypeError: list indices must be
integers
This happens for most other data types as well such as numpy arrays
In matlab, you could even say a[list(2,1)] which would return this second and then the first element.
There is an alternative implementation I am considering, but I think it would be slow for large arrays. At least it would be damn slow in matlab. I'm primarily using numpy arrays.
[ a[i] for i in [1,3] ]
What's the python way oh wise ones?
Thanks!!
A:
I believe you want numpy.take:
newA = numpy.take(a, [1,3])
A:
NumPy allows you to use lists as indices:
import numpy
a = numpy.array([1, 2, 3, 4, 5])
a[[1, 3]]
Note that this makes a copy instead of a view.
| 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 the second and third element
so I thought something like this would work
a[list(1,3)]
but that gives me this error
TypeError: list indices must be
integers
This happens for most other data types as well such as numpy arrays
In matlab, you could even say a[list(2,1)] which would return this second and then the first element.
There is an alternative implementation I am considering, but I think it would be slow for large arrays. At least it would be damn slow in matlab. I'm primarily using numpy arrays.
[ a[i] for i in [1,3] ]
What's the python way oh wise ones?
Thanks!!
| [
"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 read a bunch of ways that let me add new forms using formsets, but I don't want to append a new form, I want to just add a new input3.
Is this possible?
A:
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.
If you want to allow the user to add an undefined amount of additional inputs, I would look further into formsets.
A:
for adding dynamic fields overwrite the init method.
Something like this:
class aForm(forms.Form):
input1 = forms.CharField()
input2 = forms.CharField()
def __init__(self, addfields=0, *args, **kwargs):
super(aForm, self).__init__(*args, **kwargs)
#add new fields
for i in range(3,addfields+3)
self.fields['input%d' % i] = forms.CharField()
A:
Perhaps something like this:
from django import forms
from django.utils.datastructures import SortedDict
def some_view(request):
data = {}
# Using session to remember the row count for simplicity
if not request.session.get('form_rows', None):
request.session['form_rows'] = 3
# If posted with add row button add one more row
if request.method == 'POST' and request.POST.get('rows', None):
request.session['form_rows'] += 1
data = request.POST
# Create appropriate number of form fields on the fly
fields = SortedDict()
for row in xrange(1, request.session['form_rows']):
fields['value_{0}'.format(row)] = forms.IntegerField()
# Create form class
MyForm = type('MyForm', (forms.BaseForm,), { 'base_fields': fields })
form = MyForm(initial=data)
# When submitted...
if request.method == 'POST' and not request.POST.get('rows', None):
form = MyForm(request.POST)
if form.is_valid():
# do something
return render_to_response('some_template.html', {
'form':form,
}, context_instance=RequestContext(request))
With template:
<form action="" method="post">
{{ form }}
<input type="submit" />
<input type="submit" value='Add' name='rows' />
</form>
This is over simplified but it works.
You could easily modify this example so you can make request using AJAX and just replace old form with new one.
| 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 formsets, but I don't want to append a new form, I want to just add a new input3.
Is this possible?
| [
"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, Diamond. I could represent it with an int in range 0..3, but it would allow out of range input (like 15).
A:
class Suite(object): pass
class Heart(Suite): pass
class Club(Suite): pass
etc.
A class in python is an object. So you can write
x=Heart
etc.
A:
here is very same popular question on stackoverflow
Edit:
class Suite(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
s1 = Suite(['Heart', 'Club', 'Spade', 'Diamond'])
s1.Heart
| 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 with an int in range 0..3, but it would allow out of range input (like 15).
| [
"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
LiveRouteStatus is a Model class that I query, and while the actual code is more complicated, here's a shortened version of what I'm doing...
class LiveRouteStatus(db.Model):
dateAdded = db.DateTimeProperty(autho_now_add=True)
stopID = db.StringProperty()
time = db.IntegerProperty()
q = db.GqlQuery("select * from LiveRouteStatus where stopID = :1 order by dataeAdded desc limit 24", stopID)
route_results = []
for r in routes:
if magic_test_works:
route_results.append(r)
sorted(route_results, key=itemgetter('time')
Is there some basic element of Python that I'm screwing up here? Or is this an indexing issue with the Model class?
A:
itemgetter('time') is like saying ['time'].
You want attrgetter('time'), which is like .time.
A:
You are querying LiveRouteStatus and the class you declared is called LiveVehicleStatus.
Not sure if this could be the reason tho !
| 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 the actual code is more complicated, here's a shortened version of what I'm doing...
class LiveRouteStatus(db.Model):
dateAdded = db.DateTimeProperty(autho_now_add=True)
stopID = db.StringProperty()
time = db.IntegerProperty()
q = db.GqlQuery("select * from LiveRouteStatus where stopID = :1 order by dataeAdded desc limit 24", stopID)
route_results = []
for r in routes:
if magic_test_works:
route_results.append(r)
sorted(route_results, key=itemgetter('time')
Is there some basic element of Python that I'm screwing up here? Or is this an indexing issue with the Model class?
| [
"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\
| | | __init__.py
| | | bar2.py
| | | ...
| | ...
| scripts\
| | __init__.py
| | foo.py
| | ...
How should I use sys.path.append in foo.py so that I could use bar1.py and bar2.py?
How would the import look like?
A:
Using relative paths would be much more desirable for portability reasons.
At the top of your foo.py script add the following:
import os, sys
PROJECT_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)
sys.path.append(PROJECT_ROOT)
# Now you can import from the django_project package
from django_project.django_app1.utils import bar1
from django_project.django_app2 import bar2
A:
import sys
sys.path.append('/absolute/whatever/project/django_project/django_app1')
sys.path.append('/absolute/whatever/project/django_project/django_app2')
Though you need to evaluate whether you want to have both in your path -- in case there are competing module names in both. It might make sense to only have up to django_project in your path, and call django_app1/bar1.py when you need it and import django_app2.bar2.whatever when you need it.
| 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\
| | __init__.py
| | foo.py
| | ...
How should I use sys.path.append in foo.py so that I could use bar1.py and bar2.py?
How would the import look like?
| [
"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 to know the quickest (development sense) way to display data from a database.
edit :
I'm using MySQL with web interface for data input. I would be much better if the user had some kind of GUI.
A:
Depends on the database -- with [sqlite][1], for example, ...:
$ sqlite3 databasefile 'select foo, bar from baz'
is 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), etc, etc.
So, what specific DB engine are you concerned with? Or, if more than one, which set?
A:
Some suggestions:
1) ASP.NET Gridview
---use the free Visual Studio to create an asp.net page
...can do VB, C#, etc.
---drag/drop a gridview control on your page, then connect it to your data and display fields, all via wizard (you did say quick and dirty, correct?). No coding required if you can live within the wizard's limitations (which aren't too bad actually).
The type of database (mySQL or otherwise) isn't relevant.
Other quick and dirty approach might be Access itself -- it can create 'pages', I think, that are web publishable.
If you want to put a little more work into it, ASP.NET has some other great controls / layout capability (non-wizard derived).
Also, you could look at SSRS if you have access to it. More initial setup work, but has the option to let your users create their own reports in a semi-Access-like fashion. Web accessible.
Good luck.
| 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 display data from a database.
edit :
I'm using MySQL with web interface for data input. I would be much better if the user had some kind of GUI.
| [
"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.command.easy_install.main() into ~/.app/plugins folder (which is pointed by a pth on dist-packages)
At this point, the ~/.apps/plugins/easy-install.pth is updated with the new egg path
The problem is that the pth is not reloaded until the python process is relaunched, which means the app has to be stopped and restarted (app is a long-running process, and plugin installation must not require a restart).
So the question is how to, either reload the pth programatically so that plugin entry-point discovery works for the new egg, or somehow have easy_install return the path it installed the egg into, so I can manually (with pkg_resources) load the new plugin?
I could create a function that tries to guess the easy_install'ed path or parse the pth on my own, but I prefer not to, if at all possible.
Python 2.6, setuptools 0.6c9
Thanks to Marius Gedminas, what I'm doing now basically is:
dist = pkg_resources.get_distribution(plugin_name)
entry = dist.get_entry_info(entry_point_name, plugin_name)
plugin = entry.load()
A:
After some browsing of the documentation I think what you need to do is
pkg_resources.get_distribution(name).activate()
where name is the name of the package you just installed.
| 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 pth on dist-packages)
At this point, the ~/.apps/plugins/easy-install.pth is updated with the new egg path
The problem is that the pth is not reloaded until the python process is relaunched, which means the app has to be stopped and restarted (app is a long-running process, and plugin installation must not require a restart).
So the question is how to, either reload the pth programatically so that plugin entry-point discovery works for the new egg, or somehow have easy_install return the path it installed the egg into, so I can manually (with pkg_resources) load the new plugin?
I could create a function that tries to guess the easy_install'ed path or parse the pth on my own, but I prefer not to, if at all possible.
Python 2.6, setuptools 0.6c9
Thanks to Marius Gedminas, what I'm doing now basically is:
dist = pkg_resources.get_distribution(plugin_name)
entry = dist.get_entry_info(entry_point_name, plugin_name)
plugin = entry.load()
| [
"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. However, I can't figure out how to convince repoze.who that the user is, indeed, authenticated.
I tried creating an Identifier that looks like this:
class NtlmIdentifier(object):
def identify(self, environ):
if environ['AUTH_TYPE'] == 'NTLM':
return { 'repoze.who.userid': environ['REMOTE_USER'] }
return None
def remember(self, environ, identity):
pass
def forget(self, environ, identity):
pass
And registering the middleware later on like this:
return setup_auth(app, groups, permissions, identifiers=identifiers, authenticators=[], challengers=[])
But it seems that my identifier's identify method is never called by the framework.
How do you integrate SPNEGO/SSPI with repoze.who and repoze.what?
A:
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.
As 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 anonymous; this won't be a problem in repoze.what 2 (under development).
To make everything work as you expect, you can keep the identifier you wrote and pass the remote_user_key argument to setup_auth:
return setup_auth(app, groups, permissions, remote_user_key=None, identifiers=identifiers, authenticators=[], challengers=[])
HTH.
| 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.who that the user is, indeed, authenticated.
I tried creating an Identifier that looks like this:
class NtlmIdentifier(object):
def identify(self, environ):
if environ['AUTH_TYPE'] == 'NTLM':
return { 'repoze.who.userid': environ['REMOTE_USER'] }
return None
def remember(self, environ, identity):
pass
def forget(self, environ, identity):
pass
And registering the middleware later on like this:
return setup_auth(app, groups, permissions, identifiers=identifiers, authenticators=[], challengers=[])
But it seems that my identifier's identify method is never called by the framework.
How do you integrate SPNEGO/SSPI with repoze.who and repoze.what?
| [
"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.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'root', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
Any ideas? I cannot run the syncdb command with manage.py:
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.2.1
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.admin',
'django.contrib.admindocs',
'registration',
'django_authopenid',
'djangobb_forum',
'djapian',
'messages']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.csrf.middleware.CsrfMiddleware',
'django_authopenid.middleware.OpenIDMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'djangobb_forum.middleware.LastLoginMiddleware',
'djangobb_forum.middleware.UsersOnline')
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
80. response = middleware_method(request)
File "C:\Python25\Lib\site-packages\django\middleware\locale.py" in process_request
16. language = translation.get_language_from_request(request)
File "C:\Python25\Lib\site-packages\django\utils\translation\__init__.py" in get_language_from_request
90. return real_get_language_from_request(request)
File "C:\PYTHON25\lib\site-packages\django\utils\functional.py" in _curried
55. return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
File "C:\Python25\Lib\site-packages\django\utils\translation\__init__.py" in delayed_loader
36. return getattr(trans, real_name)(*args, **kwargs)
File "C:\Python25\Lib\site-packages\django\utils\translation\trans_real.py" in get_language_from_request
339. lang_code = request.session.get('django_language', None)
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\base.py" in get
63. return self._session.get(key, default)
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session
172. self._session_cache = self.load()
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\db.py" in load
20. expire_date__gt=datetime.datetime.now()
File "C:\Python25\lib\site-packages\django\db\models\manager.py" in get
132. return self.get_query_set().get(*args, **kwargs)
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in get
336. num = len(clone)
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in __len__
81. self._result_cache = list(self.iterator())
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in iterator
269. for row in compiler.results_iter():
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in results_iter
672. for rows in self.execute_sql(MULTI):
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
717. sql, params = self.as_sql()
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in as_sql
56. out_cols = self.get_columns(with_col_aliases)
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in get_columns
185. col_aliases)
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in get_default_columns
273. r = '%s.%s' % (qn(alias), qn2(field.column))
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in quote_name_unless_alias
43. r = self.connection.ops.quote_name(name)
File "C:\Python25\lib\site-packages\django\db\backends\dummy\base.py" in complain
15. raise ImproperlyConfigured("You haven't set the database ENGINE setting yet.")
Exception Type: ImproperlyConfigured at /admin/
Exception Value: You haven't set the database ENGINE setting yet.
A:
I set mine the old way and the new way, so that it's not django-version-specific:
DATABASE_ENGINE = 'django.db.backends.sqlite3'
DATABASE_NAME = '/path/to/db/foo.sqlite3'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
DATABASES = {
'default': {
'ENGINE': DATABASE_ENGINE,
'NAME': DATABASE_NAME,
'USER': DATABASE_USER,
'PASSWORD': DATABASE_PASSWORD,
'HOST': DATABASE_HOST,
'PORT': DATABASE_PORT,
}
}
But yeah, I'd double check that your installation is the version you think.
UPDATE:
You may be trying to import something from settings in an admin module, and importing the admin module in settings. Sometimes circular-imports result in the above.
In particular, using reverse("url-name") within settings can cause this, because it ends up forcing it to look at the "site" table at some deep-dark level...
UPDATE2:
Sorry, to explain the above:
A circular import is when a module A imports from module B, and at some level, module B also needs stuff from module A. At some point during that second level of depth, it generally fails in some inscrutable way.
Reverse() is the function to turn a url's name (the name="foo" in urls.py) back into the url itself. This makes calls that are not always possible in settings or admin modules.
UPDATE3:
Looking at the ticket djangobb.org/ticket/81 you pointed to, to break some of the terms down, the csrf token is a template tag used to add Cross Site Request Forgery protection:
http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
It generally looks like this, to grep from a project of mine:
# grep -ri csrf .
./registration/login.html: <form method="post" action="{% url django.contrib.auth.views.login %}">{% csrf_token %}
The bit about the trunk of djapian, though I don't know what djapian is myself, generally means a direct install of the (typically svn) trunk -- or "most up to date, checked in version, which is newer than any release, and possibly tested, official version". Typically, this involves doing something like an svn checkout http://wherever.com/someproject/trunk/ ./someproject and then going to that directory to install.
| 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.
'PASSWORD': 'root', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
Any ideas? I cannot run the syncdb command with manage.py:
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.2.1
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.admin',
'django.contrib.admindocs',
'registration',
'django_authopenid',
'djangobb_forum',
'djapian',
'messages']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.csrf.middleware.CsrfMiddleware',
'django_authopenid.middleware.OpenIDMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'djangobb_forum.middleware.LastLoginMiddleware',
'djangobb_forum.middleware.UsersOnline')
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
80. response = middleware_method(request)
File "C:\Python25\Lib\site-packages\django\middleware\locale.py" in process_request
16. language = translation.get_language_from_request(request)
File "C:\Python25\Lib\site-packages\django\utils\translation\__init__.py" in get_language_from_request
90. return real_get_language_from_request(request)
File "C:\PYTHON25\lib\site-packages\django\utils\functional.py" in _curried
55. return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
File "C:\Python25\Lib\site-packages\django\utils\translation\__init__.py" in delayed_loader
36. return getattr(trans, real_name)(*args, **kwargs)
File "C:\Python25\Lib\site-packages\django\utils\translation\trans_real.py" in get_language_from_request
339. lang_code = request.session.get('django_language', None)
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\base.py" in get
63. return self._session.get(key, default)
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session
172. self._session_cache = self.load()
File "C:\Python25\Lib\site-packages\django\contrib\sessions\backends\db.py" in load
20. expire_date__gt=datetime.datetime.now()
File "C:\Python25\lib\site-packages\django\db\models\manager.py" in get
132. return self.get_query_set().get(*args, **kwargs)
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in get
336. num = len(clone)
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in __len__
81. self._result_cache = list(self.iterator())
File "C:\Python25\Lib\site-packages\django\db\models\query.py" in iterator
269. for row in compiler.results_iter():
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in results_iter
672. for rows in self.execute_sql(MULTI):
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
717. sql, params = self.as_sql()
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in as_sql
56. out_cols = self.get_columns(with_col_aliases)
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in get_columns
185. col_aliases)
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in get_default_columns
273. r = '%s.%s' % (qn(alias), qn2(field.column))
File "C:\Python25\Lib\site-packages\django\db\models\sql\compiler.py" in quote_name_unless_alias
43. r = self.connection.ops.quote_name(name)
File "C:\Python25\lib\site-packages\django\db\backends\dummy\base.py" in complain
15. raise ImproperlyConfigured("You haven't set the database ENGINE setting yet.")
Exception Type: ImproperlyConfigured at /admin/
Exception Value: You haven't set the database ENGINE setting yet.
| [
"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, description, picture), as well as link them with users who earn them. Also, I need to keep track of when they earned it, as well as their current progress for those who don't have one yet.
If anyone wants to give suggestions about detection or other achievement related task feel free.
EDIT:
Non-Google User Model:
class BeardUser(db.Model):
email = db.StringProperty()
username = db.StringProperty()
password = db.StringProperty()
settings = db.ReferenceProperty(UserSettings)
is_admin = db.BooleanProperty()
user_role = db.StringProperty(default="user")
datetime = db.DateTimeProperty(auto_now_add=True)
A:
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 reference the achievements in your dynamic data by name or id as specified in this list.
To indicate whether a given user has gotten an achievement, a simple way is to add a ListProperty to your player model that will hold the achievements that the player has gotten. By default this will be indexed so you can query for which players have gotten which achievements, etc.
If you also want to store what date/time the user has gotten the achievement, we're getting into an area where the built-in properties are less ideal. You could add another ListProperty with datetime properties corresponding to each achievement, but that's awkward: what we'd really like is a tuple or dict so that we can store the achievement id/name together with the time it was achieved, and make it easy to add additional properties related to each achievement in the future.
My usual approach for cases like this is to dump my ideal data structure into a BlobProperty, but that has some disadvantages and you may prefer a different approach.
Another approach is to have an achievement model separate from your user model, and a ListProperty full of referenceProperties to all the achievements that user has gotten. this has the advantage of letting you index everything very nicely but will be an additional API CPU cost at runtime especially if you have a lot of achievements to look up, and operations like deleting all a user's achievements will be very expensive compared to the above.
A:
Building on Brandon's answer here.
If you can, it would be MUCH faster to define all the achievements in the Python files, so they are in-memory and require no database fetching. This is also simpler to implement.
class StaticAchievement(object):
"""
An achievement defined in a Python file.
"""
by_name = {}
by_index = []
def __init__(self, name, description="", picture=None):
if picture is None: picture = "static/default_achievement.png"
StaticAchievement.by_name[name] = self
StaticAchievement.by_index.append(self)
self.index = len(StaticAchievement.by_index)
# This automatically adds an entry to the StaticAchievement.by_name dict.
# It also adds an entry to to the StaticAchievement.by_index list.
StaticAchievement(
name="tied your shoe",
description="You successfully tied your shoes!",
picture="static/shoes.png"
)
Then all you have to do is keep the ids for each player's achievements in a db.StringListProperty. When you have the player's object loaded, rendering the achievements requires no additional db lookups - you already have the ids, now you just have to look them up in StaticAchievement.all. This is simple to implement, and allows you to easily query which users have a given achievement, etc. Nothing else is required.
If you want additional data associated with the user's possession of an achievement (e.g. the date at which it was acquired) then you have a choice of approaches:
1: Store it in another ListProperty of the same length.
This retains the implementation simplicity and the indexability of the properties. However, this sort of solution is not to everyone's taste. If you need to make the use of this data less messy, just write a method on the player object like this:
def achievement_tuples(self):
r = []
for i in range(0, len(self.achievements)):
r.append( (self.achievements[i], self.achievement_dates[i]) )
return r
You could handle progress by maintaining a parallel ListProperty of integers, and incrementing those integers when the user makes progress.
As long as you can understand how the data is represented, you can easily hide that representation behind whatever methods you want - allowing you to have both the interface you want and the performance and indexing characteristics you want. But if you don't really need the indexing and don't like the lists, see option #2.
2: Store the additional data in a BlobProperty.
This requires you to serialize and deserialize the data, and you give up the nice querying of the listproperties, but maybe you will be happier if you hate the concept of the parallel lists. This is what people tend to do when they really want the Python way of doing things, as distinct from the App Engine way.
3: Store the additional data in the db
(e.g. a PlayersAchievement object containing both a StringProperty of the Achievement id, and a DateProperty, and a UserProperty; and on the player an achivements listproperty full of references to PlayersAchievement objects)
Since we expect players to potentially get a large number of achievements, the overhead for this will get bad fast. Getting around it will get very complex very quickly: memcache, storing intermediate data like blobs of prerendered HTML or serialized lists of tuples, setting up tasks, etc. This is also the kind of stuff you will have to do if you want the achievement definitions themselves to be modifiable/stored in the DB.
| 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. Also, I need to keep track of when they earned it, as well as their current progress for those who don't have one yet.
If anyone wants to give suggestions about detection or other achievement related task feel free.
EDIT:
Non-Google User Model:
class BeardUser(db.Model):
email = db.StringProperty()
username = db.StringProperty()
password = db.StringProperty()
settings = db.ReferenceProperty(UserSettings)
is_admin = db.BooleanProperty()
user_role = db.StringProperty(default="user")
datetime = db.DateTimeProperty(auto_now_add=True)
| [
"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(
'access_code =', 'value_to_find').fetch(1)
When doing so, I get the following error: BadValueError: Filtering on Text properties is not supported.
Even though it's a StringProperty. This never happened before and a few searches on Google didn't help at all.
Is anyone having the same issue?
A:
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 this problem to make sure that it's access_code field is definitely a StringProperty and not a TextProperty.
| "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: Filtering on Text properties is not supported.
Even though it's a StringProperty. This never happened before and a few searches on Google didn't help at all.
Is anyone having the same issue?
| [
"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
What dtype is that? I am using numpy.genfromtxt to import with a dtype = float. I know there are all sorts of dtypes you can enter, but I cannot find a comprehensive list of the options, and examples.
Thanks.
Here is an example of my input (those spaces are tabs):
Time StampT1_ModBtT2_90BendT3_InPET5_Stg2Rfrg
5:22 AM2.115800E+21.400000E+01.400000E+03.035100E+1
5:23 AM2.094300E+21.400000E+01.400000E+03.034800E+1
5:24 AM2.079300E+21.400000E+01.400000E+03.031300E+1
5:25 AM2.069500E+21.400000E+01.400000E+03.031400E+1
5:26 AM2.052600E+21.400000E+01.400000E+03.030400E+1
5:27 AM2.040700E+21.400000E+01.400000E+03.029100E+1
Update
I figured out at least part of the reason why what I am doing does not work. Still do not know how to define dtypes the way I want to.
import numpy as np
file = np.genfromtxt('myfile.txt', usecols = (0,1), dtype = (str, float), delimiter = '\t')
That returns an array of strings for each column. How do I tell it I want column 0 to be a str, and all the rest of the columns to be float?
A:
In [55]: type(1.000000E+1)
Out[55]: <type 'float'>
What 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.
A:
Numbers in the form 1.0000E+1 can be parsed by float(), so I'm not sure what the problem is:
>>> float('1.000E+1')
10.0
A:
I think you'll want to get a text parser to parse the format into a native python data type.
like 1.00000E+1 turns into 1.0^1, which could be expressed as a float.
| 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 am using numpy.genfromtxt to import with a dtype = float. I know there are all sorts of dtypes you can enter, but I cannot find a comprehensive list of the options, and examples.
Thanks.
Here is an example of my input (those spaces are tabs):
Time StampT1_ModBtT2_90BendT3_InPET5_Stg2Rfrg
5:22 AM2.115800E+21.400000E+01.400000E+03.035100E+1
5:23 AM2.094300E+21.400000E+01.400000E+03.034800E+1
5:24 AM2.079300E+21.400000E+01.400000E+03.031300E+1
5:25 AM2.069500E+21.400000E+01.400000E+03.031400E+1
5:26 AM2.052600E+21.400000E+01.400000E+03.030400E+1
5:27 AM2.040700E+21.400000E+01.400000E+03.029100E+1
Update
I figured out at least part of the reason why what I am doing does not work. Still do not know how to define dtypes the way I want to.
import numpy as np
file = np.genfromtxt('myfile.txt', usecols = (0,1), dtype = (str, float), delimiter = '\t')
That returns an array of strings for each column. How do I tell it I want column 0 to be a str, and all the rest of the columns to be float?
| [
"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.getSuccessors(node)
if not child == 0:
stack.append(child)
closed.apped(node)
return None
code of successor is:
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
As noted in search.py:
For a given state, this should return a list of triples,
(successor, action, stepCost), where 'successor' is a
successor to the current state, 'action' is the action
required to get there, and 'stepCost' is the incremental
cost of expanding to that successor
"""
successors = []
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextState = (nextx, nexty)
cost = self.costFn(nextState)
successors.append( ( nextState, action, cost) )
# Bookkeeping for display purposes
self._expanded += 1
if state not in self._visited:
self._visited[state] = True
self._visitedlist.append(state)
return successors
The error is:
File line 87, in depthFirstSearch
child = problem.getSuccessors(node)
File line 181, in getSuccessors
nextx, nexty = int(x + dx), int(y + dy)
TypeError: can only concatenate tuple (not "float") to tuple
When we run the following commands:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
we get:
Start: (5, 5)
Is the start a goal? False
Start's successors: [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
A:
Change this:
nextx, nexty = int(x + dx), int(y + dy)
to this:
print x, y, dx, dy, state
nextx, nexty = int(x + dx), int(y + dy)
I guarantee you will see () around something besides state. That means your value is a tuple:
int(x + dx), int(y + dy)
You cannot concatenate a float and a tuple and convert the result to integer, it just won't work:
In [57]: (5, 5) + 3.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
c:\<ipython console> in <module>()
TypeError: can only concatenate tuple (not "float") to tuple
A:
Looks like x or y (or both) is a tuple when it should be a float/int. I'd make sure that state and node are what you expect them to be. That's all I can say without knowing more about what problem.getStartState() is supposed to be doing.
A:
What this error probably means is that you are trying to concatenate (with +) is a mixture of a float and a tuple, and that isn't defined. Check to see what type of thing state, x, y, dx, and dy are.
| 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:
stack.append(child)
closed.apped(node)
return None
code of successor is:
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
As noted in search.py:
For a given state, this should return a list of triples,
(successor, action, stepCost), where 'successor' is a
successor to the current state, 'action' is the action
required to get there, and 'stepCost' is the incremental
cost of expanding to that successor
"""
successors = []
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextState = (nextx, nexty)
cost = self.costFn(nextState)
successors.append( ( nextState, action, cost) )
# Bookkeeping for display purposes
self._expanded += 1
if state not in self._visited:
self._visited[state] = True
self._visitedlist.append(state)
return successors
The error is:
File line 87, in depthFirstSearch
child = problem.getSuccessors(node)
File line 181, in getSuccessors
nextx, nexty = int(x + dx), int(y + dy)
TypeError: can only concatenate tuple (not "float") to tuple
When we run the following commands:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
we get:
Start: (5, 5)
Is the start a goal? False
Start's successors: [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
| [
"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,
b2 : z1,
dep : {
cset : x2,
b1 : y2,
b2 : z2,
dep : <same as above.it recurses few more levels>
...
}
}
}
I want to convert this whole string object into dictionary.
I read on one of the articles to use pickle module, but I don't want to serialize it into some file and use it.
Ref : http://bytes.com/topic/python/answers/36059-convert-dictionary-string-vice-versa
I am looking for some other neater ways of doing it, if possible.
Would be great to know any such ways.
A:
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 contain arbitrary code at runtime.
From the docs:
Safely evaluate an expression node or
a string containing a Python
expression. The string or node
provided may only consist of the
following Python literal structures:
strings, numbers, tuples, lists,
dicts, booleans, and None.
This can be used for safely evaluating
strings containing Python expressions
from untrusted sources without the
need to parse the values oneself.
Code Example:
>>> import ast
>>> ast.literal_eval("1+1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("\"1+1\"")
'1+1'
>>> ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}")
{'a': 2, 3: 'xyz', 'b': 3}
A:
If you are careful enough to keep the code valid python, you could use eval:
eval(yourlongstring)
A:
Is that the actual data format? Do you have any flexibility?
It's very nearly JSON, which is a standard data format for which Python has native libraries for reading and writing (serialising and deserialising). However, to make it valid JSON both the keys and values would need to be surrounded by quotes:
"cset" : "x",
"b1" : "y"
and so on.
| 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 : {
cset : x2,
b1 : y2,
b2 : z2,
dep : <same as above.it recurses few more levels>
...
}
}
}
I want to convert this whole string object into dictionary.
I read on one of the articles to use pickle module, but I don't want to serialize it into some file and use it.
Ref : http://bytes.com/topic/python/answers/36059-convert-dictionary-string-vice-versa
I am looking for some other neater ways of doing it, if possible.
Would be great to know any such ways.
| [
"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: myRun() takes no arguments (1 given)
Did something change in QT? How can I make this work on both machines?
Thanks!
Nathan
A:
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:
def myThread(QtCore.QThread):
def run(self):
pass
thread = myThread()
thread.start()
UPDATED: Matching the original a bit more.
def myRun():
doStuff
thread = QtCore.QThread()
thread.run = lambda self: myRun()
thread.start()
| 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 QT? How can I make this work on both machines?
Thanks!
Nathan
| [
"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 please let me know
Thanks!
For more information: I want to use the sort option to apply the filter so that when the excel document I create is opened the user does not have to highlight everything, then click Data tab and select filter. The source data doesnt make a difference.
A:
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.
You can filter out items from a list based on if they satisfy a certain criteria. For example:
def want(s):
return s in ('dog', 'cat', 'fish') # return true if the string is dog, cat or fish
filter(want, ['dog', 'dog', 'zebra', 'zebrafish', 'fish', 'foo'])
# Returns: ['dog', 'dog', 'fish']
filter takes in a function that returns True or False as the first parameter. Then, it passes in each element in the list for the second parameter. If want('dog') returns True, it will return it in the resulting set. If it is False, it will not.
A:
List comprehension (or generator expression).
data = ['dog', 'god', 'zebra', 'zebrafish', 'fish', 'foo']
result = [w for w in data if w.startswith('z')]
| 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 sort option to apply the filter so that when the excel document I create is opened the user does not have to highlight everything, then click Data tab and select filter. The source data doesnt make a difference.
| [
"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 or should I just make a write close open module? It may be relevant that the logfile did not exist/is empty on the first open.
>>> the_page = 'some large site opened through urllib'
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> logfile.write(the_page)
>>> print logfile.read()
Nothing appears.
>>> 'Some regular expressions search'
Searches against last 100 lines written.
>>> logfile.close()
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> print logfile.read()
Everything appears.
>>> 'Some regular expressions search'
Performs as expected.
A:
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:
However, using seek() to reposition the file to
an absolute position will flush the read-ahead buffer.
A:
logfile.flush()
This should do the same thing as opening then closing the file.
| 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 open module? It may be relevant that the logfile did not exist/is empty on the first open.
>>> the_page = 'some large site opened through urllib'
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> logfile.write(the_page)
>>> print logfile.read()
Nothing appears.
>>> 'Some regular expressions search'
Searches against last 100 lines written.
>>> logfile.close()
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> print logfile.read()
Everything appears.
>>> 'Some regular expressions search'
Performs as expected.
| [
"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')
for line in big_file:
if 'S0414' in line:
small_file3.write(line)
gbigfile.close()
small_file3.close()
How can I speed this up for 30,000 lines that I need to look up>?
A:
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:
import re
keywords = ['S0414', 'GT213', 'AT3423', 'PR342'] # etc - you probably get those from some source
pattern = re.compile('|'.join(keywords))
for line in inf:
if pattern.search(ln):
outf.write(line)
A:
Testing many conditions per line is generally slow when using a naive algorithm. There are various superior algorithms (e.g. using Tries) which can do much better. I suggest you give the Aho–Corasick string matching algorithm a shot. See here for a python implementation. It should be considerably faster than the naive approach of using a nested loop and testing every string individually.
A:
According to Python's documentation of file objects, iteration you're doing should not be especially slow, and search for substrings should also be fine speed-wise.
I don't see any reason why your code should be slow, so if you need it to go faster you might have to rewrite it in C and use mmap() for fast access to the source file.
A:
1. Try to read whole file
One speed up you can do is read whole file in memory if that is possible, else read in chunks. You said 'several hudred thousand lines' lets say 1 million lines with each line 100 char i.e. around 100 MB, if you have that much free memory (I assume you have) just do this
big_file = open('C:\\gbigfile.txt', 'r')
big_file_lines = big_file.read_lines()
big_file.close()
small_file3 = open('C:\\small_file3.txt', 'w')
for line in big_file_lines:
if 'S0414' in line:
small_file3.write(line)
small_file3.close()
Time this with orginal version and see if it makes difference, I think it will.
But if your file is really big in GBs, then you can read it in chunks e.g. 100 MB chunks, split it into lines and search but don't forget to join lines at each 100MB interval (I can elaborate more if this is the case)
file.readlines returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will be returned.
Also see following link for speed difference between line by line vs entire file reading.
http://handyfloss.wordpress.com/2008/02/15/python-speed-vs-memory-tradeoff-reading-files/
2. Try to write whole file
You can also store line and write them at once at end, though I am not sure if it will help much
big_file = open('C:\\gbigfile.txt', 'r')
big_file_lines = big_file.read_lines()
small_file_lines = []
for line in big_file_lines:
if 'S0414' in line:
small_file_lines.append(line)
small_file3 = open('C:\\small_file3.txt', 'w')
small_file3.write("".join(small_file_lines))
small_file3.close()
3. Try filter
You can also try to use filter, instead of loop see if it makes difference
small_file_lines= filter(lambda line:line.find('S0414') >= 0, big_file_lines)
A:
You could try reading in big blocks, and avoiding the overhead of line-splitting except for the specific lines of interest. E.g., assuming none of your lines is longer than a megabyte:
BLOCKSIZE = 1024 * 1024
def byblock_fullines(f):
tail = ''
while True:
block = f.read(BLOCKSIZE)
if not block: break
linend = block.rindex('\n')
newtail = block[linend + 1:]
block = tail + block[:linend + 1]
tail = newtail
yield block
if tail: yield tail + '\n'
this takes an open file argument and yields blocks of about 1MB guaranteed to end with a newline. To identify (iterator-wise) all occurrences of a needle string within a haystack string:
def haystack_in_needle(haystack, needle):
start = 0
while True:
where = haystack.find(needle, start)
if where == -1: return
yield where
start = where + 1
To identify all relevant lines from within such a block:
def wantlines_inblock(s, block):
last_yielded = None
for where in haystack_in_needle(block, s):
prevend = block.rfind('\n', where) # could be -1, that's OK
if prevend == last_yielded: continue # no double-yields
linend = block.find('\n', where)
if linend == -1: linend = len(block)
yield block[prevend + 1: linend]
last_yielded = prevend
How this all fits together:
def main():
with open('bigfile.txt') as f:
with open('smallfile.txt', 'w') as g:
for block in byblock_fulllines(f):
for line in wantlines_inblock('S0414', block)
f.write(line)
In 2.7 you could fold both with statements into one, just to reduce nesting a bit.
Note: this code is untested so there might be (hopefully small;-) errors such as off-by-one's. Performance needs tuning of the block size and must be calibrated by measurement on your specific machine and data. Your mileage may vary. Void where prohibited by law.
A:
If the line begins with S0414, then you could use the .startswith method:
if line.startswith('S0414'): small_file3.write(line)
You could also strip left whitespace, if there is any:
line.lstrip().startswith('S0414')
If 'S0414' always appears after a certain point, for example, it is always at least 10 characters in and never in the last 5 characters, you could do:
'S0414' in line[10:-5]
Otherwise, you will have to search through each line, like you are.
A:
What are the criteria that define the 30000 lines you want to extract? The more information you give, the more likely you are to get a useful answer.
If you want all the lines containing a certain string, or more generally containing any of a given set of strings, or an occurrence of a regular expression, use grep. It's likely to be significantly faster for large data sets.
A:
This reminds me of a problem described by Tim Bray, who attempted to extract data from web server log files using multi-core machines. The results are described in The Wide Finder Project and Wide Finder 2. So, if serial optimizations don't go fast enough for you, this may be a place to start. There are examples of this sort of problem contributed in many languages, including python. Key quote from that last link:
Summary
In this article, we took a relatively fast Python implementation and optimized it, using a
number of tricks:
Pre-compiled RE patterns
Fast filtering of candidate lines
Chunked reading
Multiple processes
Memory mapping, combined with support for RE operations on mapped buffers
This reduced the time needed to parse 200 megabytes of log data from 6.7 seconds to 0.8
seconds on the test machine. Or in other words, the final version is over 8 times faster
than the original Python version, and (potentially) 600 times faster than Tim’s original
Erlang version.
Having said this, 30,000 lines isn't that many so you may want to at least start by investigating your disk read/write performance. Does it help if you write the output to something other than the disk that you are reading the input from or read the whole file in one go before processing?
A:
The best bet to speed it up would be if the specific string S0414 always appears at the same character position, so instead of having to make several failed comparisons per line (you said they start with different names) it could just do one and done.
e.g. if you're file has lines like
GLY S0414 GCT
ASP S0435 AGG
LEU S0432 CCT
do an if line[4:9] == 'S0414': small.write(line).
A:
This method assumes the special values appear in the same position on the line in gbigfile
def mydict(iterable):
d = {}
for k, v in iterable:
if k in d:
d[k].append(v)
else:
d[k] = [v]
return d
with open("C:\\to_find.txt", "r") as t:
tofind = mydict([(x[0], x) for x in t.readlines()])
with open("C:\\gbigfile.txt", "r") as bigfile:
with open("C:\\outfile.txt", "w") as outfile:
for line in bigfile:
seq = line[4:9]
if seq in tofind[seq[0]]:
outfile.write(line)
Depending on what the distribution of the starting letter in those targets you can cut your comparisons down by a significant amount. If you don't know where the values will appear you're talking about a LONG operation because you'll have to compare hundreds of thousands - let's say 300,000 -- 30,000 times. That's 9 million comparisons which is going to take a long time.
| 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 'S0414' in line:
small_file3.write(line)
gbigfile.close()
small_file3.close()
How can I speed this up for 30,000 lines that I need to look up>?
| [
"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 have to print and I hate use sys.stdout.write(var) for each one of them. Thanks Pythonistas!
A:
For a variable number of values:
print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
A:
Try using join:
print "\n"+'|'.join([id,var1,var2,var3,var4])
or if the variables aren't already strings:
print "\n"+'|'.join(map(str,[id,var1,var2,var3,var4]))
The benefit of this approach is that you don't have to build a long format string and it basically works unchanged for an arbitrary number of variables.
A:
print "\n|%s|%s|%s|%s" % (id,var1,var2,var3,var4)
Take a look at String Formatting.
Edit: The other answers with join are better. Join expects strings.
A:
If you are using Python 2.6 or newer, use the new standard for formating string, the str.format method:
print "\n{0}|{1}|{2}|".format(id,var1,var2)
link text
| 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 Pythonistas!
| [
"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 function included in the standard library to do this.
| 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). When parsed, namespaced elements are available without the prefix:
>>> feed = feedparser.parse("without_atom_tags.xml")
>>> print feed.entries[0].comment_status
u'open'
The XML from WordPress 3.x does contain atom:link tags (with_atom_tags.xml), and you must prefix namespace elements:
>>> feed = feedparser.parse("with_atom_tags.xml")
>>> feed.entries[0].wp_comment_status # <-- Note wp_ prefix
u'open'
>>> feed.entries[0].comment_status
AttributeError: object has no attribute 'comment_status'
Interestingly, the prefixes aren't needed if I add xmlns:atom="http://www.w3.org/2005/Atom" to the root RSS element (with_atom_tags_and_namespace.xml).
I need to parse all these different formats without modifying the XML. Is feedparser broken, or am I doing it wrong? Can I do this without a bunch of nasty conditional code?
A:
Could you add the missing namespaces (atom/wp) to the global list of supported namespaces in feedparser.py directly?
| 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 prefix:
>>> feed = feedparser.parse("without_atom_tags.xml")
>>> print feed.entries[0].comment_status
u'open'
The XML from WordPress 3.x does contain atom:link tags (with_atom_tags.xml), and you must prefix namespace elements:
>>> feed = feedparser.parse("with_atom_tags.xml")
>>> feed.entries[0].wp_comment_status # <-- Note wp_ prefix
u'open'
>>> feed.entries[0].comment_status
AttributeError: object has no attribute 'comment_status'
Interestingly, the prefixes aren't needed if I add xmlns:atom="http://www.w3.org/2005/Atom" to the root RSS element (with_atom_tags_and_namespace.xml).
I need to parse all these different formats without modifying the XML. Is feedparser broken, or am I doing it wrong? Can I do this without a bunch of nasty conditional code?
| [
"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):
What I would like to do is, rather than calling this function like so:
send_command("A234", 5, True)
... or...
send_command("B4242")
I'd like to be able to store up commands inside a deque list and use the popleft function to then call my function. This would allow me to do things such as:
CommandList = deque((['A234', 5, True], ['B4242']))
...and use the deque.append() as a way to keep adding things to the list, which would then in turn be sent to my send_command function. I could then drop in and out of the list new commands when they are needed (or as quickly as the serial part of my code can do).
The part I'm struggling with is actually using the CommandList.popleft, or any part of the deque list as the args for my send_command function. It doesn't seem as straight forward as:
send_command(CommandList.popleft)
I'm sure it's something simple, but I cannot figure it out.
Can anyone help?
Thank-you kindly.
Andy
A:
probably you need something like:
obj.send_command(*CommandList.popleft())
That 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
Another way, as I wrote in the comment, is to store prepared functions with something like this:
def make_command(obj, *args, **kwargs):
def f():
obj.send_command(*args, **kwargs)
return f
Then you can do
queue.append(make_command(obj, 'ABC', whatever='else'))
and then execute:
command = queue.popleft()
command()
A:
unbeli is right - you need the () to call the function, and you need * to unpack the arguments. However, there's no need for using deque when you can just do this:
commandlist = [['A234', 5, True], ['B4242'], ['A234', 0]]
for command in commandlist:
send_command(*command)
and that will work perfectly fine. For more info, see unpacking argument lists.
Queues are really only necessary if you're doing something in which you want to consume the values - say you want your commandlist to be empty when you're done. Of course you could also do the same thing with a list:
q = [1,2,3,4]
while q:
print q.pop(0)
print q
HTH
A:
Have you tried:
send_command(CommandList.popleft()) # note the ()
| 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 this function like so:
send_command("A234", 5, True)
... or...
send_command("B4242")
I'd like to be able to store up commands inside a deque list and use the popleft function to then call my function. This would allow me to do things such as:
CommandList = deque((['A234', 5, True], ['B4242']))
...and use the deque.append() as a way to keep adding things to the list, which would then in turn be sent to my send_command function. I could then drop in and out of the list new commands when they are needed (or as quickly as the serial part of my code can do).
The part I'm struggling with is actually using the CommandList.popleft, or any part of the deque list as the args for my send_command function. It doesn't seem as straight forward as:
send_command(CommandList.popleft)
I'm sure it's something simple, but I cannot figure it out.
Can anyone help?
Thank-you kindly.
Andy
| [
"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 Lennon parameter and birthday will just insert? Can I use something else instead of defaults?
And what method should I use to clean all fields in table (models)?
It give me FileField error can not resolve keyword default in field
So I need look for fiels, if i found it - update datas. If i didn't find it I have to crate new field... But, as I understud, It won't update me default fields when finde present fields.
A:
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 querying.
To clean the whole table, you should use something like:
Model.objects.all().delete()
which is equivalent of:
DELETE FROM app_model WHERE True;
To set some field in every object ( some column in every row ), there is update() method:
Model.objects.all().update( some_field = "" )
which translates to:
UPDATE app_model SET `some_field` = '' WHERE True;
My sql is a bit rusty, but I believe it goes like that, more or less.
A:
You can refer to this django documentation for a more detailed explanation on get_or_create method. In short, it first tries to get with the first_name and last_name provided, if not it instantiates and saves a new object in which case the default dictionary is used. And the return value is the corresponding object and True/False whether a new object was created or not.
A:
You can use anything. default if you not set anything.
| 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 will just insert? Can I use something else instead of defaults?
And what method should I use to clean all fields in table (models)?
It give me FileField error can not resolve keyword default in field
So I need look for fiels, if i found it - update datas. If i didn't find it I have to crate new field... But, as I understud, It won't update me default fields when finde present fields.
| [
"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.
Checking if your target program is maximized/fullscreen could likely be accomplished by win32gui.GetForegroundWindow() and checking that handle.
| 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)? 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.
If you're doing anything very long, the best bet is to write your program into your text editor of choice, save that file, then launch it.
Adding a comma to the start of every line with Python:
import sys
src = open(sys.argv[1])
dest = open('withcommas-' + sys.argv[1],'w')
for line in src:
dest.write(',' + line)
src.close()
dest.close()
Call like so: C:\Scripts>python commaz.py cc.py. This is a bizzare thing to do, but who am I to argue.
A:
If you are in UNIX environment, open up a terminal, cd to the directory your file is in and use the sed command. I think this may work:
sed "s/\n/\n,/" your_filename.py > new_filename.py
What this says is to replace all \n (newline character) to \n, (newline character + comma character) in your_filename.py and to output the result into new_filename.py.
UPDATE: This is much better:
sed "s/^/,/" your_filename.py > new_filename.py
This is very similar to the previous example, however we use the regular expression token ^ which matches the beginning of each line (and $ is the symbol for end).
There are chances this doesn't work or that it doesn't even apply to you because you didn't really provide that much information in your question (and I would have just commented on it, but I can't because I don't have enough reputation or something). Good luck.
A:
You need a file editor, not python.
Install the appropriate VIM variant for your operating system
Open the file you want to modify using VIM
Type: :%s/^/,/
Type: :wq
A:
Code is data. You could do this like you would with any other text file. Open the file, read the line, stick a comma on the front of it, then write it back to file.
Also, most modern IDEs/text editors have the ability to define macros. You could post a question asking for specific help for your editor. For example, in Emacs I would use C-x ( to start defining a macro, then ',' to write a comma, then C-b C-n to go back a character and down a line, then C-x ) to end my macro. I could then run this macro with C-x e, pressing e to execute it an additional time.
| 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 out. I will definitely do it from now on.
Okay. Back to the question. Previously i have written a python script to calculate the similarity between document. Now i have all the data write to notepad and it looks like this:
(1, 6821): inf
(1, 8): 3.458911570
(1, 9): 7.448105193
(1, 10): inf
(1, 11): inf
(6821, 8): inf
(6821, 9): inf
(6821, 10): inf
(6821, 11): inf
(8, 9): 2.153308936
(8, 10): inf
(8, 11): 16.227647992
(9, 10): inf
(9, 11): 34.943139430
(10, 11): inf
The number in the parenthesis represents document numbers. And the value after it, is the distance between the two documents. What i want is actually visualization tools or method which i can create nodes that represent each documents number. For example here, i have 6 different documents. So i wish to create 6 different nodes that represent my document numbers. Then, i want to have edges that connect these nodes together based on their distances. For example the distance between document 1 and 8 is 3.46 while the distance between document 1 and 9 is 7.45. So, 1 & 8 need to cluster closer than 1 & 9. While the document pairs with 'inf' distance shouldn't have any connection or edge connecting them together.
This sounds easy but i have really hard time finding an open source visualization tool that can effective help me to perform this. I appreciate any suggestion recommendation.
A:
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.
A:
http://www.graphviz.org/
In particular, the neato package:
$ cat similar.dot
graph g {
n1 -- n8 [ weight = 3.458911570 ];
n1 -- n9 [ weight = 7.448105193 ];
n8 -- n9 [ weight = 2.153308936 ];
n8 -- n11 [ weight = 16.227647992 ];
n9 -- n11 [ weight = 34.943139430 ];
n10;
n6821;
}
$ neato -Tpng similar.dot -o similar.png
A:
Processing is a really lovely tool for data visualization (and also language, based on Java). Think of it as writing simplified OpenGL (you can even use OpenGL with it if you want it) in Java plus the freedom to use all the Java libraries. You can even embed your Processing app inside another Swing or AWT application.
Here's the main page, and the brand new wiki.
You said you used Pyton. There's a hack so you can use Jython instead of Java in this blog post. I haven't tried it but maybe it works fine. The only lack in using another languageh (there's also a JavaScript 'port', Processing.js) is that all the examples are for the Processing language (based on Java).
| 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 from now on.
Okay. Back to the question. Previously i have written a python script to calculate the similarity between document. Now i have all the data write to notepad and it looks like this:
(1, 6821): inf
(1, 8): 3.458911570
(1, 9): 7.448105193
(1, 10): inf
(1, 11): inf
(6821, 8): inf
(6821, 9): inf
(6821, 10): inf
(6821, 11): inf
(8, 9): 2.153308936
(8, 10): inf
(8, 11): 16.227647992
(9, 10): inf
(9, 11): 34.943139430
(10, 11): inf
The number in the parenthesis represents document numbers. And the value after it, is the distance between the two documents. What i want is actually visualization tools or method which i can create nodes that represent each documents number. For example here, i have 6 different documents. So i wish to create 6 different nodes that represent my document numbers. Then, i want to have edges that connect these nodes together based on their distances. For example the distance between document 1 and 8 is 3.46 while the distance between document 1 and 9 is 7.45. So, 1 & 8 need to cluster closer than 1 & 9. While the document pairs with 'inf' distance shouldn't have any connection or edge connecting them together.
This sounds easy but i have really hard time finding an open source visualization tool that can effective help me to perform this. I appreciate any suggestion recommendation.
| [
"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 -> split them with \s\n\t(space,newline,tab) -> Keyword list
But this does not work great.
Is there a better way?
A:
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.
You can refine this rough search pattern by specifying certain words that can be contained as part of a phrase (pronouns ect).
| 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 list
But this does not work great.
Is there a better way?
| [
"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.CharField(max_length=20)
def __unicode__(self):
return self.name
-forms.py
class MenuCategoryForm(ModelForm):
class Meta:
model = Menu_Category
fields = ('name')
The problem i'm experiencing is that when I only select one field from the form to display (fields = ('name')) the form does not display anything nor do i get any errors. It is completely blank. However, when I add a second field fields = ('name','test_field') the form displays both fields just fine. Is there a minimum number of fields a form can display?
Thanks in advance.
A:
You have been bitten by a common Python gotcha.
In this line:
fields = ('name')
the 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 will think you have set 'n','a','m','e'.
To make a single-element tuple, you always need a trailing comma.
fields = ('name',)
(In fact, as the Python docs show, it is not the parentheses that make the tuple at all, but the comma.)
| 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
-forms.py
class MenuCategoryForm(ModelForm):
class Meta:
model = Menu_Category
fields = ('name')
The problem i'm experiencing is that when I only select one field from the form to display (fields = ('name')) the form does not display anything nor do i get any errors. It is completely blank. However, when I add a second field fields = ('name','test_field') the form displays both fields just fine. Is there a minimum number of fields a form can display?
Thanks in advance.
| [
"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 "dictlist2file" simply calls DictWriter to serialize this, but I am getting out of memory errors.
My function is:
def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
lineterminator='\n', extrasaction='ignore'):
out_f = open(filename, 'w')
# Write out header
if fieldnames != None:
header = delimiter.join(fieldnames) + lineterminator
else:
header = dictrows[0].keys()
header.sort()
out_f.write(header)
print "dictlist2file: serializing %d entries to %s" \
%(len(dictrows), filename)
t1 = time.time()
# Write out dictionary
data = csv.DictWriter(out_f, fieldnames,
delimiter=delimiter,
lineterminator=lineterminator,
extrasaction=extrasaction)
data.writerows(dictrows)
out_f.close()
t2 = time.time()
print "dictlist2file: took %.2f seconds" %(t2 - t1)
When I try this on my dictionary, I get the following output:
dictlist2file: serializing 13537 entries to myoutput_file.txt
Python(6310) malloc: *** mmap(size=45862912) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
...
File "/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/csv.py", line 149, in writerows
rows.append(self._dict_to_list(rowdict))
File "/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
MemoryError
Any idea what could be causing this? The list has only 13,000 elements and the dictionaries themselves are very simple and small (100 keys) so I don't see why this would lead to memory errors or be so inefficient. It takes minutes for it to get to the memory error.
thanks for your help.
A:
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:
Iterate over the list yourself and call DictWriter.writerow once for each one. Although this will mean a lot of writes.
Batch up rows in to smaller lists and call DictWriter.writerows for them. Less IO, but you avoid the huge chunk of memory getting allocated.
A:
You could be tripping over an internal Python issue. I'd report it at bugs.python.org.
A:
I don't have an answer to what is happening with csv, but I found that the following substitute serializes the dictionary to a file in less than a few seconds:
for row in dictrows:
out_f.write("%s%s" %(delimiter.join([row[name] for name in fieldnames]),
lineterminator))
where dictrows is a generator of dictionaries produced by DictReader from csv, fieldnames is a list of fields.
Any idea on why csv doesn't perform similarly would be greatly appreciated. thanks.
A:
You say that if you loop over data.writerow(single_dict) that it still gets the problem. Put in code to show the row count every 100 rows. How many dicts has it processed before it gets the Memory error? Run more or fewer processes to soak up more or less memory ... does the place where it fails vary?
What is max(len(d) for d in dictrows) ? How long are the strings in the dicts?
How much free memory do you have anyway?
Update: See if Dictwriter is the problem; eliminate it and use basic csv functionality:
writer = csv.writer(.....)
for d in dictrows:
row = [d[fieldname] for fieldname in fieldnames]
writer.writerow(row)
| 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 function is:
def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
lineterminator='\n', extrasaction='ignore'):
out_f = open(filename, 'w')
# Write out header
if fieldnames != None:
header = delimiter.join(fieldnames) + lineterminator
else:
header = dictrows[0].keys()
header.sort()
out_f.write(header)
print "dictlist2file: serializing %d entries to %s" \
%(len(dictrows), filename)
t1 = time.time()
# Write out dictionary
data = csv.DictWriter(out_f, fieldnames,
delimiter=delimiter,
lineterminator=lineterminator,
extrasaction=extrasaction)
data.writerows(dictrows)
out_f.close()
t2 = time.time()
print "dictlist2file: took %.2f seconds" %(t2 - t1)
When I try this on my dictionary, I get the following output:
dictlist2file: serializing 13537 entries to myoutput_file.txt
Python(6310) malloc: *** mmap(size=45862912) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
...
File "/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/csv.py", line 149, in writerows
rows.append(self._dict_to_list(rowdict))
File "/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
MemoryError
Any idea what could be causing this? The list has only 13,000 elements and the dictionaries themselves are very simple and small (100 keys) so I don't see why this would lead to memory errors or be so inefficient. It takes minutes for it to get to the memory error.
thanks for your help.
| [
"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 doesn't work.
for i in xrange(len(all_lists)):
newlist=[]
for l in all_lists[i]:
mylist = l.split()
score1 = float(mylist[2])
score2 = mylist[3]
temp_list = (score1, score2)
newlist.append(temp_list)
list_of_lists.append(newlist)
Please help. Many thanks in advance.
A:
You could use a nested list comprehension. (This assumes you want the last two "scores" out of each string):
[[tuple(l.split()[-2:]) for l in list] for list in all_list]
A:
It could work almost as-is if you filled in the value for mylist -- right now its undefined.
Hint: use the split function on the strings to break them up into their components, and you can fill mylist with the result.
Hint 2: Make sure that newlist is set back to an empty list at some point.
A:
Adding to eruciforms answer.
First remark, you don't need to generate the indices for the all_list list. You can just iterate over it directly:
for list in all_lists:
for item in list:
# magic stuff
Second remark, you can make your string splitting much more succinct by splicing the list:
values = item.split()[-2:] # select last two numbers.
Reducing it further using map or a list comprehension; you can make all the items a float on the fly:
# make a list from the two end elements of the splitted list.
values = [float(n) for n in item.split()[-2:]]
And tuplify the resulting list with the tuple built-in:
values = tuple([float(n) for n in item.split()[-2:]])
In the end you can collapse it all to one big list comprehension as sdolan shows.
Of course you can manually index into the results as well and create a tuple, but usually it's more verbose, and harder to change.
Took some liberties with your variable names, values would tmp_list in your example.
| 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(all_lists)):
newlist=[]
for l in all_lists[i]:
mylist = l.split()
score1 = float(mylist[2])
score2 = mylist[3]
temp_list = (score1, score2)
newlist.append(temp_list)
list_of_lists.append(newlist)
Please help. Many thanks in advance.
| [
"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 Image, ImageDraw
img = Image.new("RGB", (100,150),(255,255,255))
I get the following error:
ImportError: The _imaging C module is not installed
The _imaging.pyd file exists and is in the right directory. Furthermore, Python (from the command line) can load PIL and Image and execute the code that I posted above successfully. Can anyone enlighten me as to what I am doing wrong? Thank you!
A:
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.
| 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))
I get the following error:
ImportError: The _imaging C module is not installed
The _imaging.pyd file exists and is in the right directory. Furthermore, Python (from the command line) can load PIL and Image and execute the code that I posted above successfully. Can anyone enlighten me as to what I am doing wrong? Thank you!
| [
"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 get this error i went and noticed that all tables that have more than one primary key defined in the schema were not 'converted' to sqlite, that information is lost.
I believe the problem is in sqlite_backend.py but python isn't my speciality and i'm in a hurry so if you can guide me to a quick fix.
UPDATE (litle more detail):
System.Data.SQLite
"Support for the ADO.NET 3.5 Entity
Framework Supports nearly all the
entity framework functionality that
Sql Server supports, and passes 99% of
the tests in MS's EFQuerySamples demo
application."
Visual Studio 2005/2008 Design-Time
Support You can add a SQLite
connection to the Server Explorer,
create queries with the query
designer, drag-and-drop tables onto a
Typed DataSet and more!
When i drag the tables to the designer, some tables don't make it to the designer. The reasos is,
"The table/view 'main.attachment' does
not have a primary key defined and no
valid primary key could be inferred.
This table/view has been excluded. To
use the entity, you will need to
review your schema, add the correct
keys, and uncomment it."
The problem is this, no entitys = no data.
UPDATE (more info):
My objective isn't change datamodel.
In trac schema the tables attachment, auth_cookie, enum, node_change, permission, session, session_attribute, ticket_change, ticket_custom are defined with primary keys.
When i browse the file trac.db (default) the tables aren't defined with the primary_keys specified in the schema.
I want a solution to solve this litle feature of trac sqlite db.
I don't think it's the best solution edit the table after creation to add pk that aren't created.
UPDATE
Any ideia?!
A:
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.
http://trac.edgewall.org/wiki/TracDev/DatabaseApi
| 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 that all tables that have more than one primary key defined in the schema were not 'converted' to sqlite, that information is lost.
I believe the problem is in sqlite_backend.py but python isn't my speciality and i'm in a hurry so if you can guide me to a quick fix.
UPDATE (litle more detail):
System.Data.SQLite
"Support for the ADO.NET 3.5 Entity
Framework Supports nearly all the
entity framework functionality that
Sql Server supports, and passes 99% of
the tests in MS's EFQuerySamples demo
application."
Visual Studio 2005/2008 Design-Time
Support You can add a SQLite
connection to the Server Explorer,
create queries with the query
designer, drag-and-drop tables onto a
Typed DataSet and more!
When i drag the tables to the designer, some tables don't make it to the designer. The reasos is,
"The table/view 'main.attachment' does
not have a primary key defined and no
valid primary key could be inferred.
This table/view has been excluded. To
use the entity, you will need to
review your schema, add the correct
keys, and uncomment it."
The problem is this, no entitys = no data.
UPDATE (more info):
My objective isn't change datamodel.
In trac schema the tables attachment, auth_cookie, enum, node_change, permission, session, session_attribute, ticket_change, ticket_custom are defined with primary keys.
When i browse the file trac.db (default) the tables aren't defined with the primary_keys specified in the schema.
I want a solution to solve this litle feature of trac sqlite db.
I don't think it's the best solution edit the table after creation to add pk that aren't created.
UPDATE
Any ideia?!
| [
"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():
node = stack.pop()
if problem.isGoalState(node):
print "true"
closed.append(node)
else:
child = problem.getSuccessors(node)
for nodes in child:
stack.push(nodes)
closed.append(node)
return None
Error is:
File line 90, in depthFirstSearch
child = problem.getSuccessors(node)
File line 179, in getSuccessors
x,y = state
**ValueError: too many values to unpack**
The code for the getsuccessor func is:
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
"""
successors = []
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextState = (nextx, nexty)
cost = self.costFn(nextState)
successors.append( ( nextState, action, cost) )
The values returned for this function initially:
problem.getStartState() - (5, 5)
problem.isGoalState(problem.getStartState())- False
problem.getSuccessors(problem.getStartState()) - [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
A:
First, it's unlikely that's the whole getSuccessors method, since there's no return value.
To 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 as two.
You owe it to yourself to find a decent debugger, and learn how to use it. I use Eclipse (with PyDev), and it will significantly help you with these sorts of bugs.
A:
Not sure why there is an inconsistent sized tuples being passed to getSuccessors, but you could probably fix it by checking the length of node after the node = stack.pop() line. If it's 3, then you'll want to pass node[0] in the line child = problem.getSuccessors(node).
| 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.isGoalState(node):
print "true"
closed.append(node)
else:
child = problem.getSuccessors(node)
for nodes in child:
stack.push(nodes)
closed.append(node)
return None
Error is:
File line 90, in depthFirstSearch
child = problem.getSuccessors(node)
File line 179, in getSuccessors
x,y = state
**ValueError: too many values to unpack**
The code for the getsuccessor func is:
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
"""
successors = []
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextState = (nextx, nexty)
cost = self.costFn(nextState)
successors.append( ( nextState, action, cost) )
The values returned for this function initially:
problem.getStartState() - (5, 5)
problem.isGoalState(problem.getStartState())- False
problem.getSuccessors(problem.getStartState()) - [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
| [
"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 10.0.0.1 JUNK JUNK
JUNK IP ADDRESS 10.0.0.3 JUNK JUNK JUNK
JUNK JUNK JUNK
IP ADDRESS 10.0.0.2 JUNK JUNK JUNK JUNK
Note: The ip addresses I used in the example are random ones I used just for this example. In the actual script, it can be any ip address. The information I am trying to find are the ip addresses.
Can pexpect do something like re.findall? Or do I have to do re.findall(regex, p.before)?
A:
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.
In 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 RE, and accumulate those results in an instance variable of your own. So, when pexpect.expect_loop returns, that variable on your instance will have the "extra info" you're looking for.
Seems like a little bit of trial and error would be needed to get it right, and I don't understand what advantages you expect (by this or any other hack to similar purposes) over the straightforward approach you've mentioned, i.e., just using re.findall directly, without messing with pexpect's machinery -- care to explain...?
| 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 JUNK
JUNK JUNK JUNK
IP ADDRESS 10.0.0.2 JUNK JUNK JUNK JUNK
Note: The ip addresses I used in the example are random ones I used just for this example. In the actual script, it can be any ip address. The information I am trying to find are the ip addresses.
Can pexpect do something like re.findall? Or do I have to do re.findall(regex, p.before)?
| [
"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 randomSentenceRedux("My name is Sally Sue")
My is name Sue Sally
>>>print randomSentenceRedux("hello")
hello
>>>print randomSentenceRedux("Don't scream at me!")
Don't at scream me!
>>>
Description:
Write a function to randomize the order of the words in the input string string and return the resulting string. You may assume words are separated by a single space. You MAY NOT use the shuffle function found in python's random module
A:
You should look at Wikipedia's article on the Fisher-Yates shuffle. It's efficient and simple. Here's the psuedo-code they give:
To shuffle an array a of n elements:
for i from n - 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
It should be easy enough to convert to Python.
A:
Not sure how the Python syntax would fit, but using Java, you would tokenize the String on the space delimiter, then use a random index less than the length of the token array, and access that element of the token array, pop it, print it, and repeat until the token array was empty.
A:
It's a really simple algorithm:
Split the Sentence at every space (don't know about jython but both java and python have built-in functions for that)
Shuffle the Array
Join the resulting string array
Print the new string
For which part do you need help exactly?
UPDATE
Algorithm for shuffling
Create a new (empty) Array
While there are items in the old Array
Take a random Number between 0 and the Number of Items in the old Array -1
Remove the item from the old array and push it to the end of the new array
Repeat until there are no more items in the old Array
There are more advanced and definatly more efficient shuffling algorithms but this simple algorithm should get you started.
A:
Regarding shuffling - one idea is to go over the list of items (for i in range(len(lst))) and for each element at position i, swap it with random element (say at position randrange(len(lst)) )
Regarding swapping two variables, remember in Python you can do a,b = b,a and that works - instead of temp=a; a=b; b=temp you have to do in other languages.
Regarding separating the words, it's as easy as strVar.split() and re-assembling as easy as ' '.join(lst).
I am not including the exact code, since this being a homework you are expected to do the work... but with above in mind should be easy, no?
| 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 randomSentenceRedux("hello")
hello
>>>print randomSentenceRedux("Don't scream at me!")
Don't at scream me!
>>>
Description:
Write a function to randomize the order of the words in the input string string and return the resulting string. You may assume words are separated by a single space. You MAY NOT use the shuffle function found in python's random module
| [
"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()
>>> user.get_all_permissions()
set([])
>>> user = User.objects.get(username='test')
>>> user.get_all_permissions()
set([u'slides.add_slide'])
Why did the user object not update on save?
Is there a way save and update the object?
A:
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.
A:
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. Instead, its the "through" table for that relationship ("auth_user_user_permissions") that gets updated. In fact, you don't need to call user.save() at all.
The get_all_permissions() method appears to be using cached data, so if you want the latest changes, use:
user.user_permissions.all()
Note that this will return a list of Permission objects, so if you want a list of codenames in the exact same format as a get_all_permissions() call (not sure why you would though), you can do this:
set(user.user_permissions.values_list('codename', flat=True))
| 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 = User.objects.get(username='test')
>>> user.get_all_permissions()
set([u'slides.add_slide'])
Why did the user object not update on save?
Is there a way save and update the object?
| [
"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 don't know how to import src classes. I've tried importing these ways and I got nothing:
from project.src.class_one import ClassOne
and
from ..src.class_one import ClassOne
What am I doing wrong? Is there a better directory structure?
----- EDIT -----
I changed my dir structure, it's like this now:
Project/
| project.py
| project/
| __init__.py
| class_one.py
| class_two.py
| test/
| __init__.py
| test_class_one.py
And in the test_class_one.py file I'm trying to import this way:
from project.class_one import ClassOne
And it still doesn't work. I'm not using the executable project.py inside a bin dir exactly because I can't import a package from a higher level dir. :(
Thanks. =D
A:
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:
/Users/crocidb/src/project/
I would:
export PYTHONPATH=/Users/crocidb/src
and then in the test_one.py I could:
import project.src.class_one
Actually I would probably do it this way:
export PYTHONPATH=/Users/crocidb/src/project
and then this in test_one.py:
import src.class_one
but that's just my preference and really depends on what the rest of your hierarchy is. Also note that if you already have something in PYTHONPATH you'll want to add to it:
export PYTHONPATH=/Users/crocidb/src/project:$PYTHONPATH
or in the other order if you want your project path to be searched last.
This all applies to windows, too, except you would need to use windows' syntax to set the environment variables.
A:
From Jp Calderone's excellent blog post:
Do:
name the directory something related to your project. For example, if your
project is named "Twisted", name the
top-level directory for its source
files Twisted. When you do releases,
you should include a version number
suffix: Twisted-2.5.
create a directory Twisted/bin and put your executables there, if you
have any. Don't give them a .py
extension, even if they are Python
source files. Don't put any code in
them except an import of and call to a
main function defined somewhere else
in your projects. (Slight wrinkle:
since on Windows, the interpreter is
selected by the file extension, your
Windows users actually do want the .py
extension. So, when you package for
Windows, you may want to add it.
Unfortunately there's no easy
distutils trick that I know of to
automate this process. Considering
that on POSIX the .py extension is a
only a wart, whereas on Windows the
lack is an actual bug, if your
userbase includes Windows users, you
may want to opt to just have the .py
extension everywhere.)
If your project is expressable as a single Python source file, then put it
into the directory and name it
something related to your project. For
example, Twisted/twisted.py. If you
need multiple source files, create a
package instead (Twisted/twisted/,
with an empty
Twisted/twisted/__init__.py) and place
your source files in it. For example,
Twisted/twisted/internet.py.
put your unit tests in a sub-package of your package (note - this means
that the single Python source file
option above was a trick - you always
need at least one other file for your
unit tests). For example,
Twisted/twisted/test/. Of course, make
it a package with
Twisted/twisted/test/__init__.py.
Place tests in files like
Twisted/twisted/test/test_internet.py.
add Twisted/README and Twisted/setup.py to explain and
install your software, respectively,
if you're feeling nice.
Don't:
put your source in a directory called src or lib. This makes it hard
to run without installing.
put your tests outside of your Python package. This makes it hard to
run the tests against an installed
version.
create a package that only has a __init__.py and then put all your code into __init__.py. Just make a module
instead of a package, it's simpler.
try to come up with magical hacks to make Python able to import your module
or package without having the user add
the directory containing it to their
import path (either via PYTHONPATH or
some other mechanism). You will not
correctly handle all cases and users
will get angry at you when your
software doesn't work in their
environment.
| 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 tried importing these ways and I got nothing:
from project.src.class_one import ClassOne
and
from ..src.class_one import ClassOne
What am I doing wrong? Is there a better directory structure?
----- EDIT -----
I changed my dir structure, it's like this now:
Project/
| project.py
| project/
| __init__.py
| class_one.py
| class_two.py
| test/
| __init__.py
| test_class_one.py
And in the test_class_one.py file I'm trying to import this way:
from project.class_one import ClassOne
And it still doesn't work. I'm not using the executable project.py inside a bin dir exactly because I can't import a package from a higher level dir. :(
Thanks. =D
| [
"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 text> IP Address: 1.1.1.1 <random text>
<SEVERAL LINES OF RANDOM TEXT>
... and so on
I know the IP Address of the station I am looking for. Using the IP address, I am trying to construct a regex that will find the station name. The station name can be any length and can contain any number of numbers/letters/underscores. The station name will always be preceded by STATION and will always be followed by a colon. The IP Address will always be on the line following the station name and will always be preceded by IP Address:.
Note there are several stations with different station names and IP Addresses. The 'random text' can be of any length and contain any symbol/number/letter.
So far my attempts have been:
re.search('(?<=STATION ).*?(?=:.*IP Address: %s)' % sta_ip, output, re.DOTALL)
but obviously this will return pretty much the first station name every time.
How would you make a regex that can search for the specified station name? Is this possible?
A:
STATION\s*"(.*?)":\s*.*?(?:\r|\n)<.*?>\s*IP Address:\s*IPHERE\s*<
Replace IPHERE with the IP address and to get the station name, extract the first matching group.
A:
Try /STATION\s*?"(.*?)"\s*?:.*?IP Address:\s*?%s/
The trick is not to be greedy about matching. After matching this regex, the name you want will be in the first capture.
A:
Edit
I've got it. The key is that the station name and IP are only separated by one newline, so we can hardcode that newline.
re.search('STATION(?P<StationName>.*?):.*?\n.*?IP Address: %s' % sta_ip, output).group("StationName")
| 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 <random text>
<SEVERAL LINES OF RANDOM TEXT>
... and so on
I know the IP Address of the station I am looking for. Using the IP address, I am trying to construct a regex that will find the station name. The station name can be any length and can contain any number of numbers/letters/underscores. The station name will always be preceded by STATION and will always be followed by a colon. The IP Address will always be on the line following the station name and will always be preceded by IP Address:.
Note there are several stations with different station names and IP Addresses. The 'random text' can be of any length and contain any symbol/number/letter.
So far my attempts have been:
re.search('(?<=STATION ).*?(?=:.*IP Address: %s)' % sta_ip, output, re.DOTALL)
but obviously this will return pretty much the first station name every time.
How would you make a regex that can search for the specified station name? Is this possible?
| [
"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]).__name__ == 'str'): # <--- this works for strings
elif(type(lists[listname][0]).__name__ == 'object'): <--- this does not work for classes
in the second line of code above, the name variable contains "Address" as the class name. I was hoping it would contain "class" or "object" so I could branch my program. I will have many different types of objects in the future, so it's a bit impractical to perform logic on every different class name, "Address" "Person" etc
please let me know if my question needs clarification.
thanks!!
A:
FYI: it also makes a difference if its a new-style class or not:
# python
type(1).__name__
'int'
type('1').__name__
'str'
class foo(object):
pass
type(foo()).__name__
'foo'
class bar:
pass
type(bar()).__name__
'instance'
If you can make sure they're all new-style classes, your method will determine the real type. If you make them old-style, it'll show up as 'instance'. Not that I'm recommending making everything all old-style just for this.
However, you can take it one step further:
type(bar().__class__).__name__
'classobj'
type(foo().__class__).__name__
'type'
And always look for 'classobj' or 'type'. (Or the name of the metaclass, if it has one.)
A:
I think you want the isinstance function.
if isinstance(o, ClassName):
However, you'll need to first verify that o is an object, you can use type for that.
A:
It's common in Python to use exception handling to decide which code path to take; inspecting the exact type of an object (with isinstance()) to decide what to do with it is discouraged.
For example, say that what you want to do is, if it's a string, print it in "title case", and if it's an object, you want to call a particular method on it. So:
try:
# is it an object with a particular method?
lists[listname][0].particularMethod()
except AttributeError:
# no, it doesn't have particularMethod(),
# so we expect it to be a string; print it in title case
print lists[listname][0].title()
| 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(lists[listname][0]).__name__ == 'object'): <--- this does not work for classes
in the second line of code above, the name variable contains "Address" as the class name. I was hoping it would contain "class" or "object" so I could branch my program. I will have many different types of objects in the future, so it's a bit impractical to perform logic on every different class name, "Address" "Person" etc
please let me know if my question needs clarification.
thanks!!
| [
"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', 'w')
...then loop thru the lines...
for line in infile:
...add your content at the beginning...
newline = "stuff for beginning of line" + line
...then write the line to the output...
outfile.write(newline)
...lastly, don't forget to close your files!
infile.close()
outfile.close()
Or, here's a shorter version that is more "Pythonic". (Note that it sucks in the whole file at once, so don't use it for really large files, or it will suck!):
with open('inputfile', 'r') as infile:
lines = infile.readlines()
with open('outputfile', 'w') as outfile:
outfile.write("prefix-" + "prefix-".join(lines))
A:
Unless you perform this particular task on a regular basis, you don't really need a python script for it. Most editors created with programming in mind (Vim, Emacs, Notepad++, etc) supports some kind of regexp-based search and replace.
Replacing ^\(.*\)$ with "\1" should wrap all lines in double-quotes in editors that use simple regular expressions. Depending on what tool you use, this might be done in easier ways too; e.g. in a line-by-line substitution with Sed or Vim, replacing .* with "&" does the same job.
If you're unfamiliar with regular expressions, I highly recommend googling for a good tutorial. Check out the three-part introduction to Sed by Daniel Robbins if you're using Linux/Unix. You may also refer to this page for a more general introduction to regular expressions.
| 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 documentation/code completion entries that Netbeans can use.
Does anyone know how to use the PIL documentation with Netbeans (if this is possible?)
Thank you for your help!
A:
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.
| 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 documentation with Netbeans (if this is possible?)
Thank you for your help!
| [
"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 drawbacks to the method I am using? (or have recommendations for a better one?)
I've read the Python docs and many exception-related posts here, and understand that blanket except clauses are usually a bad idea. Within subroutines and modules I always
use except to handle specific expected exceptions, but it seems useful to have a "catch-all" except clause at the highest level of the program to ensure I can log the exception before the program exits.
What do you think?
import traceback
try:
# main program code here
except BaseException:
tb = traceback.format_exc()
msg = "Exiting program due to exception:" + tb
LogToFile(msg) # custom logging function
SendAlertEmail(msg) # warn admin that program terminated
raise # program exits with the existing exception
Note that I was using BaseException instead of Exception because if someone at the terminal presses Ctrl-C, I would like to log that as the reason for exiting the program (and alert an admin that the program was exited). But I suppose I could also use:
except Exception, KeyboardInterrupt:
A:
There is no specific drawback, but there is an excellent alternative -- sys.excepthook.
In 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 instance of a subclass of BaseException. E.g.:
>>> class X: pass
...
>>> raise X
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.X: <__main__.X instance at 0xc9ad0>
As you see, it is still possible to raise something a except BaseException: would not catch -- that's why bare-except except: still exists (specifically for very special uses such as yours!).
Whether you use the hook, or build your own, consider (perhaps depending on configuration flags or environment settings) not burdening the end-user with all the details (just as a neat touch of improved user experience!), just a meaningful summary (reassuring the user that all details of the problem have been recorded, etc, etc).
A:
Consider what happens if the exception is due to lack of diskspace. If the logging is written to the same partition
LogToFile(msg)
will raise an exception, an so no email is sent either. A simple try/except around each will avoid that problem
tb = traceback.format_exc()
msg = "Exiting program due to exception:" + tb
try:
LogToFile(msg) # custom logging function
except:
pass
try:
SendAlertEmail(msg) # warn admin that program terminated
except:
pass
raise # program exits with the existing exception
A:
"I've read the Python docs and many exception-related posts here, and understand that blanket except clauses are usually a bad idea."
The rationale for that is that you might be expecting three kinds of exception then wind up swallowing the fourth kind that you never considered was a possibility. A handler that does an unconditional re-raise eliminates this concern -- you will be seeing unexpected exceptions -- so it's a perfectly cromulent exception to the general rule.
| 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 exception-related posts here, and understand that blanket except clauses are usually a bad idea. Within subroutines and modules I always
use except to handle specific expected exceptions, but it seems useful to have a "catch-all" except clause at the highest level of the program to ensure I can log the exception before the program exits.
What do you think?
import traceback
try:
# main program code here
except BaseException:
tb = traceback.format_exc()
msg = "Exiting program due to exception:" + tb
LogToFile(msg) # custom logging function
SendAlertEmail(msg) # warn admin that program terminated
raise # program exits with the existing exception
Note that I was using BaseException instead of Exception because if someone at the terminal presses Ctrl-C, I would like to log that as the reason for exiting the program (and alert an admin that the program was exited). But I suppose I could also use:
except Exception, KeyboardInterrupt:
| [
"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 modules from webhelpers and those work. I'm wondering why I don't have secure_form and how I can obtain this module manually? I've tried re-running go-pylons.py and it didn't help.
Any ideas?
A:
if your webhelpers version is 1.0b4 or above, secure_form is under webhelpers.pylonslib, ie.
from webhelpers.pylonslib import secure_form
A:
I just ran into this as well.
In case the other posts aren't obvious to get the old version of webhelpers you can run:
easy_install webhelpers==0.6.4
A:
ugh, so for some reason I have 1.0b4 of webhelpers installed and the path to secure_form changed... (http://groups.google.com/group/pylons-discuss/msg/695d73b831a4aee3) I guess my question now becomes: how do I install a previous version of webhelpers? I have easy_install
A:
Actually looking at this, I got something similar and the proper tested line of import is:
from webhelpers.pylonslib.secure_form import secure_form
| 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 wondering why I don't have secure_form and how I can obtain this module manually? I've tried re-running go-pylons.py and it didn't help.
Any ideas?
| [
"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 python
import Image
bild = Image.open("au-lgflag.gif").convert("RGB")
bild.getcolors()
[(44748, (255, 255, 255)), (452, (236, 145, 146)), (653, (191, 147, 149)), ...)]
What I found strange here is that the austrian flag only has two colors in it, but the above output shows more than ten. Do you know why? My idea was to only count the top 5 colors and as I'm not interested in every color I would do some "normalize" the numbers to multiples of 64 (so (236, 145, 146) becomes (192, 128, 128)).
However at the moment I have no idea what is the best way to extract more information (Ist there a star in the image? or else). Could you give me some hints on how to do it?
Thanks in advance
A:
The Python Imaging Library - PIL just does basic image manipulation - opening, some transforms or filters, and saving to other formats.
Pattern recognition, is part of an advanced image processign field and evolving -- it deos use algorithms far different than those present in PIL.
There are some libraries and frameworks you can use in Python for pattern recognition - (recognising stars, and moons, and so) - Although I advance you: if you want this just to classify one0-hundered-and-a-few coutnry flags, you should do it manually, rather than try to dive in pattern recognition.
Your comment on the number of colors tells that you are not used with computer images at all. And pattern recognition is hardcore, even with a python front-end. (You can't expect any current framework to know beforehand what is a "moon" or a "star" for example)
So, for less than 500 images, you can resort to software that allows you to tag images manually and write some code to link the tags to each flag.
As for the colors: Computer rasterized images are formed of pixels. These are Square. At the boundary between different colors, if a pixel is on one color (say white), and its neighbor is a complete different color (like red), this boundary will show up jagged. This is known as "aliasing". To diminish this, computer software mixes colors at hard boundaries, creating intermediate colors - that is why a PNG even with 2 apparent colors can have several colors internally. For .JPG it is even worse, because the rounded decimal numbers for RGB colors we use are not even stored as they are in the image.
Unlike pattern recognizing, you can downsize the number of colours seen by using just the most significant bits of each component. I'd say the two most significant bits would be enough.
The following python function could do that using a color count given by PIL:
def get_main_colors(col_list):
main_colors = set()
for index, color in col_list:
main_colors.add(tuple(component >> 6 for component in color))
return [tuple(component << 6 for component in color) for color in main_colors]
call it with "get_main_colors(bild.get_colors()) " for example.
Here is another question dealing with the pattern recognition part:
python image recognition
A:
First some quick terminology, just in case:
A classifier learns a map of inputs to outputs. You train a classifier by giving it input/output pairs, for example feature vectors like color information and labels like 'czech flag'. In practice, the labels are represented as scalar numbers. In your example, you have a multi-class problem, which simply means that there are more than two possible labels (obviously, since there are more than two country flags). Training a multi-class classifier can a little trickier than the vanilla binary classifier, so you may want to search for terms like "multi-class classifier" or "one-vs-many classifier" to investigate the best approach for you.
On to the problem:
I think your problem might be easily-solved using a simple classifier, like k-nearest neighbors, with color histograms as feature vectors. In particular, I would use HSV feature vectors as opposed to RGB feature vectors. Some great results have been reported in the literature using just this kind of simple classifier system, for example: SVMs for Histogram-Based Image Classification. In that paper, the authors use a particular classifier known as a Support Vector Machine (SVM) and HSV feature vectors. HSV feature vectors also sidestep the issue of image scale and rotation, for example a flag that is 1024x768 vs 640x480, or a flag that is rotated in an image by 45 degrees.
The pseudocode for training the algorithm would look something like this:
# training simple kNN -- just compute feature vectors, collect labels
X = [] # tuple (input example, label)
for training_image in data:
x = get_hsv_vector(training_image)
y = get_label(training_image)
X.append((x,y))
# classification -- pick k closest feature vectors
K = 3 # the 'k' in kNN -- how many similar featvecs to use
d = [] # (distance, label) tuples for scoring
x_test = get_hsv_vector(test_image) # feature vector to be classified
for x_train in X:
d.append((distance(x_test[0], x_train), x_test[1])
# sort distances, d, by closeness and pick top K labels for scoring
d.sort()
output = get_majority_vote([x[1] for x in d[:K]])
The kNN classifier is available in several python packages, with good documentation. It should be pretty easy to convert to HSV colorspace as well. If you don't achieve your desired results, you can try to improve your feature vectors or your classifier.
| 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.gif").convert("RGB")
bild.getcolors()
[(44748, (255, 255, 255)), (452, (236, 145, 146)), (653, (191, 147, 149)), ...)]
What I found strange here is that the austrian flag only has two colors in it, but the above output shows more than ten. Do you know why? My idea was to only count the top 5 colors and as I'm not interested in every color I would do some "normalize" the numbers to multiples of 64 (so (236, 145, 146) becomes (192, 128, 128)).
However at the moment I have no idea what is the best way to extract more information (Ist there a star in the image? or else). Could you give me some hints on how to do it?
Thanks in advance
| [
"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 causes the test to fail after the test code has completed. How can I write a passing unit test for this code? Is it expected that every Deferred which could fail in normal operation should have an errback at the end of the chain which puts it back on the callback chain?
The same thing happens when there's a failed Deferred in a DeferredList, unless I create the DeferredList with consumeErrors. This is the case even when the DeferredList is created with fireOnOneErrback and is given an errback which puts it back on the callback chain. Are there any implications for consumeErrors besides suppressing test failures and error logging? Should every Deferred which may fail without an errback be put a DeferredList?
Example tests of example code:
from twisted.trial import unittest
from twisted.internet import defer
def get_dl(**kwargs):
"Return a DeferredList with a failure and any kwargs given."
return defer.DeferredList(
[defer.succeed(True), defer.fail(ValueError()), defer.succeed(True)],
**kwargs)
def two_deferreds():
"Create a failing Deferred, and create and return a succeeding Deferred."
d = defer.fail(ValueError())
return defer.succeed(True)
class DeferredChainTest(unittest.TestCase):
def check_success(self, result):
"If we're called, we're on the callback chain."
self.fail()
def check_error(self, failure):
"""
If we're called, we're on the errback chain.
Return to put us back on the callback chain.
"""
return True
def check_error_fail(self, failure):
"""
If we're called, we're on the errback chain.
"""
self.fail()
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_plain(self):
"""
Test that a DeferredList without arguments is on the callback chain.
"""
# check_error_fail asserts that we are on the callback chain.
return get_dl().addErrback(self.check_error_fail)
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_fire(self):
"""
Test that a DeferredList with fireOnOneErrback errbacks on failure,
and that an errback puts it back on the callback chain.
"""
# check_success asserts that we don't callback.
# check_error_fail asserts that we are on the callback chain.
return get_dl(fireOnOneErrback=True).addCallbacks(
self.check_success, self.check_error).addErrback(
self.check_error_fail)
# This succeeds.
def test_consume(self):
"""
Test that a DeferredList with consumeErrors errbacks on failure,
and that an errback puts it back on the callback chain.
"""
# check_error_fail asserts that we are on the callback chain.
return get_dl(consumeErrors=True).addErrback(self.check_error_fail)
# This succeeds.
def test_fire_consume(self):
"""
Test that a DeferredList with fireOnOneCallback and consumeErrors
errbacks on failure, and that an errback puts it back on the
callback chain.
"""
# check_success asserts that we don't callback.
# check_error_fail asserts that we are on the callback chain.
return get_dl(fireOnOneErrback=True, consumeErrors=True).addCallbacks(
self.check_success, self.check_error).addErrback(
self.check_error_fail)
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_two_deferreds(self):
# check_error_fail asserts that we are on the callback chain.
return two_deferreds().addErrback(self.check_error_fail)
A:
There are two important things about trial related to this question.
First, 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.
Second, a test method which returns a Deferred will not pass if the Deferred fires with a Failure.
This means that neither of these tests can pass:
def test_logit(self):
defer.fail(Exception("oh no"))
def test_returnit(self):
return defer.fail(Exception("oh no"))
This is important because the first case, the case of a Deferred being garbage collected with a Failure result, means that an error happened that no one handled. It's sort of similar to the way Python will report a stack trace if an exception reaches the top level of your program.
Likewise, the second case is a safety net provided by trial. If a synchronous test method raises an exception, the test doesn't pass. So if a trial test method returns a Deferred, the Deferred must have a success result for the test to pass.
There are tools for dealing with each of these cases though. After all, if you couldn't have a passing test for an API that returned a Deferred that fired with a Failure sometimes, then you could never test your error code. That would be a pretty sad situation. :)
So, the more useful of the two tools for dealing with this is TestCase.assertFailure. This is a helper for tests that want to return a Deferred that's going to fire with a Failure:
def test_returnit(self):
d = defer.fail(ValueError("6 is a bad value"))
return self.assertFailure(d, ValueError)
This test will pass because d does fire with a Failure wrapping a ValueError. If d had fired with a success result or with a Failure wrapping some other exception type, then the test would still fail.
Next, there's TestCase.flushLoggedErrors. This is for when you're testing an API that's supposed to log an error. After all, sometimes you do want to inform an administrator that there's a problem.
def test_logit(self):
defer.fail(ValueError("6 is a bad value"))
gc.collect()
self.assertEquals(self.flushLoggedErrors(ValueError), 1)
This lets you inspect the failures which got logged to make sure your logging code is working properly. It also tells trial not to worry about the things you flushed, so they'll no longer cause the test to fail. (The gc.collect() call is there because the error isn't logged until the Deferred is garbage collected. On CPython, it'll be garbage collected right away due to the reference counting GC behavior. However, on Jython or PyPy or any other Python runtime without reference counting, you can't rely on that.)
Also, since garbage collection can happen at pretty much any time, you might sometimes find that one of your tests fails because an error is logged by a Deferred created by an earlier test being garbage collected during the execution of the later test. This pretty much always means your error handling code is incomplete in some way - you're missing an errback, or you failed to chain two Deferreds together somewhere, or you're letting your test method finish before the task it started actually finishes - but the way the error is reported sometimes makes it hard to track down the offending code. Trial's --force-gc option can help with this. It causes trial to invoke the garbage collector between each test method. This will slow down your tests significantly, but it should cause the error to be logged against the test which is actually triggering it, not an arbitrary later test.
| 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 passing unit test for this code? Is it expected that every Deferred which could fail in normal operation should have an errback at the end of the chain which puts it back on the callback chain?
The same thing happens when there's a failed Deferred in a DeferredList, unless I create the DeferredList with consumeErrors. This is the case even when the DeferredList is created with fireOnOneErrback and is given an errback which puts it back on the callback chain. Are there any implications for consumeErrors besides suppressing test failures and error logging? Should every Deferred which may fail without an errback be put a DeferredList?
Example tests of example code:
from twisted.trial import unittest
from twisted.internet import defer
def get_dl(**kwargs):
"Return a DeferredList with a failure and any kwargs given."
return defer.DeferredList(
[defer.succeed(True), defer.fail(ValueError()), defer.succeed(True)],
**kwargs)
def two_deferreds():
"Create a failing Deferred, and create and return a succeeding Deferred."
d = defer.fail(ValueError())
return defer.succeed(True)
class DeferredChainTest(unittest.TestCase):
def check_success(self, result):
"If we're called, we're on the callback chain."
self.fail()
def check_error(self, failure):
"""
If we're called, we're on the errback chain.
Return to put us back on the callback chain.
"""
return True
def check_error_fail(self, failure):
"""
If we're called, we're on the errback chain.
"""
self.fail()
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_plain(self):
"""
Test that a DeferredList without arguments is on the callback chain.
"""
# check_error_fail asserts that we are on the callback chain.
return get_dl().addErrback(self.check_error_fail)
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_fire(self):
"""
Test that a DeferredList with fireOnOneErrback errbacks on failure,
and that an errback puts it back on the callback chain.
"""
# check_success asserts that we don't callback.
# check_error_fail asserts that we are on the callback chain.
return get_dl(fireOnOneErrback=True).addCallbacks(
self.check_success, self.check_error).addErrback(
self.check_error_fail)
# This succeeds.
def test_consume(self):
"""
Test that a DeferredList with consumeErrors errbacks on failure,
and that an errback puts it back on the callback chain.
"""
# check_error_fail asserts that we are on the callback chain.
return get_dl(consumeErrors=True).addErrback(self.check_error_fail)
# This succeeds.
def test_fire_consume(self):
"""
Test that a DeferredList with fireOnOneCallback and consumeErrors
errbacks on failure, and that an errback puts it back on the
callback chain.
"""
# check_success asserts that we don't callback.
# check_error_fail asserts that we are on the callback chain.
return get_dl(fireOnOneErrback=True, consumeErrors=True).addCallbacks(
self.check_success, self.check_error).addErrback(
self.check_error_fail)
# This fails after all callbacks and errbacks have been run, with the
# ValueError from the failed defer, even though we're
# not on the errback chain.
def test_two_deferreds(self):
# check_error_fail asserts that we are on the callback chain.
return two_deferreds().addErrback(self.check_error_fail)
| [
"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 127, it keeps on going to the else!
can some one tell me why?
A:
raw_input returns a string and "93" is NOT in range(128).
To make sure you compare apples to apples, cast key_one to int:
key = int(raw_input("Enter key (0 <= key <= 127): "))
if key in range(128)
# if condition
else
# else condition
EDIT: Python documentation is awesome, so if you have questions, it's a great idea to train by reading the docs first.
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
- http://docs.python.org/library/functions.html#raw_input
A:
raw_input will return a string, so your if comparison fails (you're comparing an int with a string). Try casting:
key_one = int(raw_input('enter key: '))
| 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 the else!
can some one tell me why?
| [
"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 filtering), then access on that element the attribute name of that property.
For an alternate reading: if you want an element whose list property in question contains a certain value, as for that attribute to "equal" said value. As the docs say:
In a query, comparing a list property
to a value performs the test against
the list members: list_property =
value tests if the value appears
anywhere in the list
Did you mean one of these two things, or yet another I wasn't able to guess from your arcane words?-)
| 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.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTails(course, tails), dep_arc_tail_q)
The modelutils methods:
def applyToResultsOfQuery(func, q):
results = q.fetch(1000)
while results:
func(results)
results = q.fetch(1000)
def removeCourseFromTail(course, tail):
# tail = DependencyArcTail.get(key_tail)
if not course in tail.courses:
return
if len(tail.courses) == 1:
DependencyArcTail.delete(tail)
return
tail.courses.remove(course)
def removeCourseFromTails(course, tails):
''' Removes `course` from a collection of `tails` '''
removeThisCourseFromTail = functools.partial(removeCourseFromTail, course)
map(removeThisCourseFromTail, tails)
I'm not getting any sort of crash or traceback... the devserver is just entirely unresponsive.
Notably, another function also uses modelutils.applyToResultsOfQuery to delete models:
def _deleteType(kind):
q = kind.all(keys_only=True)
deleteResultsOfQuery(q)
def deleteResultsOfQuery(q):
applyToResultsOfQuery(db.delete, q)
The tests run fine with these methods, making me think that the problem isn't with applyToResultsOfQuery.
Here are the models in use:
class Course(db.Model):
dept_code = db.StringProperty(required=True)
number = db.IntegerProperty(required=True)
title = db.StringProperty(multiline=True) # not sure that this should be multiline...
pickled_pre_reqs = db.StringProperty(multiline=True)
# the unparsed pre req phrase (like "CS 2110 or 1110")
unparsed_pre_reqs = db.StringProperty()
# the full value of the Note part of the course catalog listing
full_description = db.TextProperty()
# the page on which this course is described
course_catalog_url = db.LinkProperty()
parse_succeeded = db.BooleanProperty()
# true if this course has had its dependency graph built
graph_built = db.BooleanProperty()
tailsMemberOf = db.ListProperty(db.Key)
def getPreReqs(self):
return pickle.loads(str(self.pickled_pre_reqs))
def __repr__(self):
if self.dept_code == "UNKNOWN":
return "Unknown course"
return "%s %s: %s" % (self.dept_code, self.number, self.title)
# just use __dict__?
def __attrs(self):
return (self.dept_code, self.number, self.title, self.pickled_pre_reqs, self.full_description, self.unparsed_pre_reqs, self.course_catalog_url)
def __eq__(self, other):
return isinstance(other, Course) and self.__attrs() == other.__attrs()
def __hash__(self):
return hash(self.__attrs())
class DependencyArcTail(db.Model):
''' A list of courses that is a pre-req for something else '''
courses = db.ListProperty(db.Key) # can this be changed to Course.key?
''' a list of heads that reference this one '''
forwardLinks = db.ListProperty(db.Key)
def __repr__(self):
return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks))
def __eq__(self, other):
return isinstance(other, DependencyArcTail) and set(self.courses) == set(other.courses) and set(self.forwardLinks) == set(other.forwardLinks)
def __hash__(self):
return hash((frozenset(self.courses), frozenset(self.forwardLinks)))
What else could I be doing wrong here?
UPDATE: It appears that after running the test with that line uncommented, the entire dev server crashes. If I navigate to a non-test page after that, I get 500'd. I'm not sure what conclusions to draw from that.
UPDATE 2: If I get rid of modeutils, and write it out another way, it works fine:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
# modelutils.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTails(course, tails), dep_arc_tail_q)
results = dep_arc_tail_q.fetch(1000)
# while results:
for tail in results:
modelutils.removeCourseFromTail(course, tail)
# results = dep_arc_tail_q.fetch(1000)
However, if I change the comments up, it fails again:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
# modelutils.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTails(course, tails), dep_arc_tail_q)
results = dep_arc_tail_q.fetch(1000)
while results:
for tail in results:
modelutils.removeCourseFromTail(course, tail)
results = dep_arc_tail_q.fetch(1000)
Am I getting an infinite loop? Is fetch() not working as I expect?
A:
fetch(1000) will always return the first 1000 results.
You may want to try using cursors, something like this:
results = dep_arc_tail_q.fetch(1000)
while results:
for tail in results:
modelutils.removeCourseFromTail(course, tail)
results = dep_arc_tail_q.with_cursor(dep_arc_tail_q.cursor()).fetch(1000)
| 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.removeCourseFromTails(course, tails), dep_arc_tail_q)
The modelutils methods:
def applyToResultsOfQuery(func, q):
results = q.fetch(1000)
while results:
func(results)
results = q.fetch(1000)
def removeCourseFromTail(course, tail):
# tail = DependencyArcTail.get(key_tail)
if not course in tail.courses:
return
if len(tail.courses) == 1:
DependencyArcTail.delete(tail)
return
tail.courses.remove(course)
def removeCourseFromTails(course, tails):
''' Removes `course` from a collection of `tails` '''
removeThisCourseFromTail = functools.partial(removeCourseFromTail, course)
map(removeThisCourseFromTail, tails)
I'm not getting any sort of crash or traceback... the devserver is just entirely unresponsive.
Notably, another function also uses modelutils.applyToResultsOfQuery to delete models:
def _deleteType(kind):
q = kind.all(keys_only=True)
deleteResultsOfQuery(q)
def deleteResultsOfQuery(q):
applyToResultsOfQuery(db.delete, q)
The tests run fine with these methods, making me think that the problem isn't with applyToResultsOfQuery.
Here are the models in use:
class Course(db.Model):
dept_code = db.StringProperty(required=True)
number = db.IntegerProperty(required=True)
title = db.StringProperty(multiline=True) # not sure that this should be multiline...
pickled_pre_reqs = db.StringProperty(multiline=True)
# the unparsed pre req phrase (like "CS 2110 or 1110")
unparsed_pre_reqs = db.StringProperty()
# the full value of the Note part of the course catalog listing
full_description = db.TextProperty()
# the page on which this course is described
course_catalog_url = db.LinkProperty()
parse_succeeded = db.BooleanProperty()
# true if this course has had its dependency graph built
graph_built = db.BooleanProperty()
tailsMemberOf = db.ListProperty(db.Key)
def getPreReqs(self):
return pickle.loads(str(self.pickled_pre_reqs))
def __repr__(self):
if self.dept_code == "UNKNOWN":
return "Unknown course"
return "%s %s: %s" % (self.dept_code, self.number, self.title)
# just use __dict__?
def __attrs(self):
return (self.dept_code, self.number, self.title, self.pickled_pre_reqs, self.full_description, self.unparsed_pre_reqs, self.course_catalog_url)
def __eq__(self, other):
return isinstance(other, Course) and self.__attrs() == other.__attrs()
def __hash__(self):
return hash(self.__attrs())
class DependencyArcTail(db.Model):
''' A list of courses that is a pre-req for something else '''
courses = db.ListProperty(db.Key) # can this be changed to Course.key?
''' a list of heads that reference this one '''
forwardLinks = db.ListProperty(db.Key)
def __repr__(self):
return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks))
def __eq__(self, other):
return isinstance(other, DependencyArcTail) and set(self.courses) == set(other.courses) and set(self.forwardLinks) == set(other.forwardLinks)
def __hash__(self):
return hash((frozenset(self.courses), frozenset(self.forwardLinks)))
What else could I be doing wrong here?
UPDATE: It appears that after running the test with that line uncommented, the entire dev server crashes. If I navigate to a non-test page after that, I get 500'd. I'm not sure what conclusions to draw from that.
UPDATE 2: If I get rid of modeutils, and write it out another way, it works fine:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
# modelutils.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTails(course, tails), dep_arc_tail_q)
results = dep_arc_tail_q.fetch(1000)
# while results:
for tail in results:
modelutils.removeCourseFromTail(course, tail)
# results = dep_arc_tail_q.fetch(1000)
However, if I change the comments up, it fails again:
dep_arc_tail_q = db.GqlQuery("SELECT * FROM DependencyArcTail WHERE courses = :1", course)
# modelutils.applyToResultsOfQuery(lambda tails : modelutils.removeCourseFromTails(course, tails), dep_arc_tail_q)
results = dep_arc_tail_q.fetch(1000)
while results:
for tail in results:
modelutils.removeCourseFromTail(course, tail)
results = dep_arc_tail_q.fetch(1000)
Am I getting an infinite loop? Is fetch() not working as I expect?
| [
"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/testimage.jpg'
os.system(command)
When I run the project through django development server, it works fine. The image is deleted.
But if I run on apache it does not work. The image is not deleted. I checked the apache error logs, they are no errors in the apache log. Please help.
A:
Make sure the apache user has permission to write for all the images and folders you are deleting from.
A:
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.
| 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 project through django development server, it works fine. The image is deleted.
But if I run on apache it does not work. The image is not deleted. I checked the apache error logs, they are no errors in the apache log. Please help.
| [
"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 extract it from the list.same thing goes for action too.
A:
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 you want a list of lists, code:
alist = [[state, action, cost], [state, action, cost], ...]
If you want to transform the list of tuples in a list of lists,
alist = [list(t) for t in alist]
(see why you should never usurp built-in identifiers such as list?!-).
If you want to flatten the list-of-lists (or -of-tuples) into a single list,
aflatlist = [x for t in alist for x in t]
To access e.g. "just the state" (first item), say of the Nth item in the list,
justthestate = alist[N][0]
or, if you've flattened it,
justhestate = aflatlist[N*3 + 0]
(the + 0 is clearly redundant, but it's there to show you what to do for the cost, which would be at + 1, etc).
If you want a list with all states,
allstates = [t[0] for t in alist]
or
allstates = aflatlist[0::3]
I'm sure you could mean something even different from this dozen of possible interpretations of your arcane words, but I'm out of juice by now;-).
A:
I'm not sure I understand the first part of your question ("form of a list"). You can construct the list of tuples in the form you've stated:
mylist = [(1, 'west', 5), (1, 'east', 3), (2, 'west', 6)]
# add another tuple
mylist.append((2, 'east', 7))
To extract only the states or actions (i.e. the first or second item in each tuple), you can use list comprehensions:
states = [item[0] for item in mylist]
actions = [item[1] for item in mylist]
A:
The code you listed above is a list of tuples - which pretty much matches what you're asking for.
From the example above, list[0][0] returns the state from the first tuple, list[0][1] the action, and list[0][2] the cost.
You can extract the values with something like (state, action, cost)= list[i] too.
A:
try this
l = [('a',1,2),('b',3,4),('a',4,6), ('a',6,8)]
state = [sl[0] for sl in l]
or for more,
state = [sl[0] for sl in l if 'a' in sl]
| 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 thing goes for action too.
| [
"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%3Ffeaturename%20where%20%7B%3Fpart%20%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23annotation%3E%20%3Fannotation%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23status%3E%20'Available'%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23name%3E%20%3Fname.%3Fannotation%20%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23feature%3E%20%3Ffeature.%3Ffeature%20%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23type%3E%20%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23binding%3E%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23name%3E%20%3Ffeaturename%7D"
>>> raw_result = urllib.urlopen(query)
>>> xml_result = xml.dom.minidom.parse(raw_result)
That last command gives me
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 4
Almost the same thing happens if I use xml.etree.ElementTree to do the parsing. I think they both use Expat. The weird part is, if instead of loading the file in python I just paste the query into Firefox, the resulting file can be read in perfectly well using open(path_to_file, "r").
Any ideas what this could be?
UPDATE:
This is the first line of the file:
<?xml version='1.0' encoding='UTF-8'?>
However that may not be what's in raw_result... that's what you get after downloading query-result.srx and changing the extension to .txt. The file extension doesn't matter does it? Also, I'm pretty new to this whole xml thing—why is column 4 the 8th character? – Jeff 0 secs ago edit
A:
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.
My guess is that first line violates something in the "well formed XML" content anwyay. For reference, you might compare against http://en.wikipedia.org/wiki/XML
A:
Looks like something is wrong with your XML file, right about line 1, column 4.
I tried this, and what I got doesn't look like XML to me. Here are the first eight characters, as Alex suggested:
>>> raw_result.read(8)
'BRTR\x00\x00\x00\x03'
A:
Your server is picky about the accept header in deciding what to send back and in which format. The following should work:
In [265]: import urllib2
In [266]: req = urllib2.Request(query, headers={'Accept':'application/xml'})
In [267]: rsp = urllib2.urlopen(req)
In [268]: xml = minidom.parse(rsp)
In [268]: xml.toxml()[:64]
Out[268]: u'<?xml version="1.0" ?><sparql xmlns="http://www.w3.org/2005/spar'
Note the accept header in urllib2.Request.
A:
It seems that the RDF server is delivering plain text to your urllib.urlopen call.
You should be able, with setting the right header
Accept: application/sparql-results+xml, */*;q=0.5
, to get the xml response. You have to read the RDF protocol specification of openRDF for details - there is for openRDF more than one format.
| 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%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23annotation%3E%20%3Fannotation%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23status%3E%20'Available'%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23name%3E%20%3Fname.%3Fannotation%20%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23feature%3E%20%3Ffeature.%3Ffeature%20%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23type%3E%20%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23binding%3E%3B%3Chttp%3A%2F%2Fsbol.bhi.washington.edu%2Frdf%2Fsbol.owl%23name%3E%20%3Ffeaturename%7D"
>>> raw_result = urllib.urlopen(query)
>>> xml_result = xml.dom.minidom.parse(raw_result)
That last command gives me
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 4
Almost the same thing happens if I use xml.etree.ElementTree to do the parsing. I think they both use Expat. The weird part is, if instead of loading the file in python I just paste the query into Firefox, the resulting file can be read in perfectly well using open(path_to_file, "r").
Any ideas what this could be?
UPDATE:
This is the first line of the file:
<?xml version='1.0' encoding='UTF-8'?>
However that may not be what's in raw_result... that's what you get after downloading query-result.srx and changing the extension to .txt. The file extension doesn't matter does it? Also, I'm pretty new to this whole xml thing—why is column 4 the 8th character? – Jeff 0 secs ago edit
| [
"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 include being listed as one of the four languages Google uses. Possible reasons include:
enables rapid systems application prototyping using of c++ libraries using swig wrappers
built to a well defined language specification
innovative features at the syntax level enabling high level of expressiveness
highly flexible web frameworks built long before other languages (django)
The questions is what makes it so popular/highly regarded, but to give some balance I'm going to give some reasons it might not be popular:
less tool support
less enterprise support (ie a vendor helpdesk)
lower performance
BDFL not caring about backward compatibility in version upgrades
Or was it just the best at a particular point in time (about 8 years ago) and other languages and frameworks have since caught up?
A:
Highly expressive language. People often say, "Python works the way my brain does".
Dynamic typing means you spend zero time appeasing the compiler.
A large standard library means you often have the tools you need at your fingertips.
An even larger stable of third-party packages (PIL, Numpy, NLTK, Django) mean that large problem domains are often well-supported.
Open-source implementation means you don't have to grovel at the vendor helpdesk, you can find answers yourself, and get solutions from a large community of users.
A:
enables rapid systems application prototyping using of c++ libraries using swig wrappers
... What?
Most people doing Python programming aren't doing C++ programming, they're doing Python programming. And they're doing it fast, because they don't need to worry about things like memory management, or templates, or... the sort of namespace support C++ uses.
A:
I started twelve years ago to replace my Perl scripts -- and the new ones were shorter and way more readable. So, readability and the gentle learning curve was the main reason to use it.
After version 2, the language has got more and more flexible, and with it my programming needs and I got used to do metaprogramming without even noticing.
To see what I mean, have a look at the examples in SQLAlchemy's documentation.
You point to lack of tools -- but the last time I've seen a code generator has been ... I guess 10 years ago, and it was a bad idea even at the time, because you just don't need it.
The development team cares a lot about compatibility -- they ponder for years before introducing new syntax. Only mature modules go in the standard library, and python 3 has been discussed for ages. On top of the porting facilities, there is now a moratorium -- no new features to the language for at least two years.
As for performance - since I don't have to think about which methods throws which exception or having explicit interfaces for everything, and I have a lot more design patterns embedded in the language.. well, I am free to experiment with the architecture and optimize where it makes sense. Most of the time, for me, it's the network or the DB.
A:
In my experience, I haven't noticed less tool support so much as not needing big, heavy tools to get what I need from Python.
As to enterprise support there are distributions such as ActiveState and
Enthought depending on your needs. We use AIX at my day job and while we did use AS Python at one point, the standard distribution works really well for us. We just haven't needed vendor support.
And I agree with Ned, I can't tell you how many times that instead of looking at the docs, I've just tried something and it just worked. I'm not talking necessarily about a familiar library but just being comfortable with the way Python thinks. This also means when I go back and look at old code, I seem to grok it a lot quicker.
And the main reason for choosing Python over other languages that I regularly use? It's fun and I enjoy spending time in it.
A:
I think the flexibility and ease of use (readable code, lots of libraries/packages) are the big draws.
Regarding
enables rapid systems application prototyping using of c++ libraries using swig wrappers
I actually work on a Python product for mathematical and statistical analysis (PyIMSL Studio) designed specifically to address this issue, although we use ctypes instead of swig. For a variety of reasons lots of businesses use C/C++ in their enterprise applications. If they want to add some analytical functionality prototyping it in Python can be a lot faster than in C. Our Python libraries wrap our C numerical libraries 1:1, so once the prototyping is done the production development can take place confident that the same algorithms are available and the same results will be achievable. Bridging that prototype to production gap can be harder when moving from a very domain specific language like R or MATLAB to C than with a very general purpose language like Python.
Regarding
built to a well defined language specification
you should take a look at the public comments for the Security and Exchange Commissions's proposal to make Python be the language used in new assest-backed security regulation. Some people argue that Python should not be the language precisely because it does not have a well defined language specification other than (multiple) reference implementations. I love the language, but I would not view the language specification aspect as a reason why.
Finally, I think there are a lot of Pythonistas who would like to see their organization allow use of Python, or use it to a greater extent. From what I have seen, Python gets sneaked in at first for general, IT-glue kinds of projects, and from there starts being used in myriad other ways.
| 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 systems application prototyping using of c++ libraries using swig wrappers
built to a well defined language specification
innovative features at the syntax level enabling high level of expressiveness
highly flexible web frameworks built long before other languages (django)
The questions is what makes it so popular/highly regarded, but to give some balance I'm going to give some reasons it might not be popular:
less tool support
less enterprise support (ie a vendor helpdesk)
lower performance
BDFL not caring about backward compatibility in version upgrades
Or was it just the best at a particular point in time (about 8 years ago) and other languages and frameworks have since caught up?
| [
"\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.
Now, I am trying to run this program on a web server.
SO I use a HTML Form to submit the file to this script.
In my Python script, I am doing like this:
....
elif req.form.has_key("filename"):
item=req.form["filename"]
if item.file:
req.write("I GO HERE")
myscript.main(item)
....
As you can see here, I am trying to send the file directly to the "main" function.
Is this the right way to do?
I dont get any script error, but the Python script is not producing the expected results.
Any help?
Thanks
A:
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.
For example (untested):
import os
import tempfile
fd, temp_filename = tempfile.mkstemp()
try:
with os.fdopen(fd, "wb") as f:
# Copy file data to temp file
while True:
chunk = item.file.read(100000)
if not chunk: break
f.write(chunk)
# Call script's main() function
myscript.main([temp_filename])
finally:
os.remove(temp_filename)
| 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.
SO I use a HTML Form to submit the file to this script.
In my Python script, I am doing like this:
....
elif req.form.has_key("filename"):
item=req.form["filename"]
if item.file:
req.write("I GO HERE")
myscript.main(item)
....
As you can see here, I am trying to send the file directly to the "main" function.
Is this the right way to do?
I dont get any script error, but the Python script is not producing the expected results.
Any help?
Thanks
| [
"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.