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:
Copying files with unicode names
this was supposed to be a simple script
import shutil
files = os.listdir("C:\\")
for efile in files:
shutil.copy(efile, "D:\\")
It worked fine, until i tried it on a pc with files named with unicode characters!
python just converted these characters into question marks "????" when getting the list from os.listdir, and the copy process raised "file not found" exception!!
A:
You need to use Unicode to access filenames which aren't in the ACP (ANSI codepage) of the Windows system you're running on. To do that, make sure you name directories as Unicode:
import shutil
files = os.listdir(u"C:\\")
for efile in files:
shutil.copy(efile, u"D:\\")
Passing a Unicode string to os.listdir will make it return results as Unicode strings rather than encoding them.
Don't forget that os.listdir won't include path, so you probably actually want something like:
shutil.copy(u"C:\\" + efile, u"D:\\")
See also http://docs.python.org/howto/unicode.html#unicode-filenames.
| Copying files with unicode names | this was supposed to be a simple script
import shutil
files = os.listdir("C:\\")
for efile in files:
shutil.copy(efile, "D:\\")
It worked fine, until i tried it on a pc with files named with unicode characters!
python just converted these characters into question marks "????" when getting the list from os.listdir, and the copy process raised "file not found" exception!!
| [
"You need to use Unicode to access filenames which aren't in the ACP (ANSI codepage) of the Windows system you're running on. To do that, make sure you name directories as Unicode:\nimport shutil\n\nfiles = os.listdir(u\"C:\\\\\")\nfor efile in files:\n shutil.copy(efile, u\"D:\\\\\")\n\nPassing a Unicode strin... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004173477_python.txt |
Q:
wxPython: how to listen to EVT_KEY_DOWN on SearchCtrl?
In my application I want a search box, probably like the one provided by wx.SearchCtrl, with the search button and the cancel button included. I also want to know when the user presses Up or Down, so that I can browse through the search results. When I make a demo with wx.TextCtrl I can bind the event like this
self.textbox = wx.TextCtrl(self)
self.textbox.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.textbox)
But as soon as I change textbox to wx.SearchCtrl I cannot catch the event anymore. Can I make the binding work with wx.SearchCtrl or do I have to implement my textbox so that it looks like one?
If that matters, I'm developing on Ubuntu (Gnome) and the application should work well on both Linux and Windows.
A:
A workaround seems to be using EVT_KEY_UP, i.e
self.textbox.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.textbox)
However, this way the key press is not repeatable (you have to release the key in order for the event to be fired). I'm still looking for better ways.
A:
Use a different event, as per the docs.
self.textbox = wx.SearchCtrl(self, style=wx.TE_PROCESS_ENTER)
self.Bind(wx.EVT_TEXT, self.OnKeyDown, self.textbox)
| wxPython: how to listen to EVT_KEY_DOWN on SearchCtrl? | In my application I want a search box, probably like the one provided by wx.SearchCtrl, with the search button and the cancel button included. I also want to know when the user presses Up or Down, so that I can browse through the search results. When I make a demo with wx.TextCtrl I can bind the event like this
self.textbox = wx.TextCtrl(self)
self.textbox.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.textbox)
But as soon as I change textbox to wx.SearchCtrl I cannot catch the event anymore. Can I make the binding work with wx.SearchCtrl or do I have to implement my textbox so that it looks like one?
If that matters, I'm developing on Ubuntu (Gnome) and the application should work well on both Linux and Windows.
| [
"A workaround seems to be using EVT_KEY_UP, i.e\nself.textbox.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.textbox)\n\nHowever, this way the key press is not repeatable (you have to release the key in order for the event to be fired). I'm still looking for better ways.\n",
"Use a different event, as per the docs.\nself... | [
1,
0
] | [] | [] | [
"python",
"search_box",
"wxpython"
] | stackoverflow_0004156329_python_search_box_wxpython.txt |
Q:
What abut this crazy sequence of loops and ifs? Ideas to improve this code?
This code is currently working, but it looks terrible - and probably can be much improved in terms of performance.
Any Suggestions?
def OnClick():
global Selection, touch, set_elsb, set_vreg, set_els, BAR_Items
A = viz.pick(0, viz.WORLD, all=False)
if touch != A: return
for i in BAR_Items:
if not set_els: break
elif BAR_Items[i] == A or SHAPES[i+"_SHP"] == A:
if i in Selection:
Selection.remove(i)
BAR_Items[i].clearActions()
VFrame.SetStatusText(frame, i + " has been deselected")
viz.director( do_chart )
else:
Selection.append(i)
Thank you very much!
A:
My normal approach to this would be to re-factor some of it out into small methods. This generally makes it more testable and easier to read.
A:
It's a few more lines of code but I think it's clearer.
def OnClick():
if not set_els: return
# swap this with the line above if viz.pick has side effects that should occur
A = viz.pick(0, viz.WORLD, all=False)
if touch != A: return
keys = (key for key in BAR_Items
if BAR_Items[key] == A or SHAPES[key+"_SHP"] == A)
for key in keys:
if key in Selection:
Selection.remove(key)
BAR_Items[key].clearActions()
VFrame.SetStatusText(frame, key + " has been deselected")
viz.director(do_chart)
else:
Selection.append(key)
That entire global statement served no purpose as you weren't assigning to any of them. Calling attributes and setting keys don't require the global keyword.
A:
If set_els is not changed outside during this code execution then:
def OnClick():
global Selection, touch, set_elsb, set_vreg, set_els, BAR_Items
if set_els: return
A = viz.pick(0, viz.WORLD, all=False)
if touch != A: return
for i in BAR_Items:
if not (BAR_Items[i] == A or SHAPES[i+"_SHP"] == A): continue
if i in Selection:
Selection.remove(i)
BAR_Items[i].clearActions()
VFrame.SetStatusText(frame, i + " has been deselected")
viz.director( do_chart )
else:
Selection.append(i)
Anyway, my bad code detector flashes with red light when it sees such a code, especially with such amount of globals.
A:
It is very common to assume that if code is ugly, confusing, or hard to follow, it must therefore be inefficient.
Many people also think that if you want to make code go faster, you have to uglify it.
I've seen way ugly confusing code, some of which ran very fast, and other of which had massive performance problems.
I've also seen clean, clear, beautiful code of which the same could be said.
My experience - speed and beauty are independent.
| What abut this crazy sequence of loops and ifs? Ideas to improve this code? | This code is currently working, but it looks terrible - and probably can be much improved in terms of performance.
Any Suggestions?
def OnClick():
global Selection, touch, set_elsb, set_vreg, set_els, BAR_Items
A = viz.pick(0, viz.WORLD, all=False)
if touch != A: return
for i in BAR_Items:
if not set_els: break
elif BAR_Items[i] == A or SHAPES[i+"_SHP"] == A:
if i in Selection:
Selection.remove(i)
BAR_Items[i].clearActions()
VFrame.SetStatusText(frame, i + " has been deselected")
viz.director( do_chart )
else:
Selection.append(i)
Thank you very much!
| [
"My normal approach to this would be to re-factor some of it out into small methods. This generally makes it more testable and easier to read.\n",
"It's a few more lines of code but I think it's clearer. \ndef OnClick():\n if not set_els: return\n\n # swap this with the line above if viz.pick has side eff... | [
1,
1,
0,
0
] | [] | [] | [
"if_statement",
"loops",
"optimization",
"python"
] | stackoverflow_0004170806_if_statement_loops_optimization_python.txt |
Q:
How to save pictures to document with Python win32com
I am making html to doc converter
from win32com.client import Dispatch
wrd=Dispatch('Word.Application')
doc=wrd.Documents.Open(inputfile)
doc.SaveAs(outputfile, FileFormat=0)
doc.Close
And I wand save picture to document: Prepare->Edit links to file->Save picture to document
What command I need?
http://i.stack.imgur.com/SJOS7.png
A:
I believe you are looking for the AddPicture method in the InlineShapes collection.
FileName
Required String. The path and file name of the picture.
LinkToFile
Optional Object. True to link the picture to the file from which it
was created. False to make the picture
an independent copy of the file. The
default value is False.
**SaveWithDocument**
Optional Object. True to save the linked picture with the document.
The default value is False.
Range
Optional Object. The location where the picture will be placed in
the text. If the range isn't
collapsed, the picture replaces the
range; otherwise, the picture is
inserted. If this argument is omitted,
the picture is placed automatically.
| How to save pictures to document with Python win32com | I am making html to doc converter
from win32com.client import Dispatch
wrd=Dispatch('Word.Application')
doc=wrd.Documents.Open(inputfile)
doc.SaveAs(outputfile, FileFormat=0)
doc.Close
And I wand save picture to document: Prepare->Edit links to file->Save picture to document
What command I need?
http://i.stack.imgur.com/SJOS7.png
| [
"I believe you are looking for the AddPicture method in the InlineShapes collection.\n\nFileName\n\nRequired String. The path and file name of the picture.\nLinkToFile\n\nOptional Object. True to link the picture to the file from which it\n was created. False to make the picture\n an independent copy of the file.... | [
1
] | [] | [] | [
"ms_word",
"python",
"win32com"
] | stackoverflow_0004172337_ms_word_python_win32com.txt |
Q:
python easy_install failed because of wrong setuptools version
I tried to a library via easy_install like following:
$ sudo easy_install bbfreeze
Searching for bbfreeze
Reading http://pypi.python.org/simple/bbfreeze/
Reading http://systemexit.de/bbfreeze/
Best match: bbfreeze 0.97.2
Downloading http://pypi.python.org/packages/source/b/bbfreeze/bbfreeze-0.97.2.zip#md5=16e4981f4d8abaff3053f89be436ac8d
Processing bbfreeze-0.97.2.zip
Running bbfreeze-0.97.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-Ti7cDj/bbfreeze-0.97.2/egg-dist-tmp-PqrogM
The required version of setuptools (>=0.6c11) is not available, and
can't be installed while this script is running. Please install
a more recent version first, using 'easy_install -U setuptools'.
(Currently using setuptools 0.6c9 (/Library/Python/2.6/site-packages/setuptools-0.6c9-py2.6.egg))
So I tried to upgrade setuptools to 0.6c12 but it has been already installed:
$ sudo easy_install -U setuptools
Searching for setuptools
Reading http://pypi.python.org/simple/setuptools/
Reading http://peak.telecommunity.com/snapshots/
Best match: setuptools 0.6c12dev-r85381
Processing setuptools-0.6c12dev_r85381-py2.6.egg
setuptools 0.6c12dev-r85381 is already the active version in easy-install.pth
Installing easy_install script to /usr/local/bin
Installing easy_install-2.6 script to /usr/local/bin
Using /Library/Python/2.6/site-packages/setuptools-0.6c12dev_r85381-py2.6.egg
Processing dependencies for setuptools
Finished processing dependencies for setuptools
Just like this:
$ ls -l /Library/Python/2.6/site-packages/
-rw-r--r-- 1 some staff 333775 11 13 23:59 setuptools-0.6c12dev_r85381-py2.6.egg
-rw-r--r-- 1 root wheel 328075 2 6 2010 setuptools-0.6c9-py2.6.egg
I use Mac OS X 10.6.4. How can I fix this wrong reference of easy_install ?
Thank you.
A:
To use the newer version of setuptools, you need to use the newer version of easy_install installed by it. Note the line:
Installing easy_install script to /usr/local/bin
Try this:
sudo /usr/local/bin/easy_install bbfreeze
| python easy_install failed because of wrong setuptools version | I tried to a library via easy_install like following:
$ sudo easy_install bbfreeze
Searching for bbfreeze
Reading http://pypi.python.org/simple/bbfreeze/
Reading http://systemexit.de/bbfreeze/
Best match: bbfreeze 0.97.2
Downloading http://pypi.python.org/packages/source/b/bbfreeze/bbfreeze-0.97.2.zip#md5=16e4981f4d8abaff3053f89be436ac8d
Processing bbfreeze-0.97.2.zip
Running bbfreeze-0.97.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-Ti7cDj/bbfreeze-0.97.2/egg-dist-tmp-PqrogM
The required version of setuptools (>=0.6c11) is not available, and
can't be installed while this script is running. Please install
a more recent version first, using 'easy_install -U setuptools'.
(Currently using setuptools 0.6c9 (/Library/Python/2.6/site-packages/setuptools-0.6c9-py2.6.egg))
So I tried to upgrade setuptools to 0.6c12 but it has been already installed:
$ sudo easy_install -U setuptools
Searching for setuptools
Reading http://pypi.python.org/simple/setuptools/
Reading http://peak.telecommunity.com/snapshots/
Best match: setuptools 0.6c12dev-r85381
Processing setuptools-0.6c12dev_r85381-py2.6.egg
setuptools 0.6c12dev-r85381 is already the active version in easy-install.pth
Installing easy_install script to /usr/local/bin
Installing easy_install-2.6 script to /usr/local/bin
Using /Library/Python/2.6/site-packages/setuptools-0.6c12dev_r85381-py2.6.egg
Processing dependencies for setuptools
Finished processing dependencies for setuptools
Just like this:
$ ls -l /Library/Python/2.6/site-packages/
-rw-r--r-- 1 some staff 333775 11 13 23:59 setuptools-0.6c12dev_r85381-py2.6.egg
-rw-r--r-- 1 root wheel 328075 2 6 2010 setuptools-0.6c9-py2.6.egg
I use Mac OS X 10.6.4. How can I fix this wrong reference of easy_install ?
Thank you.
| [
"To use the newer version of setuptools, you need to use the newer version of easy_install installed by it. Note the line:\nInstalling easy_install script to /usr/local/bin\n\nTry this:\nsudo /usr/local/bin/easy_install bbfreeze\n\n"
] | [
2
] | [] | [] | [
"easy_install",
"python",
"setuptools"
] | stackoverflow_0004173354_easy_install_python_setuptools.txt |
Q:
Implementing Levenshtein distance in python
I have implemented the algorithm, but now I want to find the edit distance for the string which has the shortest edit distance to the others strings.
Here is the algorithm:
def lev(s1, s2):
return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1)
A:
Your "implementation" has several flaws:
(1) It should start with def lev(a, b):, not def lev(s1, s2):. Please get into the good habits of (a) running your code before asking questions about it (b) quoting the code that you've actually run (by copy/paste, not by (error-prone) re-typing).
(2) It has no termination conditions; for any arguments it will eventually end up trying to evaluate lev("", "") which would loop forever were it not for Python implementation limits: RuntimeError: maximum recursion depth exceeded.
You need to insert two lines:
if not a: return len(b)
if not b: return len(a)
to make it work.
(3) The Levenshtein distance is defined recursively. There is no such thing as "the" (one and only) algorithm. Recursive code is rarely seen outside a classroom and then only in a "strawman" capacity.
(4) Naive implementations take time and memory proportional to len(a) * len(b) ... aren't those strings normally a little bit longer than 4 to 8?
(5) Your extremely naive implementation is worse, because it copies slices of its inputs.
You can find working not-very-naive implementations on the web ... google("levenshtein python") ... look for ones which use O(max(len(a), len(b))) additional memory.
What you asked for ("the edit distance for the string who has the shortest edit distance to the others strings.") Doesn't make sense ... "THE string"??? "It takes two to tango" :-)
What you probably want (finding all pairs of strings in a collection which have the minimal distance), or maybe just that minimal distance, is a simple programming exercise. What have you tried?
By the way, finding those pairs by a simplistic algorithm will take O(N ** 2) executions of lev() where N is the number of strings in the collection ... if this is a real-world application, you should look to use proven code rather than try to write it yourself. If this is homework, you should say so.
A:
is this what you're looking for ??
import itertools
import collections
# My Simple implementation of Levenshtein distance
def levenshtein_distance(string1, string2):
"""
>>> levenshtein_distance('AATZ', 'AAAZ')
1
>>> levenshtein_distance('AATZZZ', 'AAAZ')
3
"""
distance = 0
if len(string1) < len(string2):
string1, string2 = string2, string1
for i, v in itertools.izip_longest(string1, string2, fillvalue='-'):
if i != v:
distance += 1
return distance
# Find the string with the shortest edit distance.
list_of_string = ['AATC', 'TAGCGATC', 'ATCGAT']
strings_distances = collections.defaultdict(int)
for strings in itertools.combinations(list_of_string, 2):
strings_distances[strings[0]] += levenshtein_distance(*strings)
strings_distances[strings[1]] += levenshtein_distance(*strings)
shortest = min(strings_distances.iteritems(), key=lambda x: x[1])
| Implementing Levenshtein distance in python | I have implemented the algorithm, but now I want to find the edit distance for the string which has the shortest edit distance to the others strings.
Here is the algorithm:
def lev(s1, s2):
return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1)
| [
"Your \"implementation\" has several flaws:\n(1) It should start with def lev(a, b):, not def lev(s1, s2):. Please get into the good habits of (a) running your code before asking questions about it (b) quoting the code that you've actually run (by copy/paste, not by (error-prone) re-typing).\n(2) It has no terminat... | [
5,
0
] | [] | [] | [
"levenshtein_distance",
"python"
] | stackoverflow_0004173579_levenshtein_distance_python.txt |
Q:
Accessing a child class from another child class inside parent class
I really didn't know what title I should choose. Anyway, I have code like this (this is fixtures):
from fixture import DataSet
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
parent = cat1
The problem is I can't reference cat1 in cat2 like that:
File "/home/julas/cgp/cgp/datasets/__init__.py", line 11, in cat2
parent = cat1
NameError: name 'cat1' is not defined
How can I do it?
A:
There are two problems here.
First, Python doesn't do nested scoping like that for you. To access CategoryData.cat1, you need to spell it out.
Second, and a bigger issue, is that there's no way to access CategoryData from there: the class hasn't been defined yet, since you're in the middle of defining it. If you do this:
class Object(object):
a = 1
b = Object.a
it'll fail, because the value of Object isn't assigned until the end of the class definition. You can think of it as happening like this:
class _unnamed_class(object):
a = 1
b = Object.a
Object = _unnamed_class
There's no way to reference a from where b is assigned, because the containing class hasn't yet been assigned its name.
In order to assign parent as a class property, you need to assign it after the containing class actually exists:
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
CategoryData.cat2.parent = CategoryData.cat1
A:
You either:
Move it out of the definition:
CategoryData.cat2.parent=CategoryData.cat1
Or, if it's an object attribute (and not a class attribute):
class cat2:
name = 'Category 2'
def __init__(self):
self.parent = cat1
| Accessing a child class from another child class inside parent class | I really didn't know what title I should choose. Anyway, I have code like this (this is fixtures):
from fixture import DataSet
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
parent = cat1
The problem is I can't reference cat1 in cat2 like that:
File "/home/julas/cgp/cgp/datasets/__init__.py", line 11, in cat2
parent = cat1
NameError: name 'cat1' is not defined
How can I do it?
| [
"There are two problems here.\nFirst, Python doesn't do nested scoping like that for you. To access CategoryData.cat1, you need to spell it out.\nSecond, and a bigger issue, is that there's no way to access CategoryData from there: the class hasn't been defined yet, since you're in the middle of defining it. If y... | [
3,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0004173839_pylons_python.txt |
Q:
how to handle '../' in python?
i need to strip ../something/ from a url
eg. strip ../first/ from ../first/bit/of/the/url.html where first can be anything.
what's the best way to achieve this?
thanks :)
A:
You can simply split the path twice at the official path separator (os.sep, and not '/') and take the last bit:
>>> s = "../first/bit/of/the/path.html"
>>> s.split(os.sep, 2)[-1]
'bit/of/the/path.html'
This is also more efficient than splitting the path completely and stringing it back together.
Note that this code does not complain when the path contains fewer than 3+ path elements (for instance, 'file.html' yields 'file.html'). If you want the code to raise an exception if the path is not of the expected form, you can just ask for its third element (which is not present for paths that are too short):
>>> s.split(os.sep, 2)[2]
This can help detect some subtle errors.
A:
EOL has given a nice and clean approach however I could not resist giving a regex alternative to it:)
>>> import re
>>> m=re.search('^(\.{2}\/\w+/)(.*)$','../first/bit/of/the/path.html')
>>> m.group(1)
'../first/'
| how to handle '../' in python? | i need to strip ../something/ from a url
eg. strip ../first/ from ../first/bit/of/the/url.html where first can be anything.
what's the best way to achieve this?
thanks :)
| [
"You can simply split the path twice at the official path separator (os.sep, and not '/') and take the last bit:\n>>> s = \"../first/bit/of/the/path.html\"\n>>> s.split(os.sep, 2)[-1]\n'bit/of/the/path.html'\n\nThis is also more efficient than splitting the path completely and stringing it back together.\nNote that... | [
5,
1
] | [] | [] | [
"path",
"python",
"string",
"url"
] | stackoverflow_0004172856_path_python_string_url.txt |
Q:
Where can I find Python code examples, or tutorials, of social networking style functions/components?
I am looking for tutorials and/or examples of certain components of a social network web app that may include Python code examples of:
user account auto-gen function(database)
friend/follow function (Twitter/Facebook style)
messaging/reply function (Twitter style)
live chat function (Facebook style)
blog function
public forums (like Get Satisfaction or Stack Overflow)
profile page template auto-gen function
I just want to start getting my head around how Python can be used to make these features. I am not looking for a solution like Pinax since it is built upon Django and I will be ultimately using Pylons or just straight up Python.
A:
So you're not interested in a fixed solution but want to program it yourself, do I get that correctly? If not: Go with a fixed solution. This will be a lot of programming effort, and whatever you want to do afterwards, doing it in another framework than you intended will be a much smaller problem.
But if you're actually interested in the programming experience, and you haven't found any tutorials googling for, say "messaging python tutorial", then that's because these are large-scale projects,- if you describe a project of this size, you're so many miles above actual lines of code that the concrete programming language almost doesn't matter (or at least you don't get stuck with the details). So you need to break these things down into smaller components.
For example, the friend/follow function: How to insert stuff into a table with a user id, how to keep a table of follow-relations, how to query for a user all texts from people she's following (of course there's also some infrastructural issues if you hit >100.000 people, but you get the idea ;). Then you can ask yourself, which is the part of this which I don't know how to do in Python? If your problem, on the other hand, is breaking down the problems into these subproblems, you need to start looking for help on that, but that's probably not language specific (so you might just want to start googling for "architecture friend feed" or whatever). Also, you could ask that here (beware, each bullet point makes for a huge question in itself ;). Finally, you could get into the Pinax code (don't know it but I assume it's open source) and see how they're doing it. You could try porting some of their stuff to Pylons, for example, so you don't have to reinvent their wheel, learn how they do it, end up in the framework you wanted and maybe even create something reusable by others.
sorry for tl;dr, that's because I don't have a concrete URL to point you to!
| Where can I find Python code examples, or tutorials, of social networking style functions/components? | I am looking for tutorials and/or examples of certain components of a social network web app that may include Python code examples of:
user account auto-gen function(database)
friend/follow function (Twitter/Facebook style)
messaging/reply function (Twitter style)
live chat function (Facebook style)
blog function
public forums (like Get Satisfaction or Stack Overflow)
profile page template auto-gen function
I just want to start getting my head around how Python can be used to make these features. I am not looking for a solution like Pinax since it is built upon Django and I will be ultimately using Pylons or just straight up Python.
| [
"So you're not interested in a fixed solution but want to program it yourself, do I get that correctly? If not: Go with a fixed solution. This will be a lot of programming effort, and whatever you want to do afterwards, doing it in another framework than you intended will be a much smaller problem.\nBut if you're a... | [
5
] | [] | [] | [
"get_satisfaction",
"pylons",
"python",
"social_networking"
] | stackoverflow_0004173883_get_satisfaction_pylons_python_social_networking.txt |
Q:
A question about Python script!
m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
if '01' in m:
n = m.replace('01','Janauary')
print n
elif '02' in m:
n = m.replace('02','February')
print n
elif '03' in m:
n = m.replace('03','March')
print n
elif '04' in m:
n = m.replace('04','April')
print n
elif '05' in m:
n = m.replace('05','May')
print n
elif '06' in m:
n = m.replace('06','June')
print n
elif '07' in m:
n = m.replace('07','July')
print n
elif '08' in m:
n = m.replace('08','August')
print n
elif '09' in m:
n = m.replace('09','September')
print n
elif '10' in m:
n = m.replace('10','October')
print n
elif '11' in m:
n = m.replace('11','November')
print n
elif '12' in m:
n = m.replace('12','December')
print n
main()
for example, this scrpt can output 01/29/1991 to January/29/1991, but I want it output to January,29,1991 How to do it? how to replace the " / " to " , "?
A:
Please don't do it this way; it's already wrong, and can't be fixed without a lot of work. Use datetime.strptime() to turn it into a datetime, and then datetime.strftime() to output it in the correct format.
A:
Take advantage of the datetime module:
m = raw_input('Please enter a date(format:mm/dd/yyyy)')
# First convert to a datetime object
dt = datetime.strptime(m, '%m/%d/%Y')
# Then print it out how you want it
print dt.strftime('%B,%d,%Y')
A:
Just like you replace all of the other strings - replace('/',',').
A:
You might find a dictionary to be helpful here. It would be "simpler." You could try something as follows.
m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
month_dict = {"01" : "January", "02" : "February", "03" : "March", ...}
# then when printing you could do the following
date_list = m.split("/") # This gives you a list like ["01", "21", "2010"]
print(month_dict[date_list[0]] + "," + date_list[1] + "," + date_list[2]
That will basically get you the same thing in 4 lines of code.
A:
I have just rewrite your code more compact:
m = '01/15/2001'
d = {'01' : 'Jan', '02' : 'Feb'}
for key, value in d.items():
if key in m:
m = m.replace(key, value)
| A question about Python script! | m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
if '01' in m:
n = m.replace('01','Janauary')
print n
elif '02' in m:
n = m.replace('02','February')
print n
elif '03' in m:
n = m.replace('03','March')
print n
elif '04' in m:
n = m.replace('04','April')
print n
elif '05' in m:
n = m.replace('05','May')
print n
elif '06' in m:
n = m.replace('06','June')
print n
elif '07' in m:
n = m.replace('07','July')
print n
elif '08' in m:
n = m.replace('08','August')
print n
elif '09' in m:
n = m.replace('09','September')
print n
elif '10' in m:
n = m.replace('10','October')
print n
elif '11' in m:
n = m.replace('11','November')
print n
elif '12' in m:
n = m.replace('12','December')
print n
main()
for example, this scrpt can output 01/29/1991 to January/29/1991, but I want it output to January,29,1991 How to do it? how to replace the " / " to " , "?
| [
"Please don't do it this way; it's already wrong, and can't be fixed without a lot of work. Use datetime.strptime() to turn it into a datetime, and then datetime.strftime() to output it in the correct format.\n",
"Take advantage of the datetime module:\nm = raw_input('Please enter a date(format:mm/dd/yyyy)')\n\n#... | [
11,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004174228_python.txt |
Q:
How to install python2.5.5 in Ubuntu10.10 with all libs bundled
I want to install python2.5.5 in Ubuntu10.10, since Ubuntu10.10 now just supports python>=2.6, so I download source file from python website and try to install it use
./configure && make && sudo make install, it seems that python2.5.5 has been installed successfully, but when I want to use it, sometimes it says "no module named ...", but it should be bundled, I have used it in my Win7, so I wonder whether I can install all the libs.
A:
Consider using Felix Krull's PPA which has pre-built Python 2.5 packages for Ubuntu.
A:
You probably missing some libraries that are not bundled by default on Ubuntu with Python (I have no idea why they decided to split "core" python this way).
You can try running apt-get build-dep python python-dev and build again (you might need to add other packages as well).
Rule of thumb is that if Python complains about not having sqlite3 module, you need to install libsqlite3-dev, then rebuild.
A:
You can add 10.04 to your apt sources, then you can install in the usual way after an apt-update
A:
Here's the post that might help:
http://www.codigomanso.com/en/2010/05/google-app-engine-en-ubuntu-10-4-lucid-lynx/
Don't know which library you are missing, but you would probably be able to install it with easy_install:
http://pypi.python.org/pypi/setuptools
You would have to set up python2.5 as the default python by putting it in front of python2.6 in the PATH. Note that this has to be on the sudo level, as you would need to sudo easy_install. That is, sudo python should run Python 2.5 before you try to install easy_install. It's a bit messy, but after this you should have all up and running properly.
| How to install python2.5.5 in Ubuntu10.10 with all libs bundled | I want to install python2.5.5 in Ubuntu10.10, since Ubuntu10.10 now just supports python>=2.6, so I download source file from python website and try to install it use
./configure && make && sudo make install, it seems that python2.5.5 has been installed successfully, but when I want to use it, sometimes it says "no module named ...", but it should be bundled, I have used it in my Win7, so I wonder whether I can install all the libs.
| [
"Consider using Felix Krull's PPA which has pre-built Python 2.5 packages for Ubuntu.\n",
"You probably missing some libraries that are not bundled by default on Ubuntu with Python (I have no idea why they decided to split \"core\" python this way).\nYou can try running apt-get build-dep python python-dev and bui... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"ubuntu_10.04"
] | stackoverflow_0004173674_python_ubuntu_10.04.txt |
Q:
String coverage optimization in Python
I have this initial string.
'bananaappleorangestrawberryapplepear'
And also have a tuple with strings:
('apple', 'plepe', 'leoran', 'lemon')
I want a function so that from the initial string and the tuple with strings I obtain this:
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
I know how to do it imperatively by finding the word in the initial string for every word and then loop character by character in all initial string with replaced words.
But it's not very efficient and ugly. I suspect there should be some way of doing this more elegantly, in a functional way, with itertools or something. If you know a Python library that can do this efficiently please let me know.
UPDATE: Justin Peel pointed out a case I didn't describe in my initial question. If a word is 'aaa' and 'aaaaaa' is in the initial string, the output should look like 'xxxxxx'.
A:
import re
words = ('apple', 'plepe', 'leoran', 'lemon')
s = 'bananaappleorangestrawberryapplepear'
x = set()
for w in words:
for m in re.finditer(w, s):
i = m.start()
for j in range(i, i+len(w)):
x.add(j)
result = ''.join(('x' if i in x else s[i]) for i in range(len(s)))
print result
produces:
bananaxxxxxxxxxgestrawberryxxxxxxxar
A:
Here's another answer. There might be a faster way to replace the letters with x's, but I don't think that it is necessary because this is already pretty fast.
import re
def do_xs(s,pats):
pat = re.compile('('+'|'.join(pats)+')')
sout = list(s)
i = 0
match = pat.search(s)
while match:
span = match.span()
sout[span[0]:span[1]] = ['x']*(span[1]-span[0])
i = span[0]+1
match = pat.search(s,i)
return ''.join(sout)
txt = 'bananaappleorangestrawberryapplepear'
pats = ('apple', 'plepe', 'leoran', 'lemon')
print do_xs(txt,pats)
Basically, I create a regex pattern that will match any of the input patterns. Then I just keep restarting the search starting 1 after the starting position of the most recent match. There might be a problem though if you have one of the input patterns is a prefix of another input pattern.
A:
Assuming we're restricted to working without stdlib and other imports:
s1 = 'bananaappleorangestrawberryapplepear'
t = ('apple', 'plepe', 'leoran', 'lemon')
s2 = s1
solution = 'bananaxxxxxxxxxgestrawberryxxxxxxxar'
for word in t:
if word not in s1: continue
index = -1 # Start at -1 so our index search starts at 0
for iteration in range(s1.count(word)):
index = s1.find(word, index+1)
length = len(word)
before = s2[:index]
after = s2[index+length:]
s2 = before + 'x'*length + after
print s2 == solution
A:
>>> string_ = 'bananaappleorangestrawberryapplepear'
>>> words = ('apple', 'plepe', 'leoran', 'lemon')
>>> xes = [(string_.find(w), len(w)) for w in words]
>>> xes
[(6, 5), (29, 5), (9, 6), (-1, 5)]
>>> for index, len_ in xes:
... if index == -1: continue
... string_ = string_.replace(string_[index:index+len_], 'x'*len_)
...
>>> string_
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
>>>
There are surely more effective ways, but the premature optimisation is the root of all evil.
A:
a = ('apple', 'plepe', 'leoran', 'lemon')
b = 'bananaappleorangestrawberryapplepear'
for fruit in a:
if a in b:
b = b.replace(fruit, numberofx's)
The only thing you have to do now his determine how many X's to replace with.
A:
def mask_words(s, words):
mask = [False] * len(s)
for word in words:
pos = 0
while True:
idx = s.find(word, pos)
if idx == -1:
break
length = len(word)
for i in xrange(idx, idx+length):
mask[i] = True
pos = idx+length
# Sanity check:
assert len(mask) == len(s)
result = []
for masked, c in zip(mask, s):
result.append('x' if masked else c)
return "".join(result)
| String coverage optimization in Python | I have this initial string.
'bananaappleorangestrawberryapplepear'
And also have a tuple with strings:
('apple', 'plepe', 'leoran', 'lemon')
I want a function so that from the initial string and the tuple with strings I obtain this:
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
I know how to do it imperatively by finding the word in the initial string for every word and then loop character by character in all initial string with replaced words.
But it's not very efficient and ugly. I suspect there should be some way of doing this more elegantly, in a functional way, with itertools or something. If you know a Python library that can do this efficiently please let me know.
UPDATE: Justin Peel pointed out a case I didn't describe in my initial question. If a word is 'aaa' and 'aaaaaa' is in the initial string, the output should look like 'xxxxxx'.
| [
"import re\n\nwords = ('apple', 'plepe', 'leoran', 'lemon')\ns = 'bananaappleorangestrawberryapplepear'\n\nx = set()\n\nfor w in words:\n for m in re.finditer(w, s):\n i = m.start()\n for j in range(i, i+len(w)):\n x.add(j)\n\nresult = ''.join(('x' if i in x else s[i]) for i in range(len... | [
3,
1,
1,
1,
0,
0
] | [] | [] | [
"functional_programming",
"optimization",
"python",
"python_itertools",
"string"
] | stackoverflow_0004173904_functional_programming_optimization_python_python_itertools_string.txt |
Q:
What does this Gtk error mean and how can I fix it?
**
Gtk:ERROR:/build/buildd/gtk+2.0-2.22.0/gtk/gtktoolbar.c:2248:logical_to_physical: assertion failed: (logical == 0)
Aborted
This is happening when I run code analogous to:
if condition:
self.insert(self.toolbutton, 0)
where self is an instance of a subclass of gtk.Toolbar. The error only occurs when condition is false.
A:
Is there an else, or elif clause, or is it just that single if clause that, when not satisfied, causes it to bomb out?
A:
I discovered the cause of the problem. There was a number of similar statements. The problem was due to hard coding the index. Using this form:
if condition:
self.insert(self.toolbutton, self.insert(self.toolbutton, self._n)
self._n += 1
fixes it. (self._n is originally 0).
| What does this Gtk error mean and how can I fix it? | **
Gtk:ERROR:/build/buildd/gtk+2.0-2.22.0/gtk/gtktoolbar.c:2248:logical_to_physical: assertion failed: (logical == 0)
Aborted
This is happening when I run code analogous to:
if condition:
self.insert(self.toolbutton, 0)
where self is an instance of a subclass of gtk.Toolbar. The error only occurs when condition is false.
| [
"Is there an else, or elif clause, or is it just that single if clause that, when not satisfied, causes it to bomb out?\n",
"I discovered the cause of the problem. There was a number of similar statements. The problem was due to hard coding the index. Using this form:\nif condition:\n self.insert(self.toolbutt... | [
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004175035_gtk_pygtk_python.txt |
Q:
Calculating pi using a series in my book
I'm trying (yet again) to get better at programming, this time in python, and I've hit a roadblock. I've been trying to figure out why this doesn't work for a while now, so if I could have some help that would be really, really great. I have the instructions as a comment, but the series wouldn't copy to text, it's on wikipedia though as http://en.wikipedia.org/wiki/Pi#Estimating_.CF.80
#19. Write a program that approximates the value of pi by summing the terms of this series:
#The program should prompt the user for n, the number of terms to sum
# and then output the sum of the first n terms of this series.
def pi() :
n = 0.0
p = input()
for i in range(-3,p*4,4):
n = n + 4.0 / i - 4.0 / ( i + 2)
print n
When I say 1000000, it gives me 5.80825432026; that value doesn't change much. Anyway, can someone help me please? At this point I have nothing else I can think of.
A:
Wrong starting point. Use sensible variable names (question says n, so use n, not p). Check upper bound ... to get n terms you need to do (n // 2) iterations, you are doing approx n iterations.
>>> def pi(n):
... tot = 0.0
... for i in xrange(1, n * 4, 4):
... tot += 4.0 / i - 4.0 / (i + 2)
... return tot
...
>>> pi(1000)
3.1410926536210386
>>> pi(10000)
3.1415426535898203
>>> pi(100000)
3.141587653589818
>>>
A:
Why does your range start at -3? Your function works fine with range(1,p*4,4) although p is not the number of terms.
A:
Based on the wikipedia page cited, I would go for this implementation:
def pi(p) :
def powers():
while True:
yield 1.0
yield -1.0
return 4.0 * sum(p / i for i, p in zip(range(1,2*p+1,2), powers()))
A:
In general for floating point math it's a good idea to add up the smallest terms first to minimize rounding errors, so I'd recommend this tiny modification of John Machin's answer
>>> def pi(n):
... tot = 0.0
... for i in reversed(xrange(1, n * 4, 4)):
... tot += 4.0 / i - 4.0 / (i + 2)
... return tot
| Calculating pi using a series in my book | I'm trying (yet again) to get better at programming, this time in python, and I've hit a roadblock. I've been trying to figure out why this doesn't work for a while now, so if I could have some help that would be really, really great. I have the instructions as a comment, but the series wouldn't copy to text, it's on wikipedia though as http://en.wikipedia.org/wiki/Pi#Estimating_.CF.80
#19. Write a program that approximates the value of pi by summing the terms of this series:
#The program should prompt the user for n, the number of terms to sum
# and then output the sum of the first n terms of this series.
def pi() :
n = 0.0
p = input()
for i in range(-3,p*4,4):
n = n + 4.0 / i - 4.0 / ( i + 2)
print n
When I say 1000000, it gives me 5.80825432026; that value doesn't change much. Anyway, can someone help me please? At this point I have nothing else I can think of.
| [
"Wrong starting point. Use sensible variable names (question says n, so use n, not p). Check upper bound ... to get n terms you need to do (n // 2) iterations, you are doing approx n iterations.\n>>> def pi(n):\n... tot = 0.0\n... for i in xrange(1, n * 4, 4):\n... tot += 4.0 / i - 4.0 / (i + 2)\n... ... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004175224_python.txt |
Q:
Mixing Python and PHP?
I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re-download the chunks.
I know a decent amount of PHP, but I do not see:
How to mix PHP and Python programmatically
Is it possible to have a webpage in python that can just call the python script? Can one have a GUI page that is like zzz.com/text.py as example
A:
For http requests, you need to set your web server to hand over certain request to PHP and others to Python. From within PHP's scripts, if you need to call some Python executable scripts, use one of PHP's shell functions. e.g. exec()
Yes it is possible. The djangobook is a nice tutorial that covers this in one of the earlier chapters. It shows you how to run python as a cgi or with apache.
On a personal note, if you have time to dig deeper into Python, I'd strongly encourage you to do the whole thing in it, rather than mix things with PHP. My experience tells me that there are probably more cases where a PHP app needs some Python support rather than the reverse.
If the supporting language can do everything that the main language does, what's the point of using the main language?
| Mixing Python and PHP? | I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re-download the chunks.
I know a decent amount of PHP, but I do not see:
How to mix PHP and Python programmatically
Is it possible to have a webpage in python that can just call the python script? Can one have a GUI page that is like zzz.com/text.py as example
| [
"\nFor http requests, you need to set your web server to hand over certain request to PHP and others to Python. From within PHP's scripts, if you need to call some Python executable scripts, use one of PHP's shell functions. e.g. exec()\nYes it is possible. The djangobook is a nice tutorial that covers this in one ... | [
10
] | [] | [] | [
"apache",
"php",
"python"
] | stackoverflow_0004175419_apache_php_python.txt |
Q:
Relative imports in Python
Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.
My directory structure currently looks like this
src/
__init__.py
main.py
components/
__init__.py
expander.py
language_id.py
utilities/
__init__.py
functions.py
I want expander.py and language_id.py to have access to the functions module. I run python main.py which accesses the modules just fine with from components.expander import * and components.language_id import *.
However, the code inside expander and language_id to access the functions module:
from ..utilities.functions import *
I receive this error:
ValueError: Attempted relative import beyond toplevel package
I have gone over it a bunch of times and it seems to follow the documentation. Anyone have any ideas of what's going wrong here?
A:
Nevermind, I solved it:
src/
main.py
mod/
__init__.py
components/
__init__.py
expander.py
language_id.py
utilities/
__init__.py
functions.py
main.py then refers to the subpackages as:
from mod.components.expander import *
from mod.utilities.functions import *
expander.py and language_id.py have access to functions.py with:
from ..utilities.functions import *
But the interesting thing is that I had a text file inside the components directory that expander.py uses. However, at runtime it couldn't locate the file even though it was in the same directory. I moved the text file to the same directory as main.py and it worked. Seems counter-intuitive.
| Relative imports in Python | Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.
My directory structure currently looks like this
src/
__init__.py
main.py
components/
__init__.py
expander.py
language_id.py
utilities/
__init__.py
functions.py
I want expander.py and language_id.py to have access to the functions module. I run python main.py which accesses the modules just fine with from components.expander import * and components.language_id import *.
However, the code inside expander and language_id to access the functions module:
from ..utilities.functions import *
I receive this error:
ValueError: Attempted relative import beyond toplevel package
I have gone over it a bunch of times and it seems to follow the documentation. Anyone have any ideas of what's going wrong here?
| [
"Nevermind, I solved it:\nsrc/\n main.py\n mod/\n __init__.py\n components/\n __init__.py\n expander.py\n language_id.py\n utilities/\n __init__.py\n functions.py\n\nmain.py then refers to the subpackages as:\nfrom mod.components.expa... | [
21
] | [] | [] | [
"python",
"python_packaging"
] | stackoverflow_0004175534_python_python_packaging.txt |
Q:
Errors with python-openid and Google Apps Federated Login
UPDATE
I managed to get it working although I'm not quite sure why ;) It seems like python-openid uses a POST-request to issue the openid mode=associate and for some reason Google doesn't like that. When I patched python-openid to use a GET-request instead everything worked fine. I'll continue my investigation and update this post when I have more information. Below is the diff for my change.
--- python-openid-2.2.1.orig/openid/consumer/consumer.py
+++ python-openid-2.2.1/openid/consumer/consumer.py
@@ -229,6 +229,20 @@
# Process response in separate function that can be shared by async code.
return _httpResponseToMessage(resp, server_url)
+def makeKVGet(request_message, server_url):
+ """Make a Direct Request to an OpenID Provider and return the
+ result as a Message object.
+
+ @raises openid.fetchers.HTTPFetchingError: if an error is
+ encountered in making the HTTP post.
+
+ @rtype: L{openid.message.Message}
+ """
+ # XXX: TESTME
+ resp = fetchers.fetch(request_message.toURL(server_url))
+
+ # Process response in separate function that can be shared by async code.
+ return _httpResponseToMessage(resp, server_url)
def _httpResponseToMessage(response, server_url):
"""Adapt a POST response to a Message.
@@ -682,6 +696,7 @@
return True
_makeKVPost = staticmethod(makeKVPost)
+ _makeKVGet = staticmethod(makeKVGet)
def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
@@ -1258,7 +1273,7 @@
endpoint, assoc_type, session_type)
try:
- response = self._makeKVPost(args, endpoint.server_url)
+ response = self._makeKVGet(args, endpoint.server_url)
except fetchers.HTTPFetchingError, why:
oidutil.log('openid.associate request failed: %s' % (why[0],))
return None
Old question, preserved for context
I've been trying desperately to get the trac-authopenid plugin to work but with no luck.
We use Google Apps Premier at work so I'm trying to get openid auth working with that. I think I've set up all the required stuff (XRDS and such) as far as google is concerned and I've gotten it to work fine with apache2 + mod-auth-openid as well as using it on other sites (SO for example).
But I can't seem to get it to work with trac-authopenid. I get redirected (via a form post, not a redirect as usual) to Google where I get to log in but when I return the plugin simply states that validation failed.
If i turn on debug logging I get this (I've replaced our domain name with example.com)
2010-01-27 12:21:15,811 Trac[authopenid] DEBUG: beginning OpenID authentication.
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
... snipped, repeats until line 9...
2010-01-27 12:21:16,867 Trac[authopenid] DEBUG: openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,869 Trac[authopenid] DEBUG: Generated checkid_setup request to https://www.google.com/a/example.com/o8/ud?be=o8 using stateless mode.
2010-01-27 12:21:18,068 Trac[main] DEBUG: Dispatching <Request "GET u'/openidprocess'">
2010-01-27 12:21:18,075 Trac[session] DEBUG: Retrieving session for ID '25a842642693232301aad341'
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required ty
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Attempting discovery to verify endpoint
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Performing discovery on http://example.com/openid?id=113663311178245814720
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Received id_res response from https://www.google.com/a/example.com/o8/ud?be=o8 using association AOQobUefon
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Using OpenID check_authentication
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: op_endpoint
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: claimed_id
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: identity
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: return_to
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: response_nonce
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: assoc_handle
2010-01-27 12:21:18,576 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
... snipped, repeats until line 9...
2010-01-27 12:21:18,578 Trac[authopenid] DEBUG: check_authentication failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501
I tried writing some code directly against the python-openid library in order to narrow it down a little but I'm clueless. I've been able to reproduce the error with this code snippet:
from openid.store.memstore import MemoryStore
from openid.consumer import consumer
session = { 'id' : 'foobar' }
store = MemoryStore()
consumer = consumer.Consumer(session, store)
consumer.begin('https://www.google.com/accounts/o8/site-xrds?hd=example.com')
Which consistently outputs
kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
... snip ...
openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501
Some version numbers:
Python 2.6.2
trac-authopenid 0.1.6
python-openid 2.2.1
I'm at a complete loss and I could really use some help.
A:
Okay. I don't have an Apps account so I can't test logging in, but I can successfully associate with an apps domain with python-openid 2.2.4. Here's a little debugging tool for making association requests: http://gist.github.com/288560
Your patch should not have fixed things; associate requests are always POSTs. And the Ruby library also always POSTs, so unless rpxnow has made some unusual modifications, rpxnow shouldn't work when python-openid fails here.
I was about to ask you about the openid.store on your install, but if your minimal example with the MemoryStore reproduces it, that's not it.
I guess the only thing left I have for you is to suggest that you ask Google Apps customer support.
A:
You mentioned that you're using Python 2.6.2 with python-openid. The Requirements section of the README file currently only lists Python 2.3, 2.4, or 2.5. It's good to hear you got it working.
| Errors with python-openid and Google Apps Federated Login | UPDATE
I managed to get it working although I'm not quite sure why ;) It seems like python-openid uses a POST-request to issue the openid mode=associate and for some reason Google doesn't like that. When I patched python-openid to use a GET-request instead everything worked fine. I'll continue my investigation and update this post when I have more information. Below is the diff for my change.
--- python-openid-2.2.1.orig/openid/consumer/consumer.py
+++ python-openid-2.2.1/openid/consumer/consumer.py
@@ -229,6 +229,20 @@
# Process response in separate function that can be shared by async code.
return _httpResponseToMessage(resp, server_url)
+def makeKVGet(request_message, server_url):
+ """Make a Direct Request to an OpenID Provider and return the
+ result as a Message object.
+
+ @raises openid.fetchers.HTTPFetchingError: if an error is
+ encountered in making the HTTP post.
+
+ @rtype: L{openid.message.Message}
+ """
+ # XXX: TESTME
+ resp = fetchers.fetch(request_message.toURL(server_url))
+
+ # Process response in separate function that can be shared by async code.
+ return _httpResponseToMessage(resp, server_url)
def _httpResponseToMessage(response, server_url):
"""Adapt a POST response to a Message.
@@ -682,6 +696,7 @@
return True
_makeKVPost = staticmethod(makeKVPost)
+ _makeKVGet = staticmethod(makeKVGet)
def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
@@ -1258,7 +1273,7 @@
endpoint, assoc_type, session_type)
try:
- response = self._makeKVPost(args, endpoint.server_url)
+ response = self._makeKVGet(args, endpoint.server_url)
except fetchers.HTTPFetchingError, why:
oidutil.log('openid.associate request failed: %s' % (why[0],))
return None
Old question, preserved for context
I've been trying desperately to get the trac-authopenid plugin to work but with no luck.
We use Google Apps Premier at work so I'm trying to get openid auth working with that. I think I've set up all the required stuff (XRDS and such) as far as google is concerned and I've gotten it to work fine with apache2 + mod-auth-openid as well as using it on other sites (SO for example).
But I can't seem to get it to work with trac-authopenid. I get redirected (via a form post, not a redirect as usual) to Google where I get to log in but when I return the plugin simply states that validation failed.
If i turn on debug logging I get this (I've replaced our domain name with example.com)
2010-01-27 12:21:15,811 Trac[authopenid] DEBUG: beginning OpenID authentication.
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
... snipped, repeats until line 9...
2010-01-27 12:21:16,867 Trac[authopenid] DEBUG: openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,869 Trac[authopenid] DEBUG: Generated checkid_setup request to https://www.google.com/a/example.com/o8/ud?be=o8 using stateless mode.
2010-01-27 12:21:18,068 Trac[main] DEBUG: Dispatching <Request "GET u'/openidprocess'">
2010-01-27 12:21:18,075 Trac[session] DEBUG: Retrieving session for ID '25a842642693232301aad341'
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required ty
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Attempting discovery to verify endpoint
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Performing discovery on http://example.com/openid?id=113663311178245814720
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Received id_res response from https://www.google.com/a/example.com/o8/ud?be=o8 using association AOQobUefon
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Using OpenID check_authentication
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: op_endpoint
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: claimed_id
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: identity
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: return_to
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: response_nonce
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: assoc_handle
2010-01-27 12:21:18,576 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
... snipped, repeats until line 9...
2010-01-27 12:21:18,578 Trac[authopenid] DEBUG: check_authentication failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501
I tried writing some code directly against the python-openid library in order to narrow it down a little but I'm clueless. I've been able to reproduce the error with this code snippet:
from openid.store.memstore import MemoryStore
from openid.consumer import consumer
session = { 'id' : 'foobar' }
store = MemoryStore()
consumer = consumer.Consumer(session, store)
consumer.begin('https://www.google.com/accounts/o8/site-xrds?hd=example.com')
Which consistently outputs
kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
... snip ...
openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501
Some version numbers:
Python 2.6.2
trac-authopenid 0.1.6
python-openid 2.2.1
I'm at a complete loss and I could really use some help.
| [
"Okay. I don't have an Apps account so I can't test logging in, but I can successfully associate with an apps domain with python-openid 2.2.4. Here's a little debugging tool for making association requests: http://gist.github.com/288560\nYour patch should not have fixed things; associate requests are always POSTs... | [
2,
0
] | [] | [] | [
"google_apps",
"openid",
"python",
"python_openid",
"trac"
] | stackoverflow_0002148267_google_apps_openid_python_python_openid_trac.txt |
Q:
Using arguments in Python functions
I'm aware of mutuable vs immutable arguments in Python, and which is which, but here is a weird issue I ran into with mutable arguments. The simplified version is as follows:
def fun1a(tmp):
tmp.append(3)
tmp.append(2)
tmp.append(1)
return True
def fun1(a):
b = fun1a(a)
print a #prints [3,2,1]
return b
def fun2a():
tmp = []
tmp.append(3)
tmp.append(2)
tmp.append(1)
return [True, tmp]
def fun2(a):
[b, a] = fun2a()
print a #prints [3,2,1]
return b
def main():
a=[]
if fun1(a):
print a #prints [3,2,1]
if fun2(b):
print b #prints garbage, e.g. (0,1)
As you can see the only difference is that fun2 points the passed in argument to reference a list created inside fun2a, while fun1 simply appends to the list created in main. In the end, fun1 returns the correct result, while fun2 returns random garbage rather than the result I'd expect. What's the problem here?
Thanks
A:
This isn't so much of a mutable/immutable issue as one of scope.
"b" exists only in fun1 and fun2 bodies. It is not present in the main or global scope (at least intentionally)
--EDIT--
>>> def fun1(b):
... b = b + 1
... return b
...
>>> def fun2(a):
... b = 1
... return b
...
>>> fun1(5)
6
>>> fun2(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
(From my interpreter in terminal)
I'm guessing your 'b' was initialized somewhere else. What happened in the other function is of has no effect on this.
This is me running your exact code:
>>> main()
[3, 2, 1]
[3, 2, 1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in main
NameError: global name 'b' is not defined
>>> b = 'whatever'
>>> main()
[3, 2, 1]
[3, 2, 1]
[3, 2, 1]
whatever
A:
As others have pointed out, there is no name 'b' in your main() function.
A better way of asserting how your code is behaving is to unit test it. Unit-testing is very easy in Python and a great habit to get into. When I first started writing Python a few years back the guy I paired with insisted on testing everything. Since that day I have continued and have never had to use the Python debugger as a result! I digress...
Consider:
import unittest
class Test(unittest.TestCase):
def test_fun1a_populates_tmp(self):
some_list = []
fun1a(tmp=some_list)
self.assertEquals([3, 2, 1], some_list)
def test_fun1a_returns_true(self):
some_list = []
ret = fun1a(tmp=some_list)
self.assertTrue(ret)
def test_fun1_populates_a(self):
some_list = []
fun1(a=some_list)
self.assertEquals([3, 2, 1], some_list)
def test_fun1_returns_true(self):
some_list = []
ret = fun1(a=some_list)
self.assertTrue(ret)
def test_fun2a_populates_returned_list(self):
ret = fun2a()
self.assertEquals([True, [3, 2, 1]], ret)
def test_fun2_returns_true(self):
some_list = []
ret = fun2(some_list)
self.assertTrue(ret)
def test_fun2_des_not_populate_passed_list(self):
some_list = []
fun2(some_list)
self.assertEqual(0, len(some_list))
if __name__ == '__main__':
unittest.main()
Each of these unit tests pass and document how your functions behave (save for the printing, you can add the tests for those if they are needed). They also provide a harness for when you edit your code, because they should continue to pass or start failing if you break something.
I haven't unit-tested main(), since it is clearly broken.
| Using arguments in Python functions | I'm aware of mutuable vs immutable arguments in Python, and which is which, but here is a weird issue I ran into with mutable arguments. The simplified version is as follows:
def fun1a(tmp):
tmp.append(3)
tmp.append(2)
tmp.append(1)
return True
def fun1(a):
b = fun1a(a)
print a #prints [3,2,1]
return b
def fun2a():
tmp = []
tmp.append(3)
tmp.append(2)
tmp.append(1)
return [True, tmp]
def fun2(a):
[b, a] = fun2a()
print a #prints [3,2,1]
return b
def main():
a=[]
if fun1(a):
print a #prints [3,2,1]
if fun2(b):
print b #prints garbage, e.g. (0,1)
As you can see the only difference is that fun2 points the passed in argument to reference a list created inside fun2a, while fun1 simply appends to the list created in main. In the end, fun1 returns the correct result, while fun2 returns random garbage rather than the result I'd expect. What's the problem here?
Thanks
| [
"This isn't so much of a mutable/immutable issue as one of scope.\n\"b\" exists only in fun1 and fun2 bodies. It is not present in the main or global scope (at least intentionally)\n--EDIT--\n>>> def fun1(b):\n... b = b + 1\n... return b\n... \n>>> def fun2(a):\n... b = 1\n... return b\n... \n>>> f... | [
3,
1
] | [
"The problem may be related to the difference between lists and tuples. In fun2, don't put brackets around a,b.\nIn fun2a, return a tuple of the two objects and not a list. Python should write the varaibles correctly, if that's the problem that you're trying to solve.\nAlso, you called fun2 with argument b when b w... | [
-1
] | [
"python"
] | stackoverflow_0004175585_python.txt |
Q:
python: Is this a wrong way to remove an element from a dict?
I use this way to remove an emelment from a dict:
d["ele"] = data
...
d["ele"] = None
I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.
Is it the right way to do this?
A:
You remove an element from a dictionary using del:
>>> d={}
>>> d['asdf']=3
>>> d['ele']=90
>>> d
{'asdf': 3, 'ele': 90}
>>> d['ele']=None
>>> d
{'asdf': 3, 'ele': None}
>>> del d['ele']
>>> d
{'asdf': 3}
>>>
A:
That does not remove the key, just the value.
del d['ele']
| python: Is this a wrong way to remove an element from a dict? | I use this way to remove an emelment from a dict:
d["ele"] = data
...
d["ele"] = None
I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.
Is it the right way to do this?
| [
"You remove an element from a dictionary using del:\n>>> d={}\n>>> d['asdf']=3\n>>> d['ele']=90\n>>> d\n{'asdf': 3, 'ele': 90}\n>>> d['ele']=None\n>>> d\n{'asdf': 3, 'ele': None}\n>>> del d['ele']\n>>> d\n{'asdf': 3}\n>>> \n\n",
"That does not remove the key, just the value.\ndel d['ele']\n\n"
] | [
11,
3
] | [] | [] | [
"python"
] | stackoverflow_0004175686_python.txt |
Q:
Most efficient way to sort a Django QuerySet based on a form value
Working on a project with another fella. This is some code I wrote in view.py to sort a QuerySet based on some form data:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops
stops = Stops.approved_objects.filter(**query_attributes)
# Do neccessary sorting
if sort_by == SORT_BY_PRICE:
stops = stops.order_by('price')
else: # By default, sort by last visted
stops = stops.order_by('last_visited')
However, last night my colleague modified the code to this:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops based on sort
if sort_by == SORT_BY_PRICE:
stops = Stops.approved_objects.filter(**query_attributes).order_by('price')
else: # By default, sort by last visted
stops = Stops.approved_objects.filter(**query_attributes).order_by('last_visited')
His SVN comment: More efficient.
According to Django's documentation, both will equate to one database query. It is possible that I'm missing something else. Perhaps the fact that I'm setting the stops variable (stops = ...) twice?
Because I cannot get a hold of him till Monday, thought I'll go to the SO community on this one.
A:
Unnecessary optimization. Besides:
# settings.py
SORTS = {SORT_BY_PRICE: 'price'}
DEFAULT_SORT = 'last_visited'
# whatever.py
sort_field = settings.SORTS.get(sort_by, settings.DEFAULT_SORT)
stops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)
That's what you should be doing ;)
A:
Your colleague's solution should only save one STORE_FAST instruction (assuming that this is in a function. If it's global than it's a STORE_GLOBAL) and one LOAD_FAST (or LOAD_GLOBAL instruction).
I'm pretty militant about sweating the microseconds (when I know how to) but not at the cost of readability. Your version is much more readable.
Although, I would do
sort_field = 'price' if sort_by == SORT_BY_PRICE else 'last_visited'
stops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)`
| Most efficient way to sort a Django QuerySet based on a form value | Working on a project with another fella. This is some code I wrote in view.py to sort a QuerySet based on some form data:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops
stops = Stops.approved_objects.filter(**query_attributes)
# Do neccessary sorting
if sort_by == SORT_BY_PRICE:
stops = stops.order_by('price')
else: # By default, sort by last visted
stops = stops.order_by('last_visited')
However, last night my colleague modified the code to this:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops based on sort
if sort_by == SORT_BY_PRICE:
stops = Stops.approved_objects.filter(**query_attributes).order_by('price')
else: # By default, sort by last visted
stops = Stops.approved_objects.filter(**query_attributes).order_by('last_visited')
His SVN comment: More efficient.
According to Django's documentation, both will equate to one database query. It is possible that I'm missing something else. Perhaps the fact that I'm setting the stops variable (stops = ...) twice?
Because I cannot get a hold of him till Monday, thought I'll go to the SO community on this one.
| [
"Unnecessary optimization. Besides:\n# settings.py\nSORTS = {SORT_BY_PRICE: 'price'}\nDEFAULT_SORT = 'last_visited'\n\n# whatever.py\nsort_field = settings.SORTS.get(sort_by, settings.DEFAULT_SORT)\n\nstops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)\n\nThat's what you should be doing ;... | [
1,
1
] | [] | [] | [
"django_queryset",
"python"
] | stackoverflow_0004175643_django_queryset_python.txt |
Q:
Sorting a Django QuerySet by a property (not a field) of the Model
Some code and my goal
My (simplified) model:
class Stop(models.Model):
EXPRESS_STOP = 0
LOCAL_STOP = 1
STOP_TYPES = (
(EXPRESS_STOP, 'Express stop'),
(LOCAL_STOP, 'Local stop'),
)
name = models.CharField(max_length=32)
type = models.PositiveSmallIntegerField(choices=STOP_TYPES)
price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
def _get_cost(self):
if self.price == 0:
return 0
elif self.type == self.EXPRESS_STOP:
return self.price / 2
elif self.type == self.LOCAL_STOP:
return self.price * 2
else:
return self.price
cost = property(_get_cost)
My Goal: I want to sort by the cost property. I tried two approaches.
Using order_by QuerySet API
Stops.objects.order_by('cost')
That yielded the following template error:
Caught FieldError while rendering: Cannot resolve keyword 'cost' into field.
Using dictsort template filter
{% with deal_items|dictsort:"cost_estimate" as items_sorted_by_price %}
Received the following template error:
Caught VariableDoesNotExist while rendering: Failed lookup for key [cost] in u'Union Square'
So...
How should I go about doing this?
A:
Use QuerySet.extra() along with CASE ... END to define a new field, and sort on that.
Stops.objects.extra(select={'cost': 'CASE WHEN price=0 THEN 0 '
'WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN price*2'},
order_by=['cost'])
That, or cast the QuerySet returned from the rest to a list, then use L.sort(key=operator.attrgetter('cost')) on it.
| Sorting a Django QuerySet by a property (not a field) of the Model | Some code and my goal
My (simplified) model:
class Stop(models.Model):
EXPRESS_STOP = 0
LOCAL_STOP = 1
STOP_TYPES = (
(EXPRESS_STOP, 'Express stop'),
(LOCAL_STOP, 'Local stop'),
)
name = models.CharField(max_length=32)
type = models.PositiveSmallIntegerField(choices=STOP_TYPES)
price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
def _get_cost(self):
if self.price == 0:
return 0
elif self.type == self.EXPRESS_STOP:
return self.price / 2
elif self.type == self.LOCAL_STOP:
return self.price * 2
else:
return self.price
cost = property(_get_cost)
My Goal: I want to sort by the cost property. I tried two approaches.
Using order_by QuerySet API
Stops.objects.order_by('cost')
That yielded the following template error:
Caught FieldError while rendering: Cannot resolve keyword 'cost' into field.
Using dictsort template filter
{% with deal_items|dictsort:"cost_estimate" as items_sorted_by_price %}
Received the following template error:
Caught VariableDoesNotExist while rendering: Failed lookup for key [cost] in u'Union Square'
So...
How should I go about doing this?
| [
"Use QuerySet.extra() along with CASE ... END to define a new field, and sort on that.\nStops.objects.extra(select={'cost': 'CASE WHEN price=0 THEN 0 '\n 'WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN price*2'},\n order_by=['cost'])\n\nThat, or cast the QuerySet returned from the rest to a list,... | [
17
] | [] | [] | [
"django_models",
"django_templates",
"python"
] | stackoverflow_0004175749_django_models_django_templates_python.txt |
Q:
How to redirect python runtime errors?
I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.
Is it possible for me to redirect such runtime error to a log file?
A:
It looks like you are asking two questions.
To prevent your process from exiting on errors, you need to catch all exceptions that are raised using try...except...finally.
You also wish to redirect all output to a log. Happily, Python provides a comprehensive logging module for your convenience.
An example, for your delight and delectation:
#!/usr/bin/env python
import logging
logging.basicConfig(filename='warning.log', level=logging.WARNING)
try:
1/0
except ZeroDivisionError, e:
logging.warning('The following error occurred, yet I shall carry on regardless: %s', e)
This graciously emits:
% cat warning.log
WARNING:root:The following error occurred, yet I shall carry on regardless: integer division or modulo by zero
A:
Look at the traceback module. If you catch a RuntimeError, you can write it to the log (look at the logging module for that).
| How to redirect python runtime errors? | I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.
Is it possible for me to redirect such runtime error to a log file?
| [
"It looks like you are asking two questions.\nTo prevent your process from exiting on errors, you need to catch all exceptions that are raised using try...except...finally.\nYou also wish to redirect all output to a log. Happily, Python provides a comprehensive logging module for your convenience.\nAn example, for ... | [
5,
2
] | [] | [] | [
"error_logging",
"python"
] | stackoverflow_0004175697_error_logging_python.txt |
Q:
Outputting Tabs with Django
I'm trying to output lines from a .cpp file to a template in Django. I pass the lines in a tuple called file, and output it one line at a time.
{% for line in file %}
{{line}}<br />
{% endfor %}
Everything is very nicely autoescaped in the line, so that it is displayed correctly (like < and "), except for the \t characters. How can I make it print these so that they show up as tabs?
I tried replacing the tabs with a few escaped space characters, , however, Django escapes the &, and it just shows up on the screen as . I don't really want to turn of auto-escape, because it escapes everything else so nicely.
Is there an easy way for me to get these tab characters to show up correctly in this case?
A:
Use u'\xa0' instead.
u'''def foo():
\xa0\xa0return 42'''
| Outputting Tabs with Django | I'm trying to output lines from a .cpp file to a template in Django. I pass the lines in a tuple called file, and output it one line at a time.
{% for line in file %}
{{line}}<br />
{% endfor %}
Everything is very nicely autoescaped in the line, so that it is displayed correctly (like < and "), except for the \t characters. How can I make it print these so that they show up as tabs?
I tried replacing the tabs with a few escaped space characters, , however, Django escapes the &, and it just shows up on the screen as . I don't really want to turn of auto-escape, because it escapes everything else so nicely.
Is there an easy way for me to get these tab characters to show up correctly in this case?
| [
"Use u'\\xa0' instead.\nu'''def foo():\n\\xa0\\xa0return 42'''\n\n"
] | [
4
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0004176055_django_html_python.txt |
Q:
PyQT4: Drag and drop files into QListWidget
I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script.
I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I was using these to articles for my UI design:
http://tech.xster.net/tips/pyqt-drag-images-into-list-widget-for-thumbnail-list/
http://zetcode.com/tutorials/pyqt4/dragdrop/
I noticed that there are a TON of ways to setup a PyQT4 GUI. Which one works the best?
Oops, here's the source code for the project.
The main script:
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import QListWidget
from layout import Ui_window
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_window()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.listWidget, QtCore.SIGNAL("dropped"), self.picture_dropped)
def picture_dropped(self, l):
for url in l:
if os.path.exists(url):
picture = Image.open(url)
picture.thumbnail((72, 72), Image.ANTIALIAS)
icon = QIcon(QPixmap.fromImage(ImageQt.ImageQt(picture)))
item = QListWidgetItem(os.path.basename(url)[:20] + "...", self.pictureListWidget)
item.setStatusTip(url)
item.setIcon(icon)
class DragDropListWidget(QListWidget):
def __init__(self, type, parent = None):
super(DragDropListWidget, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
l = []
for url in event.mimeData().urls():
l.append(str(url.toLocalFile()))
self.emit(SIGNAL("dropped"), l)
else:
event.ignore()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
And the UI file...
# Form implementation generated from reading ui file 'layout.ui'
#
# Created: Thu Nov 11 00:22:52 2010
# by: PyQt4 UI code generator 4.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_window(object):
def setupUi(self, window):
window.setObjectName(_fromUtf8("window"))
window.resize(543, 402)
window.setAcceptDrops(True)
self.centralwidget = QtGui.QWidget(window)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.listWidget = QtGui.QListWidget(self.centralwidget)
self.listWidget.setProperty(_fromUtf8("cursor"), QtCore.Qt.SizeHorCursor)
self.listWidget.setAcceptDrops(True)
self.listWidget.setObjectName(_fromUtf8("listWidget"))
self.verticalLayout.addWidget(self.listWidget)
window.setCentralWidget(self.centralwidget)
self.retranslateUi(window)
QtCore.QMetaObject.connectSlotsByName(window)
def retranslateUi(self, window):
window.setWindowTitle(QtGui.QApplication.translate("window", "PyNamer OCR", None, QtGui.QApplication.UnicodeUTF8))
Thanks to anybody who can help!
A:
The code you're using as an example seem to work fine and looks quite clean. According to your comment your list widget is not getting initialized; this should be the root cause of your issue. I've simplified your code a bit a tried it on my Ubuntu 10.04LTS and it worked fine. My code is listed below, see if it would for you also. You should be able to drag and drop a file into the list widget; once it's dropped a new item is added showing the image and image's file name.
import sys
import os
from PyQt4 import QtGui, QtCore
class TestListView(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(TestListView, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.ignore()
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.view = TestListView(self)
self.connect(self.view, QtCore.SIGNAL("dropped"), self.pictureDropped)
self.setCentralWidget(self.view)
def pictureDropped(self, l):
for url in l:
if os.path.exists(url):
print(url)
icon = QtGui.QIcon(url)
pixmap = icon.pixmap(72, 72)
icon = QtGui.QIcon(pixmap)
item = QtGui.QListWidgetItem(url, self.view)
item.setIcon(icon)
item.setStatusTip(url)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
hope this helps, regards
| PyQT4: Drag and drop files into QListWidget | I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script.
I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I was using these to articles for my UI design:
http://tech.xster.net/tips/pyqt-drag-images-into-list-widget-for-thumbnail-list/
http://zetcode.com/tutorials/pyqt4/dragdrop/
I noticed that there are a TON of ways to setup a PyQT4 GUI. Which one works the best?
Oops, here's the source code for the project.
The main script:
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import QListWidget
from layout import Ui_window
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_window()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.listWidget, QtCore.SIGNAL("dropped"), self.picture_dropped)
def picture_dropped(self, l):
for url in l:
if os.path.exists(url):
picture = Image.open(url)
picture.thumbnail((72, 72), Image.ANTIALIAS)
icon = QIcon(QPixmap.fromImage(ImageQt.ImageQt(picture)))
item = QListWidgetItem(os.path.basename(url)[:20] + "...", self.pictureListWidget)
item.setStatusTip(url)
item.setIcon(icon)
class DragDropListWidget(QListWidget):
def __init__(self, type, parent = None):
super(DragDropListWidget, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
l = []
for url in event.mimeData().urls():
l.append(str(url.toLocalFile()))
self.emit(SIGNAL("dropped"), l)
else:
event.ignore()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
And the UI file...
# Form implementation generated from reading ui file 'layout.ui'
#
# Created: Thu Nov 11 00:22:52 2010
# by: PyQt4 UI code generator 4.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_window(object):
def setupUi(self, window):
window.setObjectName(_fromUtf8("window"))
window.resize(543, 402)
window.setAcceptDrops(True)
self.centralwidget = QtGui.QWidget(window)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.listWidget = QtGui.QListWidget(self.centralwidget)
self.listWidget.setProperty(_fromUtf8("cursor"), QtCore.Qt.SizeHorCursor)
self.listWidget.setAcceptDrops(True)
self.listWidget.setObjectName(_fromUtf8("listWidget"))
self.verticalLayout.addWidget(self.listWidget)
window.setCentralWidget(self.centralwidget)
self.retranslateUi(window)
QtCore.QMetaObject.connectSlotsByName(window)
def retranslateUi(self, window):
window.setWindowTitle(QtGui.QApplication.translate("window", "PyNamer OCR", None, QtGui.QApplication.UnicodeUTF8))
Thanks to anybody who can help!
| [
"The code you're using as an example seem to work fine and looks quite clean. According to your comment your list widget is not getting initialized; this should be the root cause of your issue. I've simplified your code a bit a tried it on my Ubuntu 10.04LTS and it worked fine. My code is listed below, see if it wo... | [
18
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python"
] | stackoverflow_0004151637_drag_and_drop_pyqt_python.txt |
Q:
Turbogears tutorials , debugging tools
I successfully installed turbogears via virtualenv on ubuntu , loaded it with paster after quickstart. I was looking for a good ide with debugging for turbogears and paster. I need any good suggestion how to continue with , any good tutorials , links etc , ide information would be greatly appreciated.
Thank you for your time.
A:
Pydev - Eclipse can be setup for free and easy debugging
http://pydev.blogspot.com/2006/07/configuring-pydev-to-work-with.html
A:
I would checkout Wing IDE. The personal version runs 35 bucks.
| Turbogears tutorials , debugging tools | I successfully installed turbogears via virtualenv on ubuntu , loaded it with paster after quickstart. I was looking for a good ide with debugging for turbogears and paster. I need any good suggestion how to continue with , any good tutorials , links etc , ide information would be greatly appreciated.
Thank you for your time.
| [
"Pydev - Eclipse can be setup for free and easy debugging\nhttp://pydev.blogspot.com/2006/07/configuring-pydev-to-work-with.html\n",
"I would checkout Wing IDE. The personal version runs 35 bucks.\n"
] | [
3,
1
] | [] | [] | [
"python",
"turbogears"
] | stackoverflow_0004145580_python_turbogears.txt |
Q:
Django - django-reversion - not working in inheritance
I have created a common class with it's admin class which should be inherited by all of my models. My common admin class inherited the VersionAdmin
from reversion.admin import VersionAdmin
class CommonAdmin(VersionAdmin):
pass
The problem is that, the model admins which inherited CommonAdmin is not showing the deleted model entries in "Recover Items". But If I didn't use inheritance, it works fine.
A:
The following didn't run properly. It works fine now.
manage.py createinitialrevisions
| Django - django-reversion - not working in inheritance | I have created a common class with it's admin class which should be inherited by all of my models. My common admin class inherited the VersionAdmin
from reversion.admin import VersionAdmin
class CommonAdmin(VersionAdmin):
pass
The problem is that, the model admins which inherited CommonAdmin is not showing the deleted model entries in "Recover Items". But If I didn't use inheritance, it works fine.
| [
"The following didn't run properly. It works fine now.\nmanage.py createinitialrevisions\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_reversion",
"python"
] | stackoverflow_0004176194_django_django_models_django_reversion_python.txt |
Q:
Google App Engine - Admin Section
I am writing a web application with Google App Engine in Python that enables users to read books. I'd like to enable only administrators to add information about books and the contents of book pages to the website.
When restricting access to certain pages with the app.yaml configuration, such as below, is it necessary that the script associated with the admin pages be different from the script used for pages available to everyone. For instance, is there any problem if the script associated with /admin/.* urls be home.py instead of admin.py?
application: myapp
version: 1
runtime: python
api_version: 1
handlers:
- url: /
script: home.py
- url: /index\.html
script: home.py
- url: /admin/.*
script: admin.py
login: admin
- url: /.*
script: not_found.py
Thank you,
David
A:
You can also use is_current_user_admin inside your request-handling code to check programmatically.
A:
You've essentially got two options... one is what you've already got, which is to keep all the admin pages under /admin and apply blanket security on that path, which is what Adam has done.
The other is to keep the same pages for everyone (say you want to show special functions for the admins, like edit buttons or moderation tools) and like Adam already said, and use the is_current_user_admin() function to determine what to show and do for the admins.
| Google App Engine - Admin Section | I am writing a web application with Google App Engine in Python that enables users to read books. I'd like to enable only administrators to add information about books and the contents of book pages to the website.
When restricting access to certain pages with the app.yaml configuration, such as below, is it necessary that the script associated with the admin pages be different from the script used for pages available to everyone. For instance, is there any problem if the script associated with /admin/.* urls be home.py instead of admin.py?
application: myapp
version: 1
runtime: python
api_version: 1
handlers:
- url: /
script: home.py
- url: /index\.html
script: home.py
- url: /admin/.*
script: admin.py
login: admin
- url: /.*
script: not_found.py
Thank you,
David
| [
"You can also use is_current_user_admin inside your request-handling code to check programmatically. \n",
"You've essentially got two options... one is what you've already got, which is to keep all the admin pages under /admin and apply blanket security on that path, which is what Adam has done. \nThe other is to... | [
5,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004175100_google_app_engine_python.txt |
Q:
Error while executing "paster shell example.ini" in reddit.com
Friends!!! I am frustated since last five days working on implementing
reddit.com on a ubuntu 9.10 machine.
Yes, I know that reddit.com has been tested on ubuntu intrepid. But
now i want to install it on U9.10
I have installed postgresql database, created user copied the files,
and installed all the dependencies.
Everything is installed perfectly as described in the document
http://code.reddit.com/wiki/RedditStartToFinishIntrepid
until the line:
$ paster shell example.ini
this line gives me a error and i couldnt figure out where the problem
lies.
Error:
/home/ubuntu/reddit/r2/r2/lib/utils/utils.py:29: DeprecationWarning:
the sha module is deprecated; use the hashlib module instead
import re, datetime, math, random, string, sha, os
/home/ubuntu/reddit/r2/r2/lib/contrib/memcache.py:50:
DeprecationWarning: the md5 module is deprecated; use hashlib instead
from md5 import md5
Traceback (most recent call last):
File "/usr/local/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster')
()
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 84, in run
invoke(command, command_name, options, args[1:])
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 123, in invoke
exit_code = runner.run(args)
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 218, in run
result = self.command()
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/commands.py", line 341, in command
conf = appconfig(config_name, relative_to=here_dir)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 215, in appconfig
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 278, in _loadconfig
return loader.get_context(object_type, name, global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 409, in get_context
section)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 431, in _context_from_use
object_type, name=use, global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 361, in get_context
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 285, in _loadegg
return loader.get_context(object_type, name, global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 561, in get_context
object_type, name=name)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 587, in find_egg_entry_point
possible.append((entry.load(), protocol, entry.name))
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1913,
in load
entry = __import__(self.module_name, globals(),globals(),
['__name__'])
File "/home/ubuntu/reddit/r2/r2/__init__.py", line 26, in <module>
from r2.config.middleware import make_app
File "/home/ubuntu/reddit/r2/r2/config/middleware.py", line 30, in
<module>
from pylons.error import error_template
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/error.py", line 18, in <module>
from pylons.middleware import media_path
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/middleware.py", line 11, in <module>
from webhelpers.rails.asset_tag import javascript_path
**ImportError: No module named rails.asset_tag**
Kindly guys please help me, take me out of my own frustration.
Thanks in Advance
A:
Newer version of python-webhelpers doesn't have asset_tag.py, you need to install an older version (0.6.4) for Pylons 0.9.6:
wget http://pypi.python.org/packages/source/W/WebHelpers/WebHelpers-0.6.4.tar.gz && tar -xf WebHelpers-0.6.4.tar.gz && cd WebHelpers-0.6.4 && python setup.py build && sudo python setup.py install && cd .. && sudo rm -r WebHelpers-0.6.4*
| Error while executing "paster shell example.ini" in reddit.com | Friends!!! I am frustated since last five days working on implementing
reddit.com on a ubuntu 9.10 machine.
Yes, I know that reddit.com has been tested on ubuntu intrepid. But
now i want to install it on U9.10
I have installed postgresql database, created user copied the files,
and installed all the dependencies.
Everything is installed perfectly as described in the document
http://code.reddit.com/wiki/RedditStartToFinishIntrepid
until the line:
$ paster shell example.ini
this line gives me a error and i couldnt figure out where the problem
lies.
Error:
/home/ubuntu/reddit/r2/r2/lib/utils/utils.py:29: DeprecationWarning:
the sha module is deprecated; use the hashlib module instead
import re, datetime, math, random, string, sha, os
/home/ubuntu/reddit/r2/r2/lib/contrib/memcache.py:50:
DeprecationWarning: the md5 module is deprecated; use hashlib instead
from md5 import md5
Traceback (most recent call last):
File "/usr/local/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster')
()
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 84, in run
invoke(command, command_name, options, args[1:])
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 123, in invoke
exit_code = runner.run(args)
File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3-
py2.6.egg/paste/script/command.py", line 218, in run
result = self.command()
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/commands.py", line 341, in command
conf = appconfig(config_name, relative_to=here_dir)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 215, in appconfig
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 278, in _loadconfig
return loader.get_context(object_type, name, global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 409, in get_context
section)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 431, in _context_from_use
object_type, name=use, global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 361, in get_context
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext
global_conf=global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 285, in _loadegg
return loader.get_context(object_type, name, global_conf)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 561, in get_context
object_type, name=name)
File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3-
py2.6.egg/paste/deploy/loadwsgi.py", line 587, in find_egg_entry_point
possible.append((entry.load(), protocol, entry.name))
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1913,
in load
entry = __import__(self.module_name, globals(),globals(),
['__name__'])
File "/home/ubuntu/reddit/r2/r2/__init__.py", line 26, in <module>
from r2.config.middleware import make_app
File "/home/ubuntu/reddit/r2/r2/config/middleware.py", line 30, in
<module>
from pylons.error import error_template
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/error.py", line 18, in <module>
from pylons.middleware import media_path
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/middleware.py", line 11, in <module>
from webhelpers.rails.asset_tag import javascript_path
**ImportError: No module named rails.asset_tag**
Kindly guys please help me, take me out of my own frustration.
Thanks in Advance
| [
"Newer version of python-webhelpers doesn't have asset_tag.py, you need to install an older version (0.6.4) for Pylons 0.9.6:\nwget http://pypi.python.org/packages/source/W/WebHelpers/WebHelpers-0.6.4.tar.gz && tar -xf WebHelpers-0.6.4.tar.gz && cd WebHelpers-0.6.4 && python setup.py build && sudo python setup.py i... | [
4
] | [] | [] | [
"pylons",
"python",
"reddit",
"web_applications"
] | stackoverflow_0002302470_pylons_python_reddit_web_applications.txt |
Q:
Any push back like function in python?
Sorry guys!!! pardon me. I'm a beginner in Python. I am writing the following code:
for line in file:
if StartingMarker in line:
# Here: I want to push back 'line' back in 'file'
for nextline in file:
if EndingMarker in line:
# Do some Operation
print "Done"
How can I push 'line' back in 'file'?
Thanks in Advance.
A:
Don't push back, yield.
def starttoend(it):
for line in it:
if 'START' in line:
yield line
break
for line in it:
yield line
if 'END' in line:
break
l = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']
i = iter(l)
for line in starttoend(i):
print line
Just use the iterator again if you need more sequences.
A:
There's no iterator that I know of that you can start iterating over and then push an item that's been taken back into the iterator. But what you can do is create a new iterator (with itertools.chain) that iterates over the current item and the remaining items in the original iterator. Something like:
import itertools
with open('some-input-file') as f:
it = iter(f)
for line in it:
if StartingMarker in line:
it2 = itertools.chain(iter([line]), it)
for nextline in it2:
if EndingMarker in nextline:
# Do some Operation
A:
for line in file:
if StartingMarker in line and EndingMarker in line:
# look ma! no need to push back
EDIT:
for line in file:
if StartingMarker in line:
# do some operation
if EndingMarker in line:
# do some other operation
A:
for line in file:
if StartingMarker in line:
if endingmarker in line:
#do operation
else:
for nextline in file:
if EndingMarker in line:
# Do some Operation
print "Done"
| Any push back like function in python? | Sorry guys!!! pardon me. I'm a beginner in Python. I am writing the following code:
for line in file:
if StartingMarker in line:
# Here: I want to push back 'line' back in 'file'
for nextline in file:
if EndingMarker in line:
# Do some Operation
print "Done"
How can I push 'line' back in 'file'?
Thanks in Advance.
| [
"Don't push back, yield.\ndef starttoend(it):\n for line in it:\n if 'START' in line:\n yield line\n break\n for line in it:\n yield line\n if 'END' in line:\n break\n\nl = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']\n\ni = iter(l)\nfor line in starttoend(i):\n print l... | [
5,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004176033_python.txt |
Q:
What is the best way to control Twisted's reactor so that it is nonblocking?
Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted?
A:
Yes. The best practice is that this is a bad idea, and that you never really need to do it. It doesn't work with all reactors, and you certainly can't have two different libraries which want to do this.
Why do you need to maintain your own main loop? Chances are, it's something like "I want to work with PyGame" or "I am writing a GUI program and I want to use GTK's mainloop" or "I'm using Twisted from within Blender and it has its own event-handling". If this is the case, you should ask that specific question, because each one of those has its own answer.
If you absolutely need to do this (and, again: you don't) the way to do it is to call reactor.iterate() periodically. This will be slow, break signal handling, and have wonky semantics with respect to reactor.stop(). It will introduce lots of bugs into your program that wouldn't otherwise be there, and when you need help diagnosing them, if you ask someone on the Twisted dev team, the first thing they will tell you is "stop doing that, you don't need to do it".
| What is the best way to control Twisted's reactor so that it is nonblocking? | Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted?
| [
"Yes. The best practice is that this is a bad idea, and that you never really need to do it. It doesn't work with all reactors, and you certainly can't have two different libraries which want to do this.\nWhy do you need to maintain your own main loop? Chances are, it's something like \"I want to work with PyGam... | [
11
] | [] | [] | [
"nonblocking",
"python",
"twisted"
] | stackoverflow_0004176405_nonblocking_python_twisted.txt |
Q:
Problems outputting an image over http using Python
I'm trying to load an image file from my local disk and output it over http when the script is accessed on my webserver via cgi.
For example I want http://example.com/getimage.py?imageid=foo to return the corresponding image. Just opening the file and printing imgfile.read() after the appropriate content headers, however, causes the image to be scrambled. Clearly the output isn't right, but I have no idea why.
What would be the best way to do this, using the built-in modules of 2.6?
Edit:
The code essentially boils down to:
imgFile=open(fileName,"rb")
print "Content-type: image/jpeg"
print
print imgFile.read()
imgFile.close()
It outputs an image, just one that seems to be random data.
A:
You probably have to open() your image files in binary mode:
imgfile = open("%s.png" % imageid, "rb")
print imgfile.read()
On Windows, you need to explicitly make stdout binary:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
You also might want to use CR+LF pairs between headers (see RFC 2616 section 6):
imgFile = open(fileName, "rb")
sys.stdout.write("Content-type: image/jpeg\r\n")
sys.stdout.write("\r\n")
sys.stdout.write(imgFile.read())
imgFile.close()
A:
Python comes with its own HTTP module, SimpleHTTPServer - why not check out SimpleHTTPServer.py in the /Lib directory of your Python installation, and see how it is done there?
| Problems outputting an image over http using Python | I'm trying to load an image file from my local disk and output it over http when the script is accessed on my webserver via cgi.
For example I want http://example.com/getimage.py?imageid=foo to return the corresponding image. Just opening the file and printing imgfile.read() after the appropriate content headers, however, causes the image to be scrambled. Clearly the output isn't right, but I have no idea why.
What would be the best way to do this, using the built-in modules of 2.6?
Edit:
The code essentially boils down to:
imgFile=open(fileName,"rb")
print "Content-type: image/jpeg"
print
print imgFile.read()
imgFile.close()
It outputs an image, just one that seems to be random data.
| [
"You probably have to open() your image files in binary mode:\nimgfile = open(\"%s.png\" % imageid, \"rb\")\nprint imgfile.read()\n\n\nOn Windows, you need to explicitly make stdout binary:\nimport sys\nif sys.platform == \"win32\":\n import os, msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\nYou... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004176693_python.txt |
Q:
How can I serve unbuffered CGI content from Apache 2?
I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.
Example python CGI:
#!/usr/bin/python
import time
import sys
print "Content-type: text/plain"
print
for i in range(1, 10):
print i
sys.stdout.flush()
time.sleep(1)
print "Done."
Similar example in perl:
#!/usr/bin/perl
print "Content-type: text/plain\n\n";
for ($i = 1; $i <= 10 ; $i++) {
print "$i\n";
sleep(1);
}
print "Done.";
This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts
Any ideas?
A:
Randal Schwartz's article Watching long processes through CGI explains a different (and IMHO, better) way of watching a long running process.
A:
Flushing STDOUT can help. For example, the following Perl program should work as intended:
#!/usr/bin/perl
use strict;
use warnings;
local $| = 1;
print "Content-type: text/plain\n\n";
for ( my $i = 1 ; $i <= 10 ; $i++ ) {
print "$i\n";
sleep(1);
}
print "Done.";
A:
You must put your push script into a special directory wich contain a special .htaccess
with this environnment specs:
Options +ExecCGI
AddHandler cgi-script .cgi .sh .pl .py
SetEnvIfNoCase Content-Type \
"^multipart/form-data;" "MODSEC_NOPOSTBUFFERING=Do not buffer file uploads"
SetEnv no-gzip dont-vary
A:
According to CGI::Push,
Apache web server from version 1.3b2
on does not need server push scripts
installed as NPH scripts: the -nph
parameter to do_push() may be set to a
false value to disable the extra
headers needed by an NPH script.
You just have to find do_push equivalent in python.
Edit: Take a look at CherryPy: Streaming the response body.
When you set the config entry "response.stream" to True (and use "yield") CherryPy manages the conversation between the HTTP server and your code like this:
(source: cherrypy.org)
| How can I serve unbuffered CGI content from Apache 2? | I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.
Example python CGI:
#!/usr/bin/python
import time
import sys
print "Content-type: text/plain"
print
for i in range(1, 10):
print i
sys.stdout.flush()
time.sleep(1)
print "Done."
Similar example in perl:
#!/usr/bin/perl
print "Content-type: text/plain\n\n";
for ($i = 1; $i <= 10 ; $i++) {
print "$i\n";
sleep(1);
}
print "Done.";
This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts
Any ideas?
| [
"Randal Schwartz's article Watching long processes through CGI explains a different (and IMHO, better) way of watching a long running process.\n",
"Flushing STDOUT can help. For example, the following Perl program should work as intended:\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nlocal $| = 1;\n\nprint \"... | [
4,
2,
2,
1
] | [] | [] | [
"apache2",
"cgi",
"perl",
"python"
] | stackoverflow_0001181135_apache2_cgi_perl_python.txt |
Q:
Is there any way to get a better terminal in emacs?
I'm using emacs for python, and I'd like to have a nice useable shell in emacs to run an interpreter alongside my editing.
Is there any better emacs shell package out there? The default shell is awful.
A:
You say "terminal" in the title and "shell" in the question, yet you refer to an interpreter. It's all rather confusing.
If you want a better Python interpreter than the standard (although I'd suggest you explore the features of python-mode first); check out ipython.el which will give you an IPython interface.
If you want a better terminal, try M-x ansi-term, which will give you colors, etc.
If you want a better shell, are you using eshell? You can use your standard shell with M-x shell or M-x ansi-term as above.
A:
That depends on what shell you are using, in GNU Emacs 23 there are at least 3 built in:
shell - ugly, not working tab
eshell - not ugly but tab not working
term - not ugly and seems like ipython works with all goodies in it
So you might want to try the term mode.
A:
Check out Gabriel Elanaro's collection of extensions to emacs for python on github.
A:
In order to avoid future confusion between shell, terms and interpreters in Emacs, it might be worth reading this article first.
| Is there any way to get a better terminal in emacs? | I'm using emacs for python, and I'd like to have a nice useable shell in emacs to run an interpreter alongside my editing.
Is there any better emacs shell package out there? The default shell is awful.
| [
"You say \"terminal\" in the title and \"shell\" in the question, yet you refer to an interpreter. It's all rather confusing.\nIf you want a better Python interpreter than the standard (although I'd suggest you explore the features of python-mode first); check out ipython.el which will give you an IPython interfac... | [
10,
4,
2,
1
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0004174633_emacs_python.txt |
Q:
Is `extend` faster than `+=`?
In python, we can concatenate lists in two ways:
lst.extend(another_lst)
lst += another_lst
I thought extend would be faster than using +=, because it reuses the list instead of creating a new one using the other two.
But when I test it out with timeit, it turns out that += is faster,
>>> timeit('l.extend(x)', 'l = range(10); x = range(10)')
0.16929602623
>>> timeit('l += x', 'l = range(10); x = range(10)')
0.15030503273
>>> timeit('l.extend(x)', 'l = range(500); x = range(100)')
0.805264949799
>>> timeit('l += x', 'l = range(500); x = range(100)')
0.750471830368
Is there something wrong with the code I put in timeit?
A:
EDIT: I've tested the performance and I can't replicate the differences to any significant level.
Here's the bytecode -- thanks to @John Machin for pointing out inconsistencies.
>>> import dis
>>> l = [1,2,3]
>>> m = [4,5,6]
>>> def f1(l, m):
... l.extend(m)
...
>>> def f2(l,m):
... l += m
...
>>> dis.dis(f1)
2 0 LOAD_FAST 0 (l)
3 LOAD_ATTR 0 (extend)
6 LOAD_FAST 1 (m)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>> dis.dis(f2)
2 0 LOAD_FAST 0 (l)
3 LOAD_FAST 1 (m)
6 INPLACE_ADD
7 STORE_FAST 0 (l)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Notice that extend uses a CALL_FUNCTION instead of an INPLACE_ADD. Any trivial performance differences can probably be put down to this.
| Is `extend` faster than `+=`? | In python, we can concatenate lists in two ways:
lst.extend(another_lst)
lst += another_lst
I thought extend would be faster than using +=, because it reuses the list instead of creating a new one using the other two.
But when I test it out with timeit, it turns out that += is faster,
>>> timeit('l.extend(x)', 'l = range(10); x = range(10)')
0.16929602623
>>> timeit('l += x', 'l = range(10); x = range(10)')
0.15030503273
>>> timeit('l.extend(x)', 'l = range(500); x = range(100)')
0.805264949799
>>> timeit('l += x', 'l = range(500); x = range(100)')
0.750471830368
Is there something wrong with the code I put in timeit?
| [
"EDIT: I've tested the performance and I can't replicate the differences to any significant level.\n\nHere's the bytecode -- thanks to @John Machin for pointing out inconsistencies.\n>>> import dis\n>>> l = [1,2,3]\n>>> m = [4,5,6]\n>>> def f1(l, m):\n... l.extend(m)\n...\n>>> def f2(l,m):\n... l += m\n...\... | [
18
] | [] | [] | [
"list",
"performance",
"python"
] | stackoverflow_0004176980_list_performance_python.txt |
Q:
Can Java handle an Expando?
I'll synchronize the data from Google Contacts with a datastore in App Engine... i'm doing this in Python, and the datastore will be read later by a Java GAE instance.
Using Expando felt natural, but i'm not sure if the Java instance is going to be able to read it properly.
If the answer is 'no, Java won't read it', what would be the optimal solution?
A:
Edit: Once an Expando is compiled into a class file Java should be able to handle it... after all every Groovy object is an extension of the regular java Object class.
Check out this tutorial discussing mixing Groovy and Java for the gritty details.
| Can Java handle an Expando? | I'll synchronize the data from Google Contacts with a datastore in App Engine... i'm doing this in Python, and the datastore will be read later by a Java GAE instance.
Using Expando felt natural, but i'm not sure if the Java instance is going to be able to read it properly.
If the answer is 'no, Java won't read it', what would be the optimal solution?
| [
"Edit: Once an Expando is compiled into a class file Java should be able to handle it... after all every Groovy object is an extension of the regular java Object class.\nCheck out this tutorial discussing mixing Groovy and Java for the gritty details.\n"
] | [
1
] | [] | [] | [
"expando",
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0004175539_expando_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Extract audio from a video stream in python
Is there an easy way to do that? I'm tempted to call ffmpeg, but it sounds like a bad idea.
A:
Generally no. But it can be done with GStreamer.
| Extract audio from a video stream in python | Is there an easy way to do that? I'm tempted to call ffmpeg, but it sounds like a bad idea.
| [
"Generally no. But it can be done with GStreamer.\n"
] | [
3
] | [] | [] | [
"audio",
"python",
"video"
] | stackoverflow_0004176937_audio_python_video.txt |
Q:
Is serialization a must in order to transfer data across the wire?
Below is something I read and was wondering if the statement is true.
Serialization is the process of
converting a data structure or object
into a sequence of bits so that it can
be stored in a file or memory buffer,
or transmitted across a network
connection link to be "resurrected"
later in the same or another computer
environment.[1] When the resulting
series of bits is reread according to
the serialization format, it can be
used to create a semantically
identical clone of the original
object. For many complex objects, such
as those that make extensive use of
references, this process is not
straightforward.
A:
Serialization is just a fancy way of describing what you do when you want a certain data structure, class, etc to be transmitted.
For example, say I have a structure:
struct Color
{
int R, G, B;
};
When you transmit this over a network you don't say send Color. You create a line of bits and send it. I could create an unsigned char* and concatenate R, G, and B and then send these. I just did serialization
A:
Serialization of some kind is required, but this can take many forms. It can be something like dotNET serialization, that is handled by the language, or it can be a custom built format. Maybe a series of bytes where each byte represents some "magic value" that only you and your application understand.
For example, in dotNET I can can create a class with a single string property, mark it as serializable and the dotNET framework takes care of most everything else.
I can also build my own custom format where the first 4 bytes represent the length of the data being sent and all subsequent bytes are characters in a string. But then of course you need to worry about byte ordering, unicode vs ansi encoding, etc etc.
Typically it is easier to make use of whatever framework your language/OS/dev framework uses, but it is not required.
A:
Yes, serialization is the only way to transmit data over the wire. Consider what the purpose of serialization is. You define the way that the class is stored. In memory tho, you have no way to know exactly where each portion of the class is. Especially if you have, for instance, a list, if it's been allocated early but then reallocated, it's likely to be fragmented all over the place, so it's not one contiguous block of memory. How do you send that fragmented class over the line?
For that matter, if you send a List<ComplexType> over the wire, how does it know where each ComplexType begins and ends.
A:
The real problem here is not getting over the wire, the problem is ending up with the same semantic object on the other side of the wire. For properly transporting data between dissimilar systems -- whether via TCP/IP, floppy, or punch card -- the data must be encoded (serialized) into a platform independent representation.
Because of alignment and type-size issues, if you attempted to do a straight binary transfer of your object it would cause Undefined Behavior (to borrow the definition from the C/C++ standards).
For example the size and alignment of the long datatype can differ between architectures, platforms, languages, and even different builds of the same compiler.
A:
Is serialization a must in order to transfer data across the wire?
Literally no.
It is conceivable that you can move data from one address space to another without serializing it. For example, a hypothetical system using distributed virtual memory could move data / objects from one machine to another by sending pages ... without any specific serialization step.
And within a machine, the objects could be transferred by switch pages from one virtual address space to another.
But in practice, the answer is yes. I'm not aware of any mainstream technology that works that way.
A:
For anything more complex than a primitive or a homogeneous run of primitives, yes.
A:
Binary serialization is not the only option. You can also serialize an object as an XML file, for example. Or as a JSON.
A:
I think you're asking the wrong question. Serialization is a concept in computer programming and there are certain requirements which must be satisfied for something to be considered a serialization mechanism.
Any means of preparing data such that it can be transmitted or stored in such a way that another program (including but not limited to another instance of the same program on another system or at another time) can read the data and re-instantiate whatever objects the data represents.
Note I slipped the term "objects" in there. If I write a program that stores a bunch of text in a file; and I later use some other program, or some instance of that first program to read that data ... I haven't really used a "serialization" mechanism. If I write it in such a way that the text is also stored with some state about how it was being manipulated ... that might entail serialization.
The term is used mostly to convey the concept that active combinations of behavior and state are being rendered into a form which can be read by another program/instance and instantiated. Most serialization mechanism are bound to a particular programming language, or virtual machine system (in the sense of a Java VM, a C# VM etc; not in the sense of "VMware" virtual machines). JSON (and YAML) are a notable exception to this. They represents data for which there are reasonably close object classes with reasonably similar semantics such that they can be instantiated in multiple different programming languages in a meaningful way.
It's not that all data transmission or storage entails "serialization" ... is that certain ways of storing and transmitting data can be used for serialization. At very list it must be possible to disambiguated among the types of data that the programming language supports. If it reads: 1 is has to know whether that's text or an integer or a real (equivalent to 1.0) or a bit.
A:
Strictly speaking it isn't the only option; you could put an argument that "remoting" meets the meaning inthe text; here a fake object is created at the receiver that contains no state. All calls (methods, properties etc) are intercepted and only the call and result are transferred. This avoids the need to transfer the object itself, but can get very expensive if overly "chatty" usage is involved (I.e. Lots of calls)as each has the latency of the speed of light (which adds up).
However, "remoting" is now rather out of fashion. Most often, yes: the object will need to be serialised and deserialized in some way (there are lots of options here). The paragraph is then pretty-much correct.
A:
Having a messages as objects and serializing into bytes is a better way of understanding and managing what is transmitted over wire. In the old days protocols and data was much simpler, often, programmers just put bytes into output stream. Common understanding was shared by having well-known and simple specifications.
A:
I would say serialization is needed to store the objects in file for persistence, but dynamically allocated pointers in objects need to be build again when we de-serialize, But the serialization for transfer depends on the physical protocol and the mechanism used, for example if i use UART to transfer data then its serialized bit by bit but if i use parallel port then 8 bits together gets transferred , which is not serialized
| Is serialization a must in order to transfer data across the wire? | Below is something I read and was wondering if the statement is true.
Serialization is the process of
converting a data structure or object
into a sequence of bits so that it can
be stored in a file or memory buffer,
or transmitted across a network
connection link to be "resurrected"
later in the same or another computer
environment.[1] When the resulting
series of bits is reread according to
the serialization format, it can be
used to create a semantically
identical clone of the original
object. For many complex objects, such
as those that make extensive use of
references, this process is not
straightforward.
| [
"Serialization is just a fancy way of describing what you do when you want a certain data structure, class, etc to be transmitted.\nFor example, say I have a structure:\nstruct Color\n{\n int R, G, B;\n};\n\nWhen you transmit this over a network you don't say send Color. You create a line of bits and send it. I ... | [
8,
4,
3,
3,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"c",
"c#",
"java",
"python"
] | stackoverflow_0004176087_c_c#_java_python.txt |
Q:
Any downside to overriding ConfigParser get() method to include an eval?
I'm creating a subclass of ConfigParser that is easier for me to use throughout my project:
class MyConfiguration(ConfigParser.ConfigParser):
def __init__(self, filename):
ConfigParser.ConfigParser.__init__(self)
self.readfp(open(filename))
def get(self, section, option):
return eval(ConfigParser.ConfigParser.get(self, section, option))
Question: are there any downsides (security, unintended consequences) to overriding the get() method with one that includes eval?
I'd rather bake the eval into the MyConfiguration class because I want to use Python data types (tuples, etc.) in my config files but I don't want to deal with evals all over my project code.
A:
I am not sure if it is a good idea to eval an arbitary text that may be contained in the config file. A normal call to eval is usually considered unsafe.
See:
Security of Python's eval() on untrusted strings?
Use of eval in Python?
If you want to use python data types, then it is much better to store it as a python module and import it. This might be a better solution in this case.
You can split up the config file as those containing python data types in a python module and keeping the rest as config file that can be parsed by configparser.
A:
If your only interest in eval is literal values as you seem to indicate, then you can use ast.literal_eval
This will read tuple literals, list literals and others and is safe to use because it is selective about what it will accept.
>>> import ast
>>> a = ast.literal_eval('(1, 2, 3)')
>>> a
(1, 2, 3)
>>> b = ast.literal_eval('__import__("evil")')
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
Use cases like this are exactly what this function is intended for.
| Any downside to overriding ConfigParser get() method to include an eval? | I'm creating a subclass of ConfigParser that is easier for me to use throughout my project:
class MyConfiguration(ConfigParser.ConfigParser):
def __init__(self, filename):
ConfigParser.ConfigParser.__init__(self)
self.readfp(open(filename))
def get(self, section, option):
return eval(ConfigParser.ConfigParser.get(self, section, option))
Question: are there any downsides (security, unintended consequences) to overriding the get() method with one that includes eval?
I'd rather bake the eval into the MyConfiguration class because I want to use Python data types (tuples, etc.) in my config files but I don't want to deal with evals all over my project code.
| [
"I am not sure if it is a good idea to eval an arbitary text that may be contained in the config file. A normal call to eval is usually considered unsafe.\nSee:\n\nSecurity of Python's eval() on untrusted strings?\nUse of eval in Python?\n\nIf you want to use python data types, then it is much better to store it as... | [
1,
1
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0004177734_configparser_python.txt |
Q:
Calling an inherited property in python
Possible Duplicate:
Polymorphism in Python
Hi
I'm trying to call a property in a class, that is inherited from my baseclass, but it doesn't work. I guess I'm missing something, but what?
Here is my code:
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.__produktId = pID #atributt for produkt nummer
self.__produktNavn = pProdNavn #atributt for produkt navn
self.__produktNetto = pNetto #egenskap for nettopris
def getName(self): #Metode for å finne produktnavnet
return self.__produktNavn
class Bok(Produkt):
def __init__(self,pID,pProdNavn,pNetto,pForfatter):
Produkt.__init__(self,pID,pProdNavn,pNetto)
self.__produktForfatter = pForfatter #atributtp for forfatter
def getNet(self):
return self.__produktNetto
as you see I'm trying to call the _productNetto property that is inherited from my Produkt class.
What am I doing wrong?
/Andy
A:
It works fine if you don't use double underscore in attribute names
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.produktId = pID
self.produktNavn = pProdNavn
self.produktNetto = pNetto
def getName(self):
return self.__produktNavn
class Bok(Produkt):
def __init__(self,pID,pProdNavn,pNetto,pForfatter):
Produkt.__init__(self,pID,pProdNavn,pNetto)
self.produktForfatter = pForfatter
def getNet(self):
return self.produktNetto
x = Bok(1, 2, 3, 4)
print x.getNet()
output:
3
Otherwise the names get mangled and it is looking for attribute _Bok__produktNetto. See: http://docs.python.org/reference/expressions.html#atom-identifiers
AttributeError: Bok instance has no attribute '_Bok__produktNetto'
A:
The problem is that you named those members with two leading underscores, which makes them invisible under those names outside that class (see http://docs.python.org/tutorial/classes.html).
If you rename those fields with a single underscore in both places, it will work as you intend.
| Calling an inherited property in python |
Possible Duplicate:
Polymorphism in Python
Hi
I'm trying to call a property in a class, that is inherited from my baseclass, but it doesn't work. I guess I'm missing something, but what?
Here is my code:
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.__produktId = pID #atributt for produkt nummer
self.__produktNavn = pProdNavn #atributt for produkt navn
self.__produktNetto = pNetto #egenskap for nettopris
def getName(self): #Metode for å finne produktnavnet
return self.__produktNavn
class Bok(Produkt):
def __init__(self,pID,pProdNavn,pNetto,pForfatter):
Produkt.__init__(self,pID,pProdNavn,pNetto)
self.__produktForfatter = pForfatter #atributtp for forfatter
def getNet(self):
return self.__produktNetto
as you see I'm trying to call the _productNetto property that is inherited from my Produkt class.
What am I doing wrong?
/Andy
| [
"It works fine if you don't use double underscore in attribute names\nclass Produkt:\n def __init__(self,pID,pProdNavn,pNetto):\n self.produktId = pID \n self.produktNavn = pProdNavn\n self.produktNetto = pNetto \n\n def getName(self): \n return self.__produktNavn\n\nclass Bok(Produkt):\n de... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0004177794_python.txt |
Q:
Using NLTK with Google App Engine
Is anyone using NLTK with GAE? From this thread it appears that GAE does not support NLTK (Special installation tricks needed.) Do you know any other lightweight similar Python module? Thanks.
A:
GAE supports pretty much any "pure" Python modules which don't try to access files or sockets or other system level utilities. The poster from your link was mostly just trying to minimize the number of modules they included. They expressed a trial and error approach to figuring out which NLTK modules would be needed for their application. A slightly faster approach would be to download the whole NLTK package and move in all the ".py" files rather than just one at a time. There's no big downside to including modules you won't be using.
However this process is something of a fact of life with GAE. Any modules that aren't directly included in the GAE libraries need to be installed manually, and they need to be checked for any deviations from the GAE sandbox restrictions. See this.
A quick glance at the NLTK source code suggests that modules that depend on "mallet" in particular might be problematic, since this is compiled java code.
| Using NLTK with Google App Engine | Is anyone using NLTK with GAE? From this thread it appears that GAE does not support NLTK (Special installation tricks needed.) Do you know any other lightweight similar Python module? Thanks.
| [
"GAE supports pretty much any \"pure\" Python modules which don't try to access files or sockets or other system level utilities. The poster from your link was mostly just trying to minimize the number of modules they included. They expressed a trial and error approach to figuring out which NLTK modules would be ne... | [
3
] | [] | [] | [
"google_app_engine",
"nltk",
"python"
] | stackoverflow_0004176350_google_app_engine_nltk_python.txt |
Q:
Combined Event Handling of widgets in TKinter
I am making a GUI Program in Tkinter and am running into problems.What I want to do is draw 2 checkboxes and a button. According to the user input next steps should take place. A part of my code has been shown below :-
CheckVar1 = IntVar()
CheckVar2 = IntVar()
self.C1 = Checkbutton(root, text = "C Classifier", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5,width = 20).grid(row=4)
self.C2 = Checkbutton(root, text = "GClassifier", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20).grid(row=5)
self.proceed1 = Button(root,text = "\n Proceed",command = self.proceed(CheckVar1.get(),CheckVar2.get())).grid(row=6)
# where proceed prints the combined values of 2 checkboxes
The error that I am getting is typical ie a default value of both the selected checkboxes gets printed up and then there is no further input. The error that I get is NullType Object is not callable.
I searched on the net and I think the answer is related to lambda events or curry.
Please help ..
A:
You're passing the value of self.proceed(CheckVar1.get(),CheckVar2.get()) to the Button constructor, but presumably what you want is for command to be set to a function which will call self.proceed(CheckVar1.get(),CheckVar2.get()) and return a new, possibly different value every time the button is pressed. You can fix that with a lambda, or by wrapping the call in a short callback function. For example, replace the last line with:
def callback():
return self.proceed(CheckVar1.get(), CheckVar2.get())
self.proceed1 = Button(root, text="\n Proceed", command=callback).grid(row=6)
This is pretty typical Tkinter. Remember: when you see a variable called command in Tkinter, it's looking for a function, not a value.
EDIT: to be clear: you're getting 'NullType Object is not callable' because you've set command to equal the return value of a single call to self.proceed (that's the NullType Object). self.proceed is a function, but its return value is not. What you need is to set command to be a function which calls self.proceed.
A:
Like Peter Milley said, the command option needs a reference to a function (ie: give it a function name (ie: no parenthesis). Don't try to "inline" something, create a special function. Your code will be easier to understand and to maintain.
| Combined Event Handling of widgets in TKinter | I am making a GUI Program in Tkinter and am running into problems.What I want to do is draw 2 checkboxes and a button. According to the user input next steps should take place. A part of my code has been shown below :-
CheckVar1 = IntVar()
CheckVar2 = IntVar()
self.C1 = Checkbutton(root, text = "C Classifier", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5,width = 20).grid(row=4)
self.C2 = Checkbutton(root, text = "GClassifier", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20).grid(row=5)
self.proceed1 = Button(root,text = "\n Proceed",command = self.proceed(CheckVar1.get(),CheckVar2.get())).grid(row=6)
# where proceed prints the combined values of 2 checkboxes
The error that I am getting is typical ie a default value of both the selected checkboxes gets printed up and then there is no further input. The error that I get is NullType Object is not callable.
I searched on the net and I think the answer is related to lambda events or curry.
Please help ..
| [
"You're passing the value of self.proceed(CheckVar1.get(),CheckVar2.get()) to the Button constructor, but presumably what you want is for command to be set to a function which will call self.proceed(CheckVar1.get(),CheckVar2.get()) and return a new, possibly different value every time the button is pressed. You ca... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004174768_python_tkinter.txt |
Q:
I'm not being able to access some GData Contacts properties, such as gender
Here's the code:
def fetch_feed(self):
client = gdata.contacts.service.ContactsService()
client.ClientLogin(username, password) #Will change to AuthSub later.
query = gdata.contacts.service.ContactsQuery()
query.max_results = 3000
feed = client.GetContactsFeed(query.ToUri())
memcache.set('feed',feed, 3600)
return feed
feed = self.fetch_feed()
self.PrintFeed(feed)
def PrintFeed(self, feed):
for entry in feed.entry:
print entry.* #example... i can access properties such as entry.title, entry.id, entry.updated, but can't access a whole lot more.
What am i doing wrong, or what am i not doing at all?
I posted the same question on the Apps API forum, just to clarify things.
EDIT
Here's what i'm importing:
from google.appengine.api import memcache, users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
import atom
import atom.url
import datetime
import gdata.alt.appengine
import gdata.contacts
import gdata.contacts.client
import gdata.contacts.data
import gdata.contacts.service
import gdata.client
import gdata.service
import settings
EDIT2:
The error i got after fixing the qry typo:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "C:\etrebug\main.py", line 55, in get
feed = self.fetch_feed()
File "C:\etrebug\main.py", line 67, in fetch_feed
feed = client.get_contacts(qry)
File "C:\etrebug\gdata\contacts\client.py", line 194, in get_contacts
desired_class=desired_class, **kwargs)
File "C:\etrebug\gdata\client.py", line 635, in get_feed
**kwargs)
File "C:\etrebug\gdata\client.py", line 276, in request
version=get_xml_version(self.api_version))
File "C:\etrebug\atom\core.py", line 516, in parse
return _xml_element_from_tree(tree, target_class, version)
File "C:\etrebug\atom\core.py", line 525, in _xml_element_from_tree
if target_class._qname is None:
AttributeError: 'ContactsQuery' object has no attribute '_qname'
A:
You can try the V3 client
client = gdata.contacts.client.ContactsClient()
client.client_login(usr, passwd, "myscript")
qry = gdata.contacts.client.ContactsQuery(max_results=3000)
feed = client.get_contacts(query=qry)
for entry in feed.entry:
# do something with entry
| I'm not being able to access some GData Contacts properties, such as gender | Here's the code:
def fetch_feed(self):
client = gdata.contacts.service.ContactsService()
client.ClientLogin(username, password) #Will change to AuthSub later.
query = gdata.contacts.service.ContactsQuery()
query.max_results = 3000
feed = client.GetContactsFeed(query.ToUri())
memcache.set('feed',feed, 3600)
return feed
feed = self.fetch_feed()
self.PrintFeed(feed)
def PrintFeed(self, feed):
for entry in feed.entry:
print entry.* #example... i can access properties such as entry.title, entry.id, entry.updated, but can't access a whole lot more.
What am i doing wrong, or what am i not doing at all?
I posted the same question on the Apps API forum, just to clarify things.
EDIT
Here's what i'm importing:
from google.appengine.api import memcache, users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
import atom
import atom.url
import datetime
import gdata.alt.appengine
import gdata.contacts
import gdata.contacts.client
import gdata.contacts.data
import gdata.contacts.service
import gdata.client
import gdata.service
import settings
EDIT2:
The error i got after fixing the qry typo:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "C:\etrebug\main.py", line 55, in get
feed = self.fetch_feed()
File "C:\etrebug\main.py", line 67, in fetch_feed
feed = client.get_contacts(qry)
File "C:\etrebug\gdata\contacts\client.py", line 194, in get_contacts
desired_class=desired_class, **kwargs)
File "C:\etrebug\gdata\client.py", line 635, in get_feed
**kwargs)
File "C:\etrebug\gdata\client.py", line 276, in request
version=get_xml_version(self.api_version))
File "C:\etrebug\atom\core.py", line 516, in parse
return _xml_element_from_tree(tree, target_class, version)
File "C:\etrebug\atom\core.py", line 525, in _xml_element_from_tree
if target_class._qname is None:
AttributeError: 'ContactsQuery' object has no attribute '_qname'
| [
"You can try the V3 client\nclient = gdata.contacts.client.ContactsClient()\nclient.client_login(usr, passwd, \"myscript\")\nqry = gdata.contacts.client.ContactsQuery(max_results=3000)\nfeed = client.get_contacts(query=qry)\n\nfor entry in feed.entry:\n # do something with entry\n\n"
] | [
6
] | [] | [] | [
"gdata_api",
"google_app_engine",
"google_contacts_api",
"python"
] | stackoverflow_0004177339_gdata_api_google_app_engine_google_contacts_api_python.txt |
Q:
alternative for pyhook in linux?
i want to know whether there exists an alternative for pyhook(available for windows not on linux) for linux to hook messages.
A:
Haven't needed but I have seen
http://sourceforge.net/projects/pykeylogger/
| alternative for pyhook in linux? | i want to know whether there exists an alternative for pyhook(available for windows not on linux) for linux to hook messages.
| [
"Haven't needed but I have seen\nhttp://sourceforge.net/projects/pykeylogger/\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004178191_python.txt |
Q:
How do I use SSH proxy in mechanize module in python? (Is is possible to do so?)
I couldn't find useful info on SSH proxy setting in mechanize, so I wonder if I can just set the proxy like this:
br = mechanize.Browser()
br.set_proxies{“SSH": "11.11.11.11:22"}
Anybody knows? If this won't work, how do I make SSH proxy work with mechanize Browser?
Thanks
A:
Hope I understood what you want here:
You can set up a proxy on machine B (http://sourceforge.net/projects/tinyproxy/ is tiny) and then do SSH forwarding.
From machine A:
ssh -aNL 7777:localhost:8888 B
would establish a proxy on port 7777 on machine A that connects to port 8888 on machine B. If machine B has tinyproxy running on 8888, then you should be all set.
| How do I use SSH proxy in mechanize module in python? (Is is possible to do so?) | I couldn't find useful info on SSH proxy setting in mechanize, so I wonder if I can just set the proxy like this:
br = mechanize.Browser()
br.set_proxies{“SSH": "11.11.11.11:22"}
Anybody knows? If this won't work, how do I make SSH proxy work with mechanize Browser?
Thanks
| [
"Hope I understood what you want here:\nYou can set up a proxy on machine B (http://sourceforge.net/projects/tinyproxy/ is tiny) and then do SSH forwarding. \nFrom machine A:\nssh -aNL 7777:localhost:8888 B\n\nwould establish a proxy on port 7777 on machine A that connects to port 8888 on machine B. If machine B ha... | [
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004178262_mechanize_python.txt |
Q:
Datetime and utctimetuple()
In this code mDATE0 for 3 items a, b, z is:
mUNIQUE: z | mDATE0: 2010-11-14 14:55:04.293000
mUNIQUE: b | mDATE0: 2010-11-14 14:53:34.824000
mUNIQUE: a | mDATE0: 2010-11-14 14:50:14.155000
But when I do
...
utc_tuple = rep.mDATE0.utctimetuple()
...
corresponding utc_tuples are:
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
In other words min=55 for all items while mDATE0 has
z --> min=55;
b --> min=53;
a --> min=50
What am I doing wrong? Please see my related question. Thanks.
A:
That isn't code! Please post short, complete example code to illustrate a problem. Below is what I think you are trying to do, but without seeing your code, there is no way for anyone to point your bug.
from datetime import datetime
# build up some datetime objects.
z = datetime.strptime('2010-11-14 14:55:04.293000','%Y-%m-%d %H:%M:%S.%f')
b = datetime.strptime('2010-11-14 14:53:34.824000','%Y-%m-%d %H:%M:%S.%f')
a = datetime.strptime('2010-11-14 14:50:14.155000','%Y-%m-%d %H:%M:%S.%f')
# display them
print 'z =',z
print 'b =',b
print 'a =',a
# print the minute
print 'z min =',z.utctimetuple().tm_min
print 'b min =',b.utctimetuple().tm_min
print 'a min =',a.utctimetuple().tm_min
# print the minute an easier way
print 'z min =',z.minute
print 'b min =',b.minute
print 'a min =',a.minute
Output:
z = 2010-11-14 14:55:04.293000
b = 2010-11-14 14:53:34.824000
a = 2010-11-14 14:50:14.155000
z min = 55
b min = 53
a min = 50
z min = 55
b min = 53
a min = 50
| Datetime and utctimetuple() | In this code mDATE0 for 3 items a, b, z is:
mUNIQUE: z | mDATE0: 2010-11-14 14:55:04.293000
mUNIQUE: b | mDATE0: 2010-11-14 14:53:34.824000
mUNIQUE: a | mDATE0: 2010-11-14 14:50:14.155000
But when I do
...
utc_tuple = rep.mDATE0.utctimetuple()
...
corresponding utc_tuples are:
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
In other words min=55 for all items while mDATE0 has
z --> min=55;
b --> min=53;
a --> min=50
What am I doing wrong? Please see my related question. Thanks.
| [
"That isn't code! Please post short, complete example code to illustrate a problem. Below is what I think you are trying to do, but without seeing your code, there is no way for anyone to point your bug.\nfrom datetime import datetime\n# build up some datetime objects.\nz = datetime.strptime('2010-11-14 14:55:04.... | [
3
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0004178125_datetime_google_app_engine_python.txt |
Q:
Python lambda optimization
I've just been learning lambda (About time) and I've figured some things out, I get the general idea.
I have a map() with a lambda here that can surely be made shorter, but I don't know how:
map(lambda x: [ x.split()[0], x.split()[2], x.split()[4] ] , y)
I hoped it would be possible to get the 0, 2 and 4 elements of the split 'x' at once, but currently I have to split it 3 times to get them...
A:
lambda x: operator.itemgetter(0, 2, 4)(x.split())
A:
map(lambda x: x.split()[0:5:2] , y)
Meaning - take x.split() and take the sublist [0:5] with each second item in it.
A:
Just for variety's sake, featuring no itemgetter() call:
map(lambda x: [x[i] for i in (0,2,4)], (s.split() for s in y))
The (0,2,4) could be replaced with range(0,5,2), of course.
For such a small number of items you could just be explicit with: [x[0], x[2], x[4]]
How it works: The lambda function simply returns a list of the desired elements of the list it is passed. The (s.split() for s in y) is a generator that produces split() versions of the items in list y. Driving all this is the call to map() which applies the lambda function to each one of the split() items from y. In Python 2.x it creates a list of the results from each of these calls.
To answer your follow-up question in the comments about using g = lambda x: [x[i] for i in (0,2,4)]
along with (g(s.split()) for s in y) to get rid of map(). That's basically the right idea, but the second expression results in just a generator object. That would need to be wrapped in something like: [g(s.split()) for s in y] to get the result.
If you didn't want to have a separate lambda named g you could use:
[(lambda x: [x[i] for i in (0,2,4)])(s.split()) for s in y]
| Python lambda optimization | I've just been learning lambda (About time) and I've figured some things out, I get the general idea.
I have a map() with a lambda here that can surely be made shorter, but I don't know how:
map(lambda x: [ x.split()[0], x.split()[2], x.split()[4] ] , y)
I hoped it would be possible to get the 0, 2 and 4 elements of the split 'x' at once, but currently I have to split it 3 times to get them...
| [
"lambda x: operator.itemgetter(0, 2, 4)(x.split())\n\n",
"map(lambda x: x.split()[0:5:2] , y)\nMeaning - take x.split() and take the sublist [0:5] with each second item in it.\n",
"Just for variety's sake, featuring no itemgetter() call:\n map(lambda x: [x[i] for i in (0,2,4)], (s.split() for s in y))\n\nThe... | [
6,
4,
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0004177629_lambda_python.txt |
Q:
Python: memory usage statistics per object-types (or source code line)
I am doing some heavy calculations with Python (using OpenCV and Numpy) and in the end, I end up with a lot of memory usage (>1GB) whereby all refs should be gone and I only have the end-result (which should not be more than a few MB).
To debug this, it would be nice if I could get some stats somehow which show me how much object instances there are of what type, ordered by the total amount of memory they take (per object class).
Or even nicer: Not per object class but per source code line where the object was created (whereby I guess this info is not available unless I activate some debugging in Python which would make the calculation too slow, so I am not sure if that would be helpful).
Can I get some stats like this somehow? Or how would I debug this?
Some has missunderstood me: I only need to know how to debug the memory usage. Processing/run- time is perfect.
A:
I think you're searching for a python profiler ;
you have a bunch of them that you can use , like Heapy, profile or cprofile , Pysize ...
example using Heapy :
you have to include this snippet somewhere in your code:
from guppy import hpy
h = hpy()
print h.heap()
and it will give you as output:
Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 35144 27 2140412 26 2140412 26 str
1 38397 29 1309020 16 3449432 42 tuple
2 530 0 739856 9 4189288 50 dict (no owner)
example with cprofile :
you can run it like this:
python -m cProfile script.py
Output:
5 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 myscript.py:1(<module>)
1 0.000 0.000 0.000 0.000 {execfile}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {range}
You can also use gc module to know why python is not freeing your memory, and to ask him to free memory using gc.collect().
By the way have you looked at numpy, i think it more suitable if you're doing heavy calculation like you said.
A:
Ok, I hunted it down. As none of the Python mem profiles give any helpful output (because they couldn't find the memory), I was quite sure that some of the external libs (OpenCV) were the source of the mem leak.
And I could reproduce the mem leak with this simple code:
import cv
while True: cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)
Some of the other resources for Python mem debugging which were quite interesting (didn't helped in that case but may be useful for others):
Tracing Python memory leaks
Python object graphs
Hunting memory leaks in Python
Object graphs with graphviz
| Python: memory usage statistics per object-types (or source code line) | I am doing some heavy calculations with Python (using OpenCV and Numpy) and in the end, I end up with a lot of memory usage (>1GB) whereby all refs should be gone and I only have the end-result (which should not be more than a few MB).
To debug this, it would be nice if I could get some stats somehow which show me how much object instances there are of what type, ordered by the total amount of memory they take (per object class).
Or even nicer: Not per object class but per source code line where the object was created (whereby I guess this info is not available unless I activate some debugging in Python which would make the calculation too slow, so I am not sure if that would be helpful).
Can I get some stats like this somehow? Or how would I debug this?
Some has missunderstood me: I only need to know how to debug the memory usage. Processing/run- time is perfect.
| [
"I think you're searching for a python profiler ; \nyou have a bunch of them that you can use , like Heapy, profile or cprofile , Pysize ...\nexample using Heapy :\nyou have to include this snippet somewhere in your code:\nfrom guppy import hpy\nh = hpy()\nprint h.heap()\n\nand it will give you as output:\nPartitio... | [
11,
7
] | [] | [] | [
"debugging",
"memory",
"memory_leaks",
"python"
] | stackoverflow_0004178116_debugging_memory_memory_leaks_python.txt |
Q:
Which opensource web framework should a C# ASP.NET Guy Learn?
I am a web developer working mainly with C# on ASP.NET (Webforms and MVC)..
I have worked previously with PHP and Other Frameworks and languages of the sort..
I am currently looking and focusing all my development on 2 platforms..
One Proprietary and Industry Class Framework (ASP.NET MVC)
and
One Opensource and Free Framework (Insert framework of choice here)
I have no experience with python or ruby but would like to learn one and use either django or rails..
While i understand both are very different from ASP.NET please advise me which one would be the smoothest transition.. (or the one most worth the migration pain is better!)
Thanks
Daniel
A:
I've been learning rails and loving it. The pain point with it is the documentation - version 3 of rails has just come out, and not all of the documentation you will come across will be up to date. However, you can pretty easily get by.
That said, I'm loving it. Ruby is a very elegant language. You can get a feel for rails by reading through this guide:
http://guides.rubyonrails.org/getting_started.html
A:
I did ASP, then PHP, now ASP .NET for the last 5 years, dabbled with Python now I'm doing some RoR. Don't learn something 'similar' just to get outside of the MSFT stack. Check out Ruby on Rails, it's a different mindset, and you will learn a new way of thinking about a lot of things that will make your ASP .Net code better.
For me Python / Django felt much better and easier. Less magical, but Ruby on Rails is pretty amazing and has a lot going for it.
I would suggest you check out www.tekpub.com where Rob Conrey a MSFT .Net guy does a ton of tutorials including video tutorials on RoR 3.
A:
With open source frameworks, I would choose between RoR and Django. Just stay away from anything PHP-based.
First, I would say learn the base language first, to an extent, and go with the framework built on the language you prefer. For example, I do django because I learned python, not ruby. I tried ruby when I was hired for a rails project (for frontend work, but nevermind), and it just felt too... "fluffy" for my taste.
Second, there's the issue of documentation. Django's docs are always up-to-date (keeping them so is part of the django development process) on 99% of topics you would want to look up, and are fairly easy to follow once you get the basics. The other 1% of things you would want to look up are generally completely undocumented, derivable from the source or else not possible (often possible with a third-party app, though, which are easily found). I can't speak too much for rails, but I was able to find little usable documentation in my short foray into it; perhaps I'm just too used to Django's docs.
Finally there's the development environment -- you're likely to have multiple projects on one machine, possibly with conflicting dependencies. With django/python, you get virtualenv and pip as part of the python dev process (or at least you should). These tools work very well for setting up secluded environments for separate projects. Ruby doesn't have any standardized tools for this purpose, but there is a gem called sandbox that worked well enough toward this purpose when I used it; IMO though, it seems as if it has to fight against ruby's natural behavior to get the concept to work. It looks like it hasn't seen active development in a couple years, unfortunately.
Other factors to consider include mass of third-party apps for a framework and size and attitude of the community behind a framework. In the end, though, I guess it comes down to your comfort level among the languages you know and personal preference.
And I will freely admit that I'm rooting for django.
A:
I am a .NET guy and also worked on PHP for a couple of months. At present I am learning Ruby and after completing basics, I am going to move on Rails.
I would suggest you to go with Ruby and than Rails. Career-wise also, Ruby guys are in demand these days, at least in my country.
A:
For a .Net developer try to start with www.pradosoft.com/ prado framework,
it's PHP framework which looks exactly like ASP.NET ..
try it
| Which opensource web framework should a C# ASP.NET Guy Learn? | I am a web developer working mainly with C# on ASP.NET (Webforms and MVC)..
I have worked previously with PHP and Other Frameworks and languages of the sort..
I am currently looking and focusing all my development on 2 platforms..
One Proprietary and Industry Class Framework (ASP.NET MVC)
and
One Opensource and Free Framework (Insert framework of choice here)
I have no experience with python or ruby but would like to learn one and use either django or rails..
While i understand both are very different from ASP.NET please advise me which one would be the smoothest transition.. (or the one most worth the migration pain is better!)
Thanks
Daniel
| [
"I've been learning rails and loving it. The pain point with it is the documentation - version 3 of rails has just come out, and not all of the documentation you will come across will be up to date. However, you can pretty easily get by.\nThat said, I'm loving it. Ruby is a very elegant language. You can get a feel... | [
2,
2,
2,
1,
0
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0004175611_django_python_ruby_ruby_on_rails.txt |
Q:
OpenGL: Model doesn't look right when loaded in python
I have a blender model and below is a image of how my model renders when I load it into python. It looks like the normals are all messed up. I am using the correct normal for each vertex. I'm exporting them in the correct order. I test this in the blender console that the actual export file had the right data.
I know that I had to rotate the model in python because z axis is different, so I'm not sure if the normals z is pointing in the wrong direction.
I'm using pyglet. Has anyone ever had this problem before?
Any ideas of what I can do to try to fix it?
Im not sure if this a OpenGL or python problem.
opengl setup code:
glMatrixMode(GL_PROJECTION)
zNear = 0.01
zFar = 1000.0
fieldOfView = 45.0
size = zNear * math.tan(math.radians(fieldOfView) / 2.0)
glFrustum(-size, size, -size / (w / h), size /
(w / h), zNear, zFar);
glViewport(0, 0, w, h);
# Set-up projection matrix
# TODO
glMatrixMode(GL_MODELVIEW)
glShadeModel(GL_SMOOTH)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
light0Ambient = (GLfloat * 4)(*[])
light0Ambient[0] = 0.2
light0Ambient[1] = 0.2
light0Ambient[2] = 0.2
light0Ambient[3] = 1.0
glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient);
lightpos = (GLfloat * 3)(*[])
lightpos[0] = 5.0
lightpos[1] = 5.0
lightpos[2] = 5.0
glLightfv(GL_LIGHT0, GL_POSITION, lightpos)
tempLV = self.kjgCreateVectorWithStartandEndPoints((5.0,5.0,5.0), (0.0,0.0,-3.0))
lightVector = (GLfloat * 3)(*[])
lightVector[0] = tempLV[0]
lightVector[1] = tempLV[1]
lightVector[2] = tempLV[2]
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,lightVector);
glLoadIdentity( )
glTranslatef(0.0, 2.0, -18.0)
#glScalef(0.4, 0.4, 0.4)
glRotatef(-90, 1.0, 0.0, 0.0)
Draw Code:
for face in self.faces:
#print group
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
if i in (104,16,18,102):
glVertex3f(*self.vertices[i])
color = self.calculateVertexIntensity((.5,.5,.5),self.normals[i],self.vertices[i])
glColor3f(*color)
glNormal3f(*self.normals[i])
glEnd()
A:
Right now you are specifying the normal after the vertex instead of before, so basically you're specifying the normal of vertex X for the vertex X+1. This is the most important flaw in the current code.
Also, what's that calculateVertexIntensity? First of all, lighting is enabled in your code so glColor is going to be ignored anyway, but still it looks like you tried to do something unnecessary here - the OpenGL fixed function rendering already will calculate the vertex intensity basing on the glLight* settings and glMaterial* settings.
Also, you might want to normalize your lightVector, I'm not sure whether OpenGL's going to normalize it for you.
(Also make sure to check on the recent OpenGL features; you're using deprecated functions right now and because of that you'll soon hit a performance barrier. First thing too look for is vertex arrays or VBO, the next is shaders.)
A:
This looks like a problem with your normals.
The data in self.normals is probably wrong: you should recalculate normals making sure that you always use a sequence of vertices in the anticlockwise direction around the face to calculate each normal.
(also, you should be calling glNormal before drawing each vertex / face)
(also also, I don't know what's going on when you calculate the colour for each vertex: but check that that isn't causing problems)
| OpenGL: Model doesn't look right when loaded in python | I have a blender model and below is a image of how my model renders when I load it into python. It looks like the normals are all messed up. I am using the correct normal for each vertex. I'm exporting them in the correct order. I test this in the blender console that the actual export file had the right data.
I know that I had to rotate the model in python because z axis is different, so I'm not sure if the normals z is pointing in the wrong direction.
I'm using pyglet. Has anyone ever had this problem before?
Any ideas of what I can do to try to fix it?
Im not sure if this a OpenGL or python problem.
opengl setup code:
glMatrixMode(GL_PROJECTION)
zNear = 0.01
zFar = 1000.0
fieldOfView = 45.0
size = zNear * math.tan(math.radians(fieldOfView) / 2.0)
glFrustum(-size, size, -size / (w / h), size /
(w / h), zNear, zFar);
glViewport(0, 0, w, h);
# Set-up projection matrix
# TODO
glMatrixMode(GL_MODELVIEW)
glShadeModel(GL_SMOOTH)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
light0Ambient = (GLfloat * 4)(*[])
light0Ambient[0] = 0.2
light0Ambient[1] = 0.2
light0Ambient[2] = 0.2
light0Ambient[3] = 1.0
glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient);
lightpos = (GLfloat * 3)(*[])
lightpos[0] = 5.0
lightpos[1] = 5.0
lightpos[2] = 5.0
glLightfv(GL_LIGHT0, GL_POSITION, lightpos)
tempLV = self.kjgCreateVectorWithStartandEndPoints((5.0,5.0,5.0), (0.0,0.0,-3.0))
lightVector = (GLfloat * 3)(*[])
lightVector[0] = tempLV[0]
lightVector[1] = tempLV[1]
lightVector[2] = tempLV[2]
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,lightVector);
glLoadIdentity( )
glTranslatef(0.0, 2.0, -18.0)
#glScalef(0.4, 0.4, 0.4)
glRotatef(-90, 1.0, 0.0, 0.0)
Draw Code:
for face in self.faces:
#print group
if len(face) == 3:
glBegin(GL_TRIANGLES)
elif len(face) == 4:
glBegin(GL_QUADS)
else:
glBegin(GL_POLYGON)
for i in face:
if i in (104,16,18,102):
glVertex3f(*self.vertices[i])
color = self.calculateVertexIntensity((.5,.5,.5),self.normals[i],self.vertices[i])
glColor3f(*color)
glNormal3f(*self.normals[i])
glEnd()
| [
"Right now you are specifying the normal after the vertex instead of before, so basically you're specifying the normal of vertex X for the vertex X+1. This is the most important flaw in the current code.\nAlso, what's that calculateVertexIntensity? First of all, lighting is enabled in your code so glColor is going ... | [
6,
0
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004178258_opengl_pyglet_python.txt |
Q:
wx Text with outline
I have a video player written in wxpython and am overlaying the current FPS onto the video.
My text is black, so if the video is sufficiently dark the FPS counter is not visible.
I am looking for a way to draw text with an outline so it will stand out no matter what the video is displaying. E.g. I want black text with a white outline.
I am currently drawing text directly onto the DC, as so:
dc.DrawBitmap(self.img, 0, 0)
dc.DrawText(str(self.frames), 0, 0)
Thanks for any help!
A:
You are out of luck for any nice built in solution along the lines of options in font selection or pairs of fonts, one to draw the outline, one to draw the interior.
If you are only showing frame per second values and only using digits 0..9 and '.' then use small bitmaps for the numbers created yourself in an image editor, with alpha so that only the central region and outline show.
If you want arbitrary text it's rather more work. Generate the characters with an outline programmatically. Draw the unoutlined font to a bitmap using a wxMemoryDC, convert to a wxImage, GetData() to get the raw data, use a http://en.wikipedia.org/wiki/Sobel_filter to add an outline - and from this you can create the partially transparent bitmap to overlay onto your DC. If you want nice anti-aliasing of the numbers draw them at twice the size you'll use and use a 5x5 kernel.
| wx Text with outline | I have a video player written in wxpython and am overlaying the current FPS onto the video.
My text is black, so if the video is sufficiently dark the FPS counter is not visible.
I am looking for a way to draw text with an outline so it will stand out no matter what the video is displaying. E.g. I want black text with a white outline.
I am currently drawing text directly onto the DC, as so:
dc.DrawBitmap(self.img, 0, 0)
dc.DrawText(str(self.frames), 0, 0)
Thanks for any help!
| [
"You are out of luck for any nice built in solution along the lines of options in font selection or pairs of fonts, one to draw the outline, one to draw the interior.\nIf you are only showing frame per second values and only using digits 0..9 and '.' then use small bitmaps for the numbers created yourself in an ima... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003661054_python_wxpython.txt |
Q:
move_uploaded_file function equivalent in django
I would like to upload some files from form to cloud server without redirecting there. So I've found this tutorial with php/ajax but a function that is not present in django is used there - move_uploaded_file. How can I achieve the same with django ? Currently I'm using a part of django-filetransfers, but after submitting my form the whole part after if request.method == POST is omitted :
def upload_handler(request):
if request.method == 'POST':
form = ArtifactSubmissionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
upload_url, upload_data = prepare_upload(request, "uploadlink")
form = ArtifactSubmissionForm()
myfileid = create_myfileid()
return direct_to_template(request, 'rte/artifact_inline.html',
{'upload_url': upload_url,
'form': form,
'upload_data': upload_data,
'myfileid': myfileid,
'artifact': artifact,
'submissions': submissions})
and the html:
{% load filetransfers %}
{% block artifact %}
<h1>Submit</h1>
<form action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
{% render_upload_data upload_data %}
<table>{{ form }}</table>
<p>
<input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
{% endblock %}
EDIT:
I just need to send files to server for further processing and then read their urls from servers response. Don't need to use them as File objects.
A:
The django-storages plug-in has features that allows you to automatically store uploaded content to the repository of your choice. It has an annoying need to be linked to your MEDIA_URL, but that's just code and you can work around it.
Source code can be found here: Django storages.
I recommend rooting around the network for one that you like. If you're using Amazon Cloudfront, as I do at my current position, using one that disabls HTTPS over signed URLS saved us a few millicents per download, which does add up over time.
| move_uploaded_file function equivalent in django | I would like to upload some files from form to cloud server without redirecting there. So I've found this tutorial with php/ajax but a function that is not present in django is used there - move_uploaded_file. How can I achieve the same with django ? Currently I'm using a part of django-filetransfers, but after submitting my form the whole part after if request.method == POST is omitted :
def upload_handler(request):
if request.method == 'POST':
form = ArtifactSubmissionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
upload_url, upload_data = prepare_upload(request, "uploadlink")
form = ArtifactSubmissionForm()
myfileid = create_myfileid()
return direct_to_template(request, 'rte/artifact_inline.html',
{'upload_url': upload_url,
'form': form,
'upload_data': upload_data,
'myfileid': myfileid,
'artifact': artifact,
'submissions': submissions})
and the html:
{% load filetransfers %}
{% block artifact %}
<h1>Submit</h1>
<form action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
{% render_upload_data upload_data %}
<table>{{ form }}</table>
<p>
<input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
{% endblock %}
EDIT:
I just need to send files to server for further processing and then read their urls from servers response. Don't need to use them as File objects.
| [
"The django-storages plug-in has features that allows you to automatically store uploaded content to the repository of your choice. It has an annoying need to be linked to your MEDIA_URL, but that's just code and you can work around it.\nSource code can be found here: Django storages.\nI recommend rooting around t... | [
0
] | [] | [] | [
"cloud_hosting",
"django",
"file_upload",
"python",
"redirect"
] | stackoverflow_0004174376_cloud_hosting_django_file_upload_python_redirect.txt |
Q:
python/pylons - multiple controllers for template
I have a main page in Python/Pylons project, which have multiple different blocks (e.g. news/demo/(registration|private zone)/...).
My thought is that each block should be generated in a separate controller.
How can I call another controller method in a main page controller?
A:
What you want to do is HMVC. I'm not sure it is easily doable out of the box with Pylons, since it's MVC.
If you have code that is repeated in multiple controllers, you could move some of this code out of the controller (in the models, or another module).
Also, if you are using Mako templates, you can reuse parts of templates by using inheritance http://www.makotemplates.org/docs/inheritance.html and by using defs http://www.makotemplates.org/docs/defs.html.
A:
This is probably where you start moving chunks of code to library functions, to the /lib part of your Pylons project. "Generated by a separate controller" is probably going too far - you merely need to not repeat yourself. Try using library functions to make sure that the correct data is available, then use Mako's inheritance and namespace features.
| python/pylons - multiple controllers for template | I have a main page in Python/Pylons project, which have multiple different blocks (e.g. news/demo/(registration|private zone)/...).
My thought is that each block should be generated in a separate controller.
How can I call another controller method in a main page controller?
| [
"What you want to do is HMVC. I'm not sure it is easily doable out of the box with Pylons, since it's MVC.\nIf you have code that is repeated in multiple controllers, you could move some of this code out of the controller (in the models, or another module).\nAlso, if you are using Mako templates, you can reuse part... | [
1,
0
] | [] | [] | [
"model_view_controller",
"pylons",
"python"
] | stackoverflow_0004171842_model_view_controller_pylons_python.txt |
Q:
Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?
Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?a
Thanks
A:
Because cursor.execute() doesn't actually return the data. Presumably you need that, so you need to run fetchall.
| Why would I want to reference cursor.fetchall() if I can use cursor.execute directly? | Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?a
Thanks
| [
"Because cursor.execute() doesn't actually return the data. Presumably you need that, so you need to run fetchall.\n"
] | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004178828_python_sqlite.txt |
Q:
Python: Problems adding items to list in a class
I've got a class defined with a method to add items to it:
class ProdReg:
def __init__(self):
self.__PListe=[]
def addProdukt(self,pItem):
self.__Pliste.append(pItem)
When I instantiate a ProdReg object and try to add an object to it with the following code i gent an error:
pr.addProdukt(b)
I get the following error:
AttributeError: 'ProdReg' object has no attribute '_ProdReg__Pliste'
What's wrong? I'm not able to figure thisone out.
/Andy.l
A:
Because in the __init__ you wrote: __PListe and in the the addProdukt method, you wrote __Pliste. Python is case sensitive.
A:
It's a typo in your code I think, or a misunderstand of how names work. In Python names are case-sensitive.
You add the attribute as PListe then reference it as Pliste. In one in the L is lower case and in the other it is upper case.
| Python: Problems adding items to list in a class | I've got a class defined with a method to add items to it:
class ProdReg:
def __init__(self):
self.__PListe=[]
def addProdukt(self,pItem):
self.__Pliste.append(pItem)
When I instantiate a ProdReg object and try to add an object to it with the following code i gent an error:
pr.addProdukt(b)
I get the following error:
AttributeError: 'ProdReg' object has no attribute '_ProdReg__Pliste'
What's wrong? I'm not able to figure thisone out.
/Andy.l
| [
"Because in the __init__ you wrote: __PListe and in the the addProdukt method, you wrote __Pliste. Python is case sensitive.\n",
"It's a typo in your code I think, or a misunderstand of how names work. In Python names are case-sensitive.\nYou add the attribute as PListe then reference it as Pliste. In one in th... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0004179062_python.txt |
Q:
Python Named Argument is Keyword?
So an optional parameter expected in the web POST request of an API I'm using is actually a reserved word in python too. So how do I name the param in my method call:
example.webrequest(x=1,y=1,z=1,from=1)
this fails with a syntax error due to 'from' being a keyword. How can I pass this in in such a way that no syntax error is encountered?
A:
Pass it as a dict.
func(**{'as': 'foo', 'from': 'bar'})
A:
args = {'x':1, 'y':1, 'z':1, 'from':1}
example.webrequest(**args)
// dont use that library
| Python Named Argument is Keyword? | So an optional parameter expected in the web POST request of an API I'm using is actually a reserved word in python too. So how do I name the param in my method call:
example.webrequest(x=1,y=1,z=1,from=1)
this fails with a syntax error due to 'from' being a keyword. How can I pass this in in such a way that no syntax error is encountered?
| [
"Pass it as a dict.\nfunc(**{'as': 'foo', 'from': 'bar'})\n\n",
"args = {'x':1, 'y':1, 'z':1, 'from':1}\nexample.webrequest(**args)\n\n// dont use that library\n"
] | [
16,
2
] | [] | [] | [
"keyword",
"named_parameters",
"python",
"reserved_words"
] | stackoverflow_0004179175_keyword_named_parameters_python_reserved_words.txt |
Q:
Unable to print content of list in python
I've made a class containing a list, with the following code:
class ProdReg:
def __init__(self):
self.__Pliste=[]
This works perfectly.
I've also added a method to print the contents of my list:
def printProdReg(self):
for produkt in self.__Pliste:
print(produkt)
This doesn't work all to great, When I try to add an object to this list, I get the following error:
<__main__.Bok object at 0x05777970>
The object is a class called Bok.
No idea what so ever how I can resolve this.
A:
The call to print calls __str__ on your object, which by default prints the type and memory address. If you want a more readable representation of your object you need to give your class a new implementation of __str__.
class Bok(object):
def __str__(self):
return 'This is a Bok!'
# Other members here...
A:
There's no problem, its just that the interpreter doesn't know how to print your object:
>>> class Me:
... pass
...
>>> me = Me()
>>> print me
<__main__.Me instance at 0xf98368>
If you need something to be printed, you can add an __str__ method to your object:
>>> class Me:
... def __str__(self):
... return "It's Me!"
...
>>> me = Me()
>>> print me
It's Me!
A:
This actually is not an error - it's printing your object, which is of class Bok. Try adding __str__ to the Bok class to print it's contents. You can see how here: http://en.wikibooks.org/wiki/Python_Programming/Classes.
As a simple test, try adding this to your Bok class:
class Bok(object):
def __str__(self):
return "This is Bok"
and running your test again.
A:
That's not an error, it's the object that is being returned by the function you're using to add to the list.
| Unable to print content of list in python | I've made a class containing a list, with the following code:
class ProdReg:
def __init__(self):
self.__Pliste=[]
This works perfectly.
I've also added a method to print the contents of my list:
def printProdReg(self):
for produkt in self.__Pliste:
print(produkt)
This doesn't work all to great, When I try to add an object to this list, I get the following error:
<__main__.Bok object at 0x05777970>
The object is a class called Bok.
No idea what so ever how I can resolve this.
| [
"The call to print calls __str__ on your object, which by default prints the type and memory address. If you want a more readable representation of your object you need to give your class a new implementation of __str__.\nclass Bok(object):\n def __str__(self):\n return 'This is a Bok!'\n\n # Other ... | [
6,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004179308_python.txt |
Q:
Passing Django template variables into javascript in GAE
I'm trying to create a wordcloud with the Google's visualization sample:
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="wcdiv"></div>
<script type="text/javascript">
google.load("visualization", "1");
google.setOnLoadCallback(draw);
function draw() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Text1');
data.addRows(160);
{{datamade}}
var outputDiv = document.getElementById('wcdiv');
var wc = new WordCloud(outputDiv);
wc.draw(data, null);
}
</script>
I'm creating {{datamade}} in my main.py file, then passing it as a template variable:
tweets1 = []
fetched = urlfetch.fetch("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+tweets.username+"&count=200")
statustext = json.loads(fetched.content)
for tweetInfo in statustext:
tweets1.append(tweetInfo["text"])
datamake = []
n = 1
for n in range(160):
tweet = tweets1[n]
datamake.append("data.setCell("+str(n)+", 0, '"+tweet+"');")
datamade = '<br>'.join(datamake)
content_values = {
'datamade':datamade,
'username':tweets.username,
}
When I print the {{datamade}}, I see the correct Javascript code. And when I hardcode the values into my statuspage.html, the javascript executes correctly. But when I pass the variable directly into the javascript, the javascript does not execute properly.
It my javascript executing prior to the template value is passed? Not sure how to adjust for this. I'd appreciate any advice.
Disclaimer: I'm a total newb.
Thank you!
Jake
A:
I would suggest making a number of changes to your code. Instead of generating javascript calls (data.setCell), generate the table and let Google's DataTable process it.
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
class GetTweetsHandler(webapp.RequestHandler):
def get(self):
user = self.request.get('user', 'someuser')
fetched = urlfetch.fetch("http://api.twitter.com/1/statuses/user_timeline.json"
"?screen_name=" + user + "&count=200")
tweets = json.loads(fetched.content)
data = {'cols': [{'type': 'string', 'label': 'Tweets'}],
'rows': [{'c': [{'v': tweet["text"]}]} for tweet in tweets]}
template_values = {'tweet_data': json.dumps(data),
'user': user}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
def main():
application = webapp.WSGIApplication([('/gettweets', GetTweetsHandler)],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
So then you will just need to pass the datatable you generated to Google's DataTable. Luckily that is a very small change to your template:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1");
google.setOnLoadCallback(draw);
function draw() {
var tweet_data = {{tweet_data}};
var data = new google.visualization.DataTable(tweet_data);
var outputDiv = document.getElementById('wcdiv');
var wc = new WordCloud(outputDiv);
wc.draw(data, null);
}
</script>
</head>
<body>
<div id="wcdiv"></div>
<form method='get'>
<input type='text' name='user' value="{{user}}"></input>
<input type='submit'></input>
</form>
</body>
</html>
Call it by going to http://localhost:8080/gettweets/someuser
A:
Jake, offhand it looks like you're putting '<br>' tags into your js code. 'datamade' could be:
data.setCell('foo', 0, 'bar');<br>data.setCell('foo', 0, 'bar');
This is not executable js because html tags aren't read by a js interpreter. You'd effectively be writing an incomplete comparison expression (nothing is less than a variable called br). Don't bother trying to insert the page breaks into your code, and just join on an empty string.datamade = ''.join(datamake)
Edit:
In general though, it's not good practice to use a loop to print out 100+ lines of js. You're better off sending the whole object to js in json format and looping over it afterward in the client.
I'd advise this:
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="wcdiv"></div>
<script type="text/javascript">
google.load("visualization", "1");
google.setOnLoadCallback(draw);
function draw() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Text1');
data.addRows(160);
var tweets = {{tweets}};
for (var i in tweets) {
data.setCell(i, 0, tweets[i]);
}
var outputDiv = document.getElementById('wcdiv');
var wc = new WordCloud(outputDiv);
wc.draw(data, null);
}
</script>
And have you server file show the following:
tweets1 = []
fetched = urlfetch.fetch("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+tweets.username+"&count=200")
statustext = json.loads(fetched.content)
for tweetInfo in statustext:
tweets1.append(tweetInfo["text"])
tweetsJson = json.dumps(tweets1)
content_values = {
'tweets':tweetsJson,
'username':tweets.username,
}
| Passing Django template variables into javascript in GAE | I'm trying to create a wordcloud with the Google's visualization sample:
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="wcdiv"></div>
<script type="text/javascript">
google.load("visualization", "1");
google.setOnLoadCallback(draw);
function draw() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Text1');
data.addRows(160);
{{datamade}}
var outputDiv = document.getElementById('wcdiv');
var wc = new WordCloud(outputDiv);
wc.draw(data, null);
}
</script>
I'm creating {{datamade}} in my main.py file, then passing it as a template variable:
tweets1 = []
fetched = urlfetch.fetch("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+tweets.username+"&count=200")
statustext = json.loads(fetched.content)
for tweetInfo in statustext:
tweets1.append(tweetInfo["text"])
datamake = []
n = 1
for n in range(160):
tweet = tweets1[n]
datamake.append("data.setCell("+str(n)+", 0, '"+tweet+"');")
datamade = '<br>'.join(datamake)
content_values = {
'datamade':datamade,
'username':tweets.username,
}
When I print the {{datamade}}, I see the correct Javascript code. And when I hardcode the values into my statuspage.html, the javascript executes correctly. But when I pass the variable directly into the javascript, the javascript does not execute properly.
It my javascript executing prior to the template value is passed? Not sure how to adjust for this. I'd appreciate any advice.
Disclaimer: I'm a total newb.
Thank you!
Jake
| [
"I would suggest making a number of changes to your code. Instead of generating javascript calls (data.setCell), generate the table and let Google's DataTable process it.\nimport os\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext.webapp... | [
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0004179338_django_google_app_engine_javascript_python.txt |
Q:
How to query a Django model defining a IP range with two int fields (IP, mask)
I have:
class Range(models.Model):
ip = models.IntegerField() # as produced by socket.inet_aton + struct.unpack
mask = models.IntegerField()
Given a certain IP, how can I get all the ranges that match this specific IP using the Django models?
If I were using raw SQL, I would use the database's bitwise operators, but the Django ORM doesn't support those.
A:
The QuerySet API in Django 1.0 now includes the 'extra' method, described here in the Django docs. The extra method allows you to pass custom WHERE clauses to your QuerySet, which should allow you to use the bitwise comparison you need.
A:
To do faster query fitting the range you'd better store lower and upper IP of range as integer. Then selection of needed objects should be as simple as Range.objects.filter(ip_low__le=ip, ip_up__ge=ip).
A:
I would recommend using python's iptools :
http://code.google.com/p/python-iptools/
| How to query a Django model defining a IP range with two int fields (IP, mask) | I have:
class Range(models.Model):
ip = models.IntegerField() # as produced by socket.inet_aton + struct.unpack
mask = models.IntegerField()
Given a certain IP, how can I get all the ranges that match this specific IP using the Django models?
If I were using raw SQL, I would use the database's bitwise operators, but the Django ORM doesn't support those.
| [
"The QuerySet API in Django 1.0 now includes the 'extra' method, described here in the Django docs. The extra method allows you to pass custom WHERE clauses to your QuerySet, which should allow you to use the bitwise comparison you need.\n",
"To do faster query fitting the range you'd better store lower and upper... | [
4,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001610227_django_django_models_python.txt |
Q:
Suggestions for developing a threaded tcp based admin interface
I've built a very simple TCP server (in python) that when queried, returns various system level statistics of the host OS running said script.
As part of my experimentation and goal to gain knowledge of python and its available libraries; i would like to build on an administration interface that a) binds to a separate TCP socket b) accepts remote connections from the LAN and c) allows the connected user to issue various commands. The Varnish application is an example of a tool that offers similar administrative functionality.
My knowledge of threads is limited, and I am looking for pointers on how to accomplish something similar to the following :
user connects to admin port (telnet remote.host 12111), and issues "SET LOGGING DEBUG", or "STOP SERVICE".
My confusion relates to how i would go about sharing data between threads. If the service is started on for example thread-1 , how can i access data from that thread?
Alternatively, a list of python applications that offer such a feature would be a great help. I'd gladly poke through code, in order to reuse their ideas.
A:
python includes some multi-threading servers (SocketServer, BaseHTTPServer, xmlrpclib). You might want to look at Twisted as well, it is a powerful framework for networking.
A:
Probably the easiest starting point would involve Python's xmlrpclib.
Regarding threading, all threads can read all data in a Python program; only one thread at a time can modify any given object, so primitives such as lists and dicts will always be in a consistent state. Data structures (i.e. class objects) involving multiple primitives will require a little more care. The safest way to coordinate between threads is to pass messages/commands between threads via something like Queue.Queue; this isn't always the most efficient way but it's far less prone to problems.
A:
Best use the multiprocessing library, it provides a full set of functionality for parallel computing (Queues, Pipes, ...).
Multithreading in python is not efficient due to the limitations that come with the GIL.
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
The GIL is controversial because it prevents multithreaded CPython programs from taking full advantage of multiprocessor systems in certain situations.
| Suggestions for developing a threaded tcp based admin interface | I've built a very simple TCP server (in python) that when queried, returns various system level statistics of the host OS running said script.
As part of my experimentation and goal to gain knowledge of python and its available libraries; i would like to build on an administration interface that a) binds to a separate TCP socket b) accepts remote connections from the LAN and c) allows the connected user to issue various commands. The Varnish application is an example of a tool that offers similar administrative functionality.
My knowledge of threads is limited, and I am looking for pointers on how to accomplish something similar to the following :
user connects to admin port (telnet remote.host 12111), and issues "SET LOGGING DEBUG", or "STOP SERVICE".
My confusion relates to how i would go about sharing data between threads. If the service is started on for example thread-1 , how can i access data from that thread?
Alternatively, a list of python applications that offer such a feature would be a great help. I'd gladly poke through code, in order to reuse their ideas.
| [
"python includes some multi-threading servers (SocketServer, BaseHTTPServer, xmlrpclib). You might want to look at Twisted as well, it is a powerful framework for networking.\n",
"Probably the easiest starting point would involve Python's xmlrpclib.\nRegarding threading, all threads can read all data in a Python ... | [
1,
0,
0
] | [] | [] | [
"admin_interface",
"multithreading",
"python",
"sockets"
] | stackoverflow_0004179077_admin_interface_multithreading_python_sockets.txt |
Q:
What is the proper python way to write methods that only take a particular type?
I have a function that is supposed to take a string, append things to it where necessary, and return the result.
My natural inclination is to just return the result, which involved string concatenation, and if it failed, let the exception float up to the caller. However, this function has a default value, which I just return unmodified.
My question is: What if someone passed something unexpected to the method, and it returns something the user doesn't expect? The method should fail, but how to enforce that?
A:
It's not necessary to do so, but if you want you can have your method raise a TypeError if you know that the object is of a type that you cannot handle. One reason to do this is to help people to understand why the method call is failing and to give them some help fixing it, rather than giving them obscure error from the internals of your function.
Some methods in the standard library do this:
>>> [] + 1
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate list (not "int") to list
A:
You can use decorators for this kind of thing, you can see an example here.
But forcing parameters to be of a specific type isn't very pythonic.
A:
Python works under the assumption that we are all intelligent adults that read the documentation. If you still want to do it, you should not assert the actual type, but rather just catch the exception when the argument does not support the operations you need, like that:
def foo(arg):
try:
return arg + "asdf"
except TypeError:
return arg
A:
What does the default value have to do with it? Are you saying you want to return the default value in the case where the caller doesn't pass a str? In that case:
def yourFunc( foo ):
try:
return foo + " some stuff"
except TypeError:
return "default stuff"
Space_C0wb0y has the right answer if you want to return the arg unmodified if it's not a string, and there's also the option of making an attempt to convert something to a string:
def yourFunc2( bar ):
return str(bar) + " some stuff"
Which will work with a lot of different types.
| What is the proper python way to write methods that only take a particular type? | I have a function that is supposed to take a string, append things to it where necessary, and return the result.
My natural inclination is to just return the result, which involved string concatenation, and if it failed, let the exception float up to the caller. However, this function has a default value, which I just return unmodified.
My question is: What if someone passed something unexpected to the method, and it returns something the user doesn't expect? The method should fail, but how to enforce that?
| [
"It's not necessary to do so, but if you want you can have your method raise a TypeError if you know that the object is of a type that you cannot handle. One reason to do this is to help people to understand why the method call is failing and to give them some help fixing it, rather than giving them obscure error f... | [
5,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004179831_python.txt |
Q:
Multiple frames in Tkinter while using Python
Hi I have been trying to get a simple GUI working which accepts a string using an entry form, included in the Tkinter module, and, depending on which container it is in, either runs "killall + string" or "open + string" through terminal. Below is my code that I am using. The problem is in line 8 and the comments above explain in more detail what is wrong.
from tkinter import *
import os
root = Tk()
def buttonPressed():
# this is the problem in the program.
# it keeps returning [''] in the print statement and doesn't quit
# any applications
listOfApps = form1.form.get().split(',')
# the print is just so i can see the output
print(listOfApps)
# goes through each item in list and kills them(yes i know there are much easier
# ways to do this, i'm just trying to learn a bit about GUI and the os module
for i in listOfApps:
try:
os.system("killall " + i)
except:
pass
def buttonPressed2():
filesToOpen = form2.form.get().split(', ')
for i in filesToOpen:
try:
os.system("open " + i)
except:
pass
class form_and_submit:
def _init_(self):
pass
#creates an instance of a form with seperate variables for button text, buton command, and color of the frame
def create_container(self, buttonText, buttonCommand, color):
#Creating all widgets/containers
self.container = Frame(root)
self.form = Entry(self.container)
self.button = Button(self.container)
#defining variables for all widgets/containers
root['background'] = color
self.container['background'] = color
self.button['text'] = buttonText
self.button['command'] = buttonCommand
self.form['background'] = color
self.form['border'] = '5'
self.form['highlightthickness'] = '0'
#Packing all widgets/containers
self.container.pack()
self.form.pack()
self.button.pack()
#creating forms and putting them in root with desire attributes
form1 = form_and_submit
form2 = form_and_submit
form1.create_container(form1, 'kill matching processes', buttonPressed, 'red')
form2.create_container(form2, 'Open desired files', buttonPressed2, 'blue')
#starts up window
root.mainloop()
I believe the problem here is within the multiple frames because it worked fine before with just form1 as an instance of class form_and_submit. Thank you in advance to anyone that can help with this problem.
A:
This is probably not the answer you are looking for, but I can make it do the right thing by getting rid of the class. Here is what I have:
from tkinter import *
import os
root = Tk()
def buttonPressed():
# this is the problem in the program.
# it keeps returning [''] in the print statement and doesn't quit
# any applications
listOfApps = form.get().split(',')
# the print is just so i can see the output
print(listOfApps)
# goes through each item in list and kills them(yes i know there are much easier
# ways to do this, i'm just trying to learn a bit about GUI and the os module
for i in listOfApps:
try:
os.system("killall " + i)
except:
pass
def buttonPressed2():
filesToOpen = form2.get().split(', ')
for i in filesToOpen:
try:
os.system("open " + i)
except:
pass
container = Frame(root)
form = Entry(container)
button = Button(container)
root['background'] = 'red'
container['background'] = 'red'
button['text'] = 'kill matching processes'
button['command'] = buttonPressed
form['background'] = 'red'
form['border'] = '5'
form['highlightthickness'] = '0'
container2 = Frame(root)
form2 = Entry(container2)
button2 = Button(container2)
root['background'] = 'blue'
container2['background'] = 'blue'
button2['text'] = 'Open desired files'
button2['command'] = buttonPressed2
form2['background'] = 'blue'
form2['border'] = '5'
form2['highlightthickness'] = '0'
container.pack()
form.pack()
button.pack()
container2.pack()
form2.pack()
button2.pack()
#starts up window
root.mainloop()
| Multiple frames in Tkinter while using Python | Hi I have been trying to get a simple GUI working which accepts a string using an entry form, included in the Tkinter module, and, depending on which container it is in, either runs "killall + string" or "open + string" through terminal. Below is my code that I am using. The problem is in line 8 and the comments above explain in more detail what is wrong.
from tkinter import *
import os
root = Tk()
def buttonPressed():
# this is the problem in the program.
# it keeps returning [''] in the print statement and doesn't quit
# any applications
listOfApps = form1.form.get().split(',')
# the print is just so i can see the output
print(listOfApps)
# goes through each item in list and kills them(yes i know there are much easier
# ways to do this, i'm just trying to learn a bit about GUI and the os module
for i in listOfApps:
try:
os.system("killall " + i)
except:
pass
def buttonPressed2():
filesToOpen = form2.form.get().split(', ')
for i in filesToOpen:
try:
os.system("open " + i)
except:
pass
class form_and_submit:
def _init_(self):
pass
#creates an instance of a form with seperate variables for button text, buton command, and color of the frame
def create_container(self, buttonText, buttonCommand, color):
#Creating all widgets/containers
self.container = Frame(root)
self.form = Entry(self.container)
self.button = Button(self.container)
#defining variables for all widgets/containers
root['background'] = color
self.container['background'] = color
self.button['text'] = buttonText
self.button['command'] = buttonCommand
self.form['background'] = color
self.form['border'] = '5'
self.form['highlightthickness'] = '0'
#Packing all widgets/containers
self.container.pack()
self.form.pack()
self.button.pack()
#creating forms and putting them in root with desire attributes
form1 = form_and_submit
form2 = form_and_submit
form1.create_container(form1, 'kill matching processes', buttonPressed, 'red')
form2.create_container(form2, 'Open desired files', buttonPressed2, 'blue')
#starts up window
root.mainloop()
I believe the problem here is within the multiple frames because it worked fine before with just form1 as an instance of class form_and_submit. Thank you in advance to anyone that can help with this problem.
| [
"This is probably not the answer you are looking for, but I can make it do the right thing by getting rid of the class. Here is what I have:\nfrom tkinter import *\nimport os\nroot = Tk()\n\ndef buttonPressed():\n # this is the problem in the program.\n # it keeps returning [''] in the print statement and do... | [
0
] | [] | [] | [
"python",
"python_3.x",
"terminal",
"tkinter",
"user_interface"
] | stackoverflow_0004179044_python_python_3.x_terminal_tkinter_user_interface.txt |
Q:
Can I use Django's mail API in Google App Engine?
I'm using Django-nonrel for Google App Engine and I was wondering if it's possible to use Django's built-in mail API instead of GAE's mail API for sending mail. If it is, how do I do it?
Sorry if this seems like a noob question. I just started learning Django and GAE recently and I can't work out this problem that I have by myself.
A:
Yes, djangoappengine has a mail backend for GAE and it's enabled by default in your settings.py via "from djangoappengine.settings_base import *". You can take a look at the settings_base module to see all backends and default settings.
| Can I use Django's mail API in Google App Engine? | I'm using Django-nonrel for Google App Engine and I was wondering if it's possible to use Django's built-in mail API instead of GAE's mail API for sending mail. If it is, how do I do it?
Sorry if this seems like a noob question. I just started learning Django and GAE recently and I can't work out this problem that I have by myself.
| [
"Yes, djangoappengine has a mail backend for GAE and it's enabled by default in your settings.py via \"from djangoappengine.settings_base import *\". You can take a look at the settings_base module to see all backends and default settings.\n"
] | [
3
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0004177907_django_django_nonrel_google_app_engine_python.txt |
Q:
Python script load testing web page
I want to do a test load for a web page. I want to do it in python with multiple threads.
First POST request would login user (set cookies).
Then I need to know how many users doing the same POST request simultaneously can server take.
So I'm thinking about spawning threads in which requests would be made in loop.
I have a couple of questions:
1. Is it possible to run 1000 - 1500 requests at the same time CPU wise? I mean wouldn't it slow down the system so it's not reliable anymore?
2. What about the bandwidth limitations? How good the channel should be for this test to be reliable?
Server on which test site is hosted is Amazon EC2 script would be run from another server(Amazon too).
Thanks!
A:
cPython does not take advantage from multiple cores when running multiple threads. It means, that basically, You will only have one core doing the testing job.
There are dedicated tools to do what You want to do. Let me suggest two:
FunkLoad is a functional and load web tester, written in Python, whose main use cases are:
Functional testing of web projects, and thus regression testing as well.
Performance testing: by loading the web application and monitoring
your servers it helps you to pinpoint bottlenecks, giving a detailed
report of performance measurement.
Load testing tool to expose bugs that do not surface in cursory testing,
like volume testing or longevity testing.
Stress testing tool to overwhelm the web application resources and test
the application recoverability.
Writing web agents by scripting any web repetitive task, like checking if
a site is alive.
Tsung is an open-source multi-protocol distributed load testing tool
The purpose of Tsung is to simulate
users in order to test the scalability
and performance of IP based
client/server applications. You can
use it to do load and stress testing
of your servers. Many protocols have
been implemented and tested, and it
can be easily extended. WebDAV, LDAP
and MySQL support have been added
recently (experimental).
It can be distributed on several
client machines and is able to
simulate hundreds of thousands of
virtual users concurrently (or even
millions if you have enough hardware
...).
If You decide to write Your own tool, You will probably want to use Python's multiprocessing module as it would let You use multiple cores. You should also take a look on Twisted as it would let You easily handle multiple sockets while a limited number of threads. That would be much better than spawning a new thread for each socket.
You work with Amazon EC2, so I would recommend using Tsung. You can rent a dozen of multicore servers for a few hours and run some really heavy load tests with Tsung. It scales very well in this kind of configuration.
As for the bandwidth, it's usually not a problem, but it depends on the application. You will have to monitor all Your resources closely while performing a load test.
A:
too many variables. 1000 at the same time... no. in the same second... possibly. bandwidth may well be the bottleneck. this is something best solved by experimentation.
| Python script load testing web page | I want to do a test load for a web page. I want to do it in python with multiple threads.
First POST request would login user (set cookies).
Then I need to know how many users doing the same POST request simultaneously can server take.
So I'm thinking about spawning threads in which requests would be made in loop.
I have a couple of questions:
1. Is it possible to run 1000 - 1500 requests at the same time CPU wise? I mean wouldn't it slow down the system so it's not reliable anymore?
2. What about the bandwidth limitations? How good the channel should be for this test to be reliable?
Server on which test site is hosted is Amazon EC2 script would be run from another server(Amazon too).
Thanks!
| [
"cPython does not take advantage from multiple cores when running multiple threads. It means, that basically, You will only have one core doing the testing job.\nThere are dedicated tools to do what You want to do. Let me suggest two:\nFunkLoad is a functional and load web tester, written in Python, whose main use ... | [
6,
1
] | [] | [] | [
"load_testing",
"multithreading",
"python"
] | stackoverflow_0004179879_load_testing_multithreading_python.txt |
Q:
Django reverse lookup by ForeignKey
I have a django project which has two apps, one is AppA and AppB. Now AppA has a model
ModelA which is referenced by the model ModelB in AppB, using modelA = models.ForeignKey(ModelA, related_name='tricky')
Now in my view for AppA, when it shows ModelA, I do a get_object_or_404(ModelA, pk=prim_id). Then I want to get all the ModelBs which have a Foreign Key pointing to ModelA.
Documentation says I should do a mb = ModelB.objects.get(pk=prim_id) then mb.modela_set.all()
But, it failed on the mb.modela_set, and it says "ModelB object has no attribute 'suchsuch'". Notice I added the related_name field to ForeignKey, so I tried with that as well, including mb.tricky.all() and mb.tricky_set.all() to no avail.
Oh, and I have specified a different manager for AppA where I do objects = MyManager() which returns the normal query but with a filter applied.
What could be the problem? What is the prefered way to get the ModelBs referencing ModelA?
A:
If the ForeignKey is, as you describe in ModelB and you do mb = ModelB.objects.get(pk=prim_id) then the look up for the modela attribute is not a reverse lookup. you simply access the related object via mb.modela!
| Django reverse lookup by ForeignKey | I have a django project which has two apps, one is AppA and AppB. Now AppA has a model
ModelA which is referenced by the model ModelB in AppB, using modelA = models.ForeignKey(ModelA, related_name='tricky')
Now in my view for AppA, when it shows ModelA, I do a get_object_or_404(ModelA, pk=prim_id). Then I want to get all the ModelBs which have a Foreign Key pointing to ModelA.
Documentation says I should do a mb = ModelB.objects.get(pk=prim_id) then mb.modela_set.all()
But, it failed on the mb.modela_set, and it says "ModelB object has no attribute 'suchsuch'". Notice I added the related_name field to ForeignKey, so I tried with that as well, including mb.tricky.all() and mb.tricky_set.all() to no avail.
Oh, and I have specified a different manager for AppA where I do objects = MyManager() which returns the normal query but with a filter applied.
What could be the problem? What is the prefered way to get the ModelBs referencing ModelA?
| [
"If the ForeignKey is, as you describe in ModelB and you do mb = ModelB.objects.get(pk=prim_id) then the look up for the modela attribute is not a reverse lookup. you simply access the related object via mb.modela!\n"
] | [
5
] | [] | [] | [
"django",
"django_queryset",
"model",
"python"
] | stackoverflow_0004180120_django_django_queryset_model_python.txt |
Q:
Dynamic global variables assignment
I'm new in python and I'm having many troubles in using global instruction.
Here is a code example:
mouse = "a"
background = "b"
list_ab = [mouse, background]
def func ():
for item in list_ab:
global item # I want to modify the GLOBAL item, which is mouse
# and background.
item = "modified"
print mouse # must be "modified" not "a"
print background # must be "modified" not "b"
This is the problem. How can I solve it?
A:
Your problem is that Python works not the way you think.
So I will try to explain what's going on in your code, line by line.
mouse = "a"
Assigns the string "a" to the name mouse.
background = "b"
Assigns the string "b" to the name background.
list_ab = [mouse, background]
Assigns two objects, referenced by names mouse and background, to the list list_ab.
As we already know, they are constants "a" and "b". So you can just write:
list_ab = ["a", "b"]
Now the loop
for item in list_ab:
assigns each object in the list to the name item.
For the first loop iteration, it means item = "a".
The line
global item # I want to modify the GLOBAL item, which is mouse ad background
doesn't make sense, because it tries to tell Python that the name item is global, while there is no such global variable declared.
And for the most confusing behavior on the line
item = "modified"
you should just understand that while it assigns the string "modified" to the name item, strings "a" and "b" are still the same, and still assigned to the list list_ab (and names mouse and background, which you didn't touch either).
The name item itself lives only in the scope where it was declared, when the "for" loop ends, it's destructed.
It is also reassigned every iteration with the next item from the list_ab.
To sum it up:
If you want to assign "modified" string to the items in the list, do it directly:
list_ab[0] = "modified"
list_ab[1] = "modified"
If you need to change variable declared in the global scope, do this:
mouse = "a"
def func():
global mouse # tell Python that you want to work with global variable
mouse = "modified"
func()
print mouse # now mouse is "modified"
Example based on the first revision of the question:
Instead of
background = g_base("bg.jpg") # g_base class instance
mouse = g_base("mouse.png",alpha=1) # g_base class instance
imgs_to_load = [mouse, background]
def Image_loader (img):
# ..... code to load the image and convert it into pygame surface...
return img_load
def main ():
for image in img_to_load:
global image
image = Image_loader (img)
print image # if I print image, it is a pygame surface
print background # But here, outside the loop, image is still a g_base instance ?!?!
print mouse # " "
main()
You can do:
imgs_to_load = [g_base("bg.jpg"), g_base("mouse.png",alpha=1)] # list with a g_base class instances
def Image_loader(img):
# ..... code to load the image and convert it into pygame surface...
return img_load
def main ():
imgs_in_pygame_format = [] # create an empty list
for image in imgs_to_load:
loaded_image = Image_loader(image)
imgs_in_pygame_format.append(loaded_image) # add to the list
for image in imgs_in_pygame_format:
print image # every image in the list is a pygame surface
# or
print image[0]
print image[1]
main()
Or if you want to reference to images by name, you can put them into dictionary:
imgs_to_load = {}
imgs_to_load["bg"] = g_base("bg.jpg")
imgs_to_load["mouse"] = g_base("mouse.png",alpha=1)
imgs_in_pygame_format = {} # create a global dictionary for loaded images
def main ():
global imgs_in_pygame_format # import that global name into the local scope for write access
for name, data in imgs_to_load.items():
imgs_in_pygame_format[name] = Image_loader(data) # add to the dictionary
for image in imgs_in_pygame_format:
print image # every image in the dictionary is a pygame surface
# or
print imgs_in_pygame_format["bg"]
print imgs_in_pygame_format["mouse"]
main()
But most importantly, global variables are bad idea. The better solution would be to use a class:
def Image_loader(img):
# ..... code to load the image and convert it into pygame surface...
return img_load
class Image:
def __init__(self, image):
self.data = Image_loader(image)
def main ():
bg = Image(g_base("bg.jpg"))
mouse = Image(g_base("mouse.png",alpha=1))
print bg.data
print mouse.data
main()
For more examples see Python Tutorial.
Hope it helps, and welcome to StackOverflow!
A:
As I said in my comment to your question, list_ab does not contain references to mouse and background. You can simulate that to some degree in this case by putting their names in the list, like this:
mouse = "a"
background = "b"
list_ab = ['mouse', 'background']
def func():
for name in list_ab:
globals()[name] = "modified"
print mouse # must be "modified" not "a"
print background # must be "modified" not "b"
func()
# modified
# modified
globals() returns a dictionary-like object that represents the non-local name bindings at that point in your script/modules's execution. It's important to note that list_ab is not changed by the for loop in func(). Also you should be aware that this is only an illustration of one simple way to make your sample code work like you wanted, not of an especially good or generic way to accomplish such things.
A:
I am not sure what you are trying do to. The global keyword is intended to import a global name into the current scope, not to make a local name global.
A:
You are having two distinct problems and one of them occurs twice. The first is that you are attempting to use global on elements of a list which is useless. You can already do:
def func():
list_ab[0] = 'modified'
list_ab[1] = 'modified'
This will change the values which are referenced by list_ab which is further than your code is getting now. It works because you are not changing the binding represented by list_ab and so it doesn't need to be global. You can already read a global indexing and into it is just an item lookup and doesn't (in itself) overwrite any bindings. However it will not actually change which values are referenced by a and b
The second is that when you bind the first and second indices of list_ab to a and b, it creates entirely new bindings so that changing the values of the bindings in the list does nothing to change the values referenced by a and b. If you want to do that, you need to do it directly.
def func():
global a, b
a = 'modified'
b = 'modified'
You are running into the second problem again when you try to modify the elements of list_ab by iterating over them. You can see it more clearly with the code
def func():
list_ab = ['a', 'b']
for item in list_ab:
item = 'modified'
print list_ab # prints ['a', 'b']
Again, this occurs because you are creating a new binding to the value and then modifying that binding instead of the original one.
If you need to modify a list in place while iterating over it you can do
def func():
list_ab = ['a', 'b']
for i in xrange(len(list_ab)):
list_ab[i] = 'modified'
So as things currently stand to update a, b and list_ab, and keeping your current patterns (i.e. not introducing comprehensions), you need to do:
def func():
global a, b
for i in xrange(len(list_ab)):
list_ab[i] = 'modified'
a = 'modified'
b = 'modified'
print list_ab
print a, b
That looks pretty ugly. Why do you need to keep them as free variables and in a list? Isn't just a list good enough? If you need to access them by name then you can use a dictionary:
dict_ab = {'a': 'a', 'b': 'b'}
for key in dict_ab:
dict_ab[key] = modified
print dict_ab['a']
print dict_ab['b']
A:
The issue here is that you're trying to update variables in-place, but your functions return new instances. Try something like this:
def main ():
converted_images = []
for image in [mouse, background]:
converted_images.append(Image_loader(img))
# now re-assign the pygame surfaces to the old names
background, mouse = converted_images
And if you want to be especially concise, here's a one-liner that does the same thing:
background, mouse = [Image_loader(img) for img in [background, mouse]]
But really, if you only have two images, it might make more sense to do this explicitly:
background = Image_loader(background)
mouse = Image_loader(mouse)
A:
I'm not sure what you are trying to do either, but here's an example of using global:
value = 7
def display():
print value # global values are read-only any time
def increment():
global value # must declare global to write it
value += 1
def local():
value = 9 # this is a local value
print value
increment() # changes global value to 8
display() # displays it
local() # changes local value to 9 and displays it
print value # displays global value (still 8)
| Dynamic global variables assignment | I'm new in python and I'm having many troubles in using global instruction.
Here is a code example:
mouse = "a"
background = "b"
list_ab = [mouse, background]
def func ():
for item in list_ab:
global item # I want to modify the GLOBAL item, which is mouse
# and background.
item = "modified"
print mouse # must be "modified" not "a"
print background # must be "modified" not "b"
This is the problem. How can I solve it?
| [
"Your problem is that Python works not the way you think.\nSo I will try to explain what's going on in your code, line by line.\nmouse = \"a\"\n\nAssigns the string \"a\" to the name mouse.\nbackground = \"b\"\n\nAssigns the string \"b\" to the name background.\nlist_ab = [mouse, background]\n\nAssigns two objects,... | [
7,
5,
2,
2,
1,
0
] | [] | [] | [
"dynamic",
"global_variables",
"python",
"variable_assignment"
] | stackoverflow_0004180095_dynamic_global_variables_python_variable_assignment.txt |
Q:
Python classes - instances being overwritten?
When calling on a new instance of an object for a class I've created, my one instance of the class is just being overwritten. Why could this be? Example is below.
My class is defined as follows:
class my_class:
attribute = ""
examples = []
children = []
d = {}
def __init__(self, attribute, e):
self.attribute = attribute
self.examples = e
for ex in self.examples:
self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
I am making an initial instance as such:
root = my_class(some_attribute, data)
Then, I create another instance as such:
child = my_class(different_attribute, root.examples[somewhere_1:somewhere_2])
In the end, my initial 'root' is now somehow identical to 'child', where 'root' should have gone unchanged. Why is this!?
A:
I don't think you are doing with the initializations of attribute, examples, children and d what you think you are doing. Those are now attributes of the class, not of each instance. If you want each instance of the class to have its own attributes for attribute, examples, children and d, you should instead write:
class my_class:
def __init__(self, attribute, e):
self.attribute = attribute
self.examples = e
self.children = []
self.d = {}
for ex in self.examples:
self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
A:
When you define variables in the class definition, they are class attributes.
>>> my_class.examples is my_class().examples
True
(is checks that they are exactly the same object, not just equal. For example, True == 1, but True is not 1.)
As lists and dicts are mutable, this means that changes in my_class.examples or root.examples or child.examples will be reflected in all the others.
The way you should do such a thing is by setting it inside the constructor:
class my_class:
def __init__(self, attribute, e):
self.attribute = attribute
self.examples = e
self.children = []
self.d = {}
for ex in self.examples:
self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
You probably also wish to replace self.examples = e with self.examples = e[:] which will make a shallow copy of the list. Otherwise:
>>> data
[1, 2, 3, 4, 5]
>>> root = my_class(some_attribute, data)
>>> root.examples
[1, 2, 3, 4, 5]
>>> data += [6, 7]
>>> root.examples
[1, 2, 3, 4, 5, 6, 7]
>>> # ... because:
>>> root.examples is data
True
Side-note: the recommended Python style would have your class as MyClass. I recommend that you read PEP 8.
| Python classes - instances being overwritten? | When calling on a new instance of an object for a class I've created, my one instance of the class is just being overwritten. Why could this be? Example is below.
My class is defined as follows:
class my_class:
attribute = ""
examples = []
children = []
d = {}
def __init__(self, attribute, e):
self.attribute = attribute
self.examples = e
for ex in self.examples:
self.d[ex[-1]] = self.d.get(ex[-1], 0) + 1
I am making an initial instance as such:
root = my_class(some_attribute, data)
Then, I create another instance as such:
child = my_class(different_attribute, root.examples[somewhere_1:somewhere_2])
In the end, my initial 'root' is now somehow identical to 'child', where 'root' should have gone unchanged. Why is this!?
| [
"I don't think you are doing with the initializations of attribute, examples, children and d what you think you are doing. Those are now attributes of the class, not of each instance. If you want each instance of the class to have its own attributes for attribute, examples, children and d, you should instead writ... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0004180505_python.txt |
Q:
Make a Python log file only when there are errors (using logging module)
I'd like to use the "logging" module in Python to write errors to a log file. However, I want the file to only be created when there are errors. I use the following code:
import logging
f = 'test.conf'
logger = logging.getLogger("test_logger")
logger.setLevel(logging.INFO)
ch_file = logging.FileHandler("test_logger.conf")
ch_file.setLevel(logging.ERROR)
logger.addHandler(ch_file)
ch_file.close()
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.info("info")
logger.warn("warning")
#logger.error("error")
When logger.error("error") is uncommented, I expect the file "test_logger.conf" to be made with the error in it. However, when the line is commented out, I find that the test_logger.conf file is still made and is empty. How can I make it so this file is NOT made unless there are errors to report?
Thanks.
A:
You're in luck. The FileHandler has a delay parameter designed for this purpose:
ch_file = logging.FileHandler("test_logger.conf",delay=True)
| Make a Python log file only when there are errors (using logging module) | I'd like to use the "logging" module in Python to write errors to a log file. However, I want the file to only be created when there are errors. I use the following code:
import logging
f = 'test.conf'
logger = logging.getLogger("test_logger")
logger.setLevel(logging.INFO)
ch_file = logging.FileHandler("test_logger.conf")
ch_file.setLevel(logging.ERROR)
logger.addHandler(ch_file)
ch_file.close()
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.info("info")
logger.warn("warning")
#logger.error("error")
When logger.error("error") is uncommented, I expect the file "test_logger.conf" to be made with the error in it. However, when the line is commented out, I find that the test_logger.conf file is still made and is empty. How can I make it so this file is NOT made unless there are errors to report?
Thanks.
| [
"You're in luck. The FileHandler has a delay parameter designed for this purpose:\nch_file = logging.FileHandler(\"test_logger.conf\",delay=True)\n\n"
] | [
8
] | [] | [] | [
"error_logging",
"logging",
"python"
] | stackoverflow_0004180518_error_logging_logging_python.txt |
Q:
Do I use integer or float?
This is the model in Google App Engine:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.FloatProperty()
So, mCOUNT is integer and mWEIGHT is float. I calculate the age of the item like this:
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
But when I try a query like this:
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
# line 103
result.mCOUNT,
))
I get a TypeError on line 103 which is
result.mCOUNT,
TypeError: a float is required
Why would mCOUNT be float? By the way, the error is raised only if the item is not in the datastore and it is written for the first time by the else clause of the if loop.
Can you help me use the correct type? Thanks for your help.
-----------------------------------------------------
EDIT
I just noticed that I had %f for string formatting for mWEIGHT and changing that to %s seems to solve the problem (but I don't know why. Is it because mWEIGHT=None?):
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
# changing %f to %s appears to solve the problem.
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT if result.mWEIGHT is not None else 0.0,
result.mWEIGHT,
result.mCOUNT,
))
And here are some values:
mUNIQUE: A | mWEIGHT: 0.299954933969 | mCOUNT: 2 |
mUNIQUE: Z | mWEIGHT: 0.0 | mCOUNT: 1 | # With answer by TokenMacGuy
mUNIQUE: R | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
mUNIQUE: P | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
Any suggestions how I can add rep.mWEIGHT to the else clause?
------------------------------------------------------------
The entire code is below:
K = []
s = self.request.get('sentence')
K.append(s)
K = f2.remove_empty(K[0].split('\r\n'))
UNIQUES = f2.f2(K)
COUNTS = f2.lcount(K, UNIQUES)
C_RESULT = "no results yet"
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
rep = C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
self.response.out.write("<b>rep.UNIQUE: %s</b>: <br />"
# "rep.mCOUNT: %s <br />"
"rep.mWEIGHT: %s <br />"
# "C_RESULT: %s <br />"
# "rep: %s <br />"
# "utc_tuple: %s <br />"
# "mDATE0_epoch: %s <br />"
"rep.mDATE0: %s "
"age_hour: %s <br />"
#
% (rep.mUNIQUE,
# rep.mCOUNT,
rep.mWEIGHT,
# C_RESULT,
# rep,
# utc_tuple,
# mDATE0_epoch,
rep.mDATE0,
age_hour,
))
rep.put()
else:
rep = Rep()
rep.mCOUNT = COUNTS[i]
rep.mUNIQUE = UNIQUES[i]
rep.put()
self.response.out.write("<b>rep.UNIQUE: %s</b>: |"
"rep.mCOUNT: %s: <br />"
% (rep.mUNIQUE,
rep.mCOUNT,))
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
result.mCOUNT,
))
A:
It looks like you are occasionally not setting mWEIGHT. How about changing
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
result.mCOUNT,
))
to
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT if result.mWEIGHT is not None else 0.0,
result.mCOUNT,
))
| Do I use integer or float? | This is the model in Google App Engine:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.FloatProperty()
So, mCOUNT is integer and mWEIGHT is float. I calculate the age of the item like this:
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
But when I try a query like this:
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
# line 103
result.mCOUNT,
))
I get a TypeError on line 103 which is
result.mCOUNT,
TypeError: a float is required
Why would mCOUNT be float? By the way, the error is raised only if the item is not in the datastore and it is written for the first time by the else clause of the if loop.
Can you help me use the correct type? Thanks for your help.
-----------------------------------------------------
EDIT
I just noticed that I had %f for string formatting for mWEIGHT and changing that to %s seems to solve the problem (but I don't know why. Is it because mWEIGHT=None?):
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
# changing %f to %s appears to solve the problem.
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT if result.mWEIGHT is not None else 0.0,
result.mWEIGHT,
result.mCOUNT,
))
And here are some values:
mUNIQUE: A | mWEIGHT: 0.299954933969 | mCOUNT: 2 |
mUNIQUE: Z | mWEIGHT: 0.0 | mCOUNT: 1 | # With answer by TokenMacGuy
mUNIQUE: R | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
mUNIQUE: P | mWEIGHT: None | mCOUNT: 1 | # with %f changed to %s
Any suggestions how I can add rep.mWEIGHT to the else clause?
------------------------------------------------------------
The entire code is below:
K = []
s = self.request.get('sentence')
K.append(s)
K = f2.remove_empty(K[0].split('\r\n'))
UNIQUES = f2.f2(K)
COUNTS = f2.lcount(K, UNIQUES)
C_RESULT = "no results yet"
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
rep = C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
age1 = datetime.datetime.now() - rep.mDATE0
age_hour = float(age1.seconds) / 3600
rep.mWEIGHT = float((rep.mCOUNT - 1) / (age_hour + 2)**1.5)
self.response.out.write("<b>rep.UNIQUE: %s</b>: <br />"
# "rep.mCOUNT: %s <br />"
"rep.mWEIGHT: %s <br />"
# "C_RESULT: %s <br />"
# "rep: %s <br />"
# "utc_tuple: %s <br />"
# "mDATE0_epoch: %s <br />"
"rep.mDATE0: %s "
"age_hour: %s <br />"
#
% (rep.mUNIQUE,
# rep.mCOUNT,
rep.mWEIGHT,
# C_RESULT,
# rep,
# utc_tuple,
# mDATE0_epoch,
rep.mDATE0,
age_hour,
))
rep.put()
else:
rep = Rep()
rep.mCOUNT = COUNTS[i]
rep.mUNIQUE = UNIQUES[i]
rep.put()
self.response.out.write("<b>rep.UNIQUE: %s</b>: |"
"rep.mCOUNT: %s: <br />"
% (rep.mUNIQUE,
rep.mCOUNT,))
QUERY = Rep.all()
QUERY.filter("mAUTHOR =", user)
QUERY.order("-mWEIGHT")
RESULTS = QUERY.fetch(10)
for result in RESULTS:
self.response.out.write("mUNIQUE: <b>%s</b> | "
"mWEIGHT: %f | "
"mCOUNT: %s | <br />"
% (result.mUNIQUE,
result.mWEIGHT,
result.mCOUNT,
))
| [
"It looks like you are occasionally not setting mWEIGHT. How about changing\nfor result in RESULTS:\n self.response.out.write(\"mUNIQUE: <b>%s</b> | \"\n \"mWEIGHT: %f | \" \n \"mCOUNT: %s | <br />\" \n % (result.mUN... | [
1
] | [] | [] | [
"floating_point",
"google_app_engine",
"google_cloud_datastore",
"integer",
"python"
] | stackoverflow_0004180566_floating_point_google_app_engine_google_cloud_datastore_integer_python.txt |
Q:
Change Firefox Proxy settings from Python
Is there are way to change the Firefox Proxy settings from a Python script?
A:
Yes, you can edit the settings saved in the prefs.js file in the Firefox profile directory. Firefox has to be restarted for the settings to take effect, though.
This article details where the profile is stored, depending on the operating system:
http://support.mozilla.com/en-US/kb/profiles
| Change Firefox Proxy settings from Python | Is there are way to change the Firefox Proxy settings from a Python script?
| [
"Yes, you can edit the settings saved in the prefs.js file in the Firefox profile directory. Firefox has to be restarted for the settings to take effect, though.\nThis article details where the profile is stored, depending on the operating system:\nhttp://support.mozilla.com/en-US/kb/profiles\n"
] | [
2
] | [] | [] | [
"configure",
"firefox",
"proxy",
"python",
"settings"
] | stackoverflow_0004180550_configure_firefox_proxy_python_settings.txt |
Q:
Python urllib2 sending POST data
I am attempting to send POST data using urllib, but the problem is normally you urlencode your dictionary of fields and then you send that along with your request. But some of my fields that I have to send to the server are named the exact same name, so using a dictionary I end up deleting a lot of my data out of the dictionary because you can't have two keys with the same name and different data.
I have my request data in a string format in the correct syntax(eg. var=value&var=value2&...) and I try to send that along with my urllib request, but I get a bad request every time. Is there any other way to urlencode the data before sending so I don't get a 400?
A:
urllib.urlencode() can take a list of tuples, allowing you to specify multiple values for a parameter:
>>> urlencode([("var", "value"), ("var", "value2")])
'var=value&var=value2'
Or use a map with lists as values:
>>> p = {"var": ["value", "value2"], "var2": ["yetanothervalue"]}
>>> urlencode([(k, v) for k, vs in p.items() for v in vs])
'var=value&var=value2&var2=yetanothervalue'
You could even allow lists or strings as values, although it becomes less concise:
>>> p = {"var": ["value", "value2"], "var2": "yetanothervalue"}
>>> urlencode([(k, v) for k, vs in p.items()
... for v in isinstance(vs, list) and vs or [vs]])
'var=value&var=value2&var2=yetanothervalue'
| Python urllib2 sending POST data | I am attempting to send POST data using urllib, but the problem is normally you urlencode your dictionary of fields and then you send that along with your request. But some of my fields that I have to send to the server are named the exact same name, so using a dictionary I end up deleting a lot of my data out of the dictionary because you can't have two keys with the same name and different data.
I have my request data in a string format in the correct syntax(eg. var=value&var=value2&...) and I try to send that along with my urllib request, but I get a bad request every time. Is there any other way to urlencode the data before sending so I don't get a 400?
| [
"urllib.urlencode() can take a list of tuples, allowing you to specify multiple values for a parameter:\n>>> urlencode([(\"var\", \"value\"), (\"var\", \"value2\")])\n'var=value&var=value2'\n\nOr use a map with lists as values:\n>>> p = {\"var\": [\"value\", \"value2\"], \"var2\": [\"yetanothervalue\"]}\n>>> urlenc... | [
6
] | [] | [] | [
"http",
"python"
] | stackoverflow_0004180584_http_python.txt |
Q:
How to enable/disable toolbar items?
How do you make a gtk.ToolButton disabled so that it is 'greyed out'? Like this:
How do you make it enabled again?
A:
Use the set_sensitive method. If all you need is to disable/enable the button, you should call the method on the button; the argument should be True for enabling and False for disabling:
button.set_sensitive(True) # enables the button
button.set_sensitive(False) # disables the button
If you are dealing with actions, you may want to disable/enable the action associated to the button (this ensures that other widgets that may be related to the same actions, e.g. menu items, are enabled/disabled too), and call the set_sensitive method on the gtk.Action instead (although this is a different method from the gtk.Widget one, the usage is exactly the same; except that the button will not be enabled if the parent gtk.ActionGroup is disabled).
| How to enable/disable toolbar items? | How do you make a gtk.ToolButton disabled so that it is 'greyed out'? Like this:
How do you make it enabled again?
| [
"Use the set_sensitive method. If all you need is to disable/enable the button, you should call the method on the button; the argument should be True for enabling and False for disabling:\nbutton.set_sensitive(True) # enables the button\nbutton.set_sensitive(False) # disables the button\nIf you are dealing wit... | [
13
] | [] | [] | [
"gtk",
"pygtk",
"python",
"toolbar"
] | stackoverflow_0004179910_gtk_pygtk_python_toolbar.txt |
Q:
Trying to update a 3D graphs coordinates with matplotlib
I have a function that will graph a 3D sphere with matplotlib in tkinter. However, every successive time I call the function the performance when orbiting the sphere drops. Also the graph only updates after I try to orbit the sphere.
self.A is a variable that adjusts the size of the sphere.
My function:
def draw_fig(self):
self.ax = Axes3D(self.fig)
u = numpy.linspace(0, 2 * numpy.pi, 100)
v = numpy.linspace(0, numpy.pi, 100)
x = self.A * numpy.outer(numpy.cos(u), numpy.sin(v))
y = self.A * numpy.outer(numpy.sin(u), numpy.sin(v))
z = self.A * numpy.outer(numpy.ones(numpy.size(u)), numpy.cos(v))
t = self.ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightblue',linewidth=0)
A:
You should not regenerate each time all the data, but just modify your existing one.
Edit: Just move out of the calling draw_fig the axes building code
def __init__...
u = numpy.linspace(0, 2 * numpy.pi, 100)
v = numpy.linspace(0, numpy.pi, 100)
self.x = A * numpy.outer(numpy.cos(u), numpy.sin(v))
self.y = A * numpy.outer(numpy.sin(u), numpy.sin(v))
self.z = A * numpy.outer(numpy.ones(numpy.size(u)), numpy.cos(v))
self.ax = Axes3D(self.fig)
def draw_fig(self):
t = self.ax.plot_surface(self.x, self.y, self.z, rstride=4, cstride=4,color='lightblue',linewidth=0)
| Trying to update a 3D graphs coordinates with matplotlib | I have a function that will graph a 3D sphere with matplotlib in tkinter. However, every successive time I call the function the performance when orbiting the sphere drops. Also the graph only updates after I try to orbit the sphere.
self.A is a variable that adjusts the size of the sphere.
My function:
def draw_fig(self):
self.ax = Axes3D(self.fig)
u = numpy.linspace(0, 2 * numpy.pi, 100)
v = numpy.linspace(0, numpy.pi, 100)
x = self.A * numpy.outer(numpy.cos(u), numpy.sin(v))
y = self.A * numpy.outer(numpy.sin(u), numpy.sin(v))
z = self.A * numpy.outer(numpy.ones(numpy.size(u)), numpy.cos(v))
t = self.ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightblue',linewidth=0)
| [
"You should not regenerate each time all the data, but just modify your existing one.\nEdit: Just move out of the calling draw_fig the axes building code\ndef __init__...\n u = numpy.linspace(0, 2 * numpy.pi, 100)\n v = numpy.linspace(0, numpy.pi, 100)\n self.x = A * numpy.outer(numpy.cos(u), numpy.sin(... | [
4
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0004181097_matplotlib_python_tkinter.txt |
Q:
How can I parse html using lxml , python
I have some html file:
<html>
<body>
<span class="text">One</span>some text1</br>
<span class="cyrillic">Мир</span>some text2</br>
</body>
</html>
How can i get "some text1" and "some text2" using lxml with python?
A:
import lxml.html
doc = lxml.html.document_fromstring("""<html>
<body>
<span class="text">One</span>some text1</br>
<span class="cyrillic">Мир</span>some text2</br>
</body>
</html>
""")
txt1 = doc.xpath('/html/body/span[@class="text"]/following-sibling::text()[1]')
txt2 = doc.xpath('/html/body/span[@class="cyrillic"]/following-sibling::text()[1]')
A:
I use lxml for xml parsing, but I use BeautifulSoup for HTML. Here's a very quick/brief tour, ending with one solution to your question. Hope it helps.
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from BeautifulSoup import BeautifulSoup as soup
>>> stream = open('bs.html', 'r')
>>> doc = soup(stream.read())
>>> doc.body.span
<span class="text">One</span>
>>> doc.body.span.nextSibling
u'some text1'
>>> x = doc.findAll('span')
>>> for i in x:
... print unicode(i)
...
<span class="text">One</span>
<span class="cyrillic">Мир</span>
>>> x = doc('span')
>>> type(x)
<class 'BeautifulSoup.ResultSet'>
>>> for i in x:
... print unicode(i)
...
<span class="text">One</span>
<span class="cyrillic">Мир</span>
>>> for i in x:
... print i.nextSibling
...
some text1
some text2
>>>
| How can I parse html using lxml , python | I have some html file:
<html>
<body>
<span class="text">One</span>some text1</br>
<span class="cyrillic">Мир</span>some text2</br>
</body>
</html>
How can i get "some text1" and "some text2" using lxml with python?
| [
"import lxml.html\n\ndoc = lxml.html.document_fromstring(\"\"\"<html>\n <body>\n <span class=\"text\">One</span>some text1</br>\n <span class=\"cyrillic\">Мир</span>some text2</br>\n </body>\n</html>\n\"\"\")\n\ntxt1 = doc.xpath('/html/body/span[@class=\"text\"]/following-sibling::text()[1]')\ntxt2 = doc.xpath(... | [
6,
3
] | [] | [] | [
"lxml",
"parsing",
"python"
] | stackoverflow_0004180887_lxml_parsing_python.txt |
Q:
Best way to store a python time.struct_time in a mysql database
I am using python's feedparser module, to parse an RSS feed. Once parsed, feedparser returns dates in a python 9 tuple time format (time.struct_time).
I am want to store these values in my mysql database so I can later check the Last-Modified headers of the feed. It's import that if the times tuples are converted, that when converted back they stay the same, so I can later use them for comparison.
I tried this to convert the time tuple to datetime and then back, but it wasn't the same when converted back:
dt = datetime.fromtimestamp(time.mktime(struct))
time_tuple = dt.timetuple()
What do you think is the method to do this?
A:
Store the datetime as UTC in the database, along with the timezone. Convert back to a local time when pulling from the database if needed.
A:
I believe the reason why your method is not preserving the time tuple is because the is_dst value was changed. time.mktime respected the is_dst in struct, but dt.timetuple changes is_dst to -1.
One way to avoid this error would be to interprets the time tuple as representing a UTC time. That may not be strictly correct, but it may be good enough for your purposes.
In [1]: import datetime as dt
In [2]: import time
In [3]: import calendar
In [17]: time_tuple=(1970, 1, 1, 0, 0, 0, 3, 1, 1)
In [18]: timestamp=calendar.timegm(time_tuple)
In [19]: timestamp
Out[19]: 0
In [20]: date=dt.datetime.utcfromtimestamp(timestamp)
In [21]: date
Out[21]: datetime.datetime(1970, 1, 1, 0, 0)
In [22]: tuple(date.timetuple())
Out[22]: (1970, 1, 1, 0, 0, 0, 3, 1, -1)
PS. Here is an example showing how the method you posted might fail to preserve the time tuple. Suppose the remote server is in a locale where is_dst = 1, while is_dst = 0 in your locale:
In [11]: time_tuple=(1970, 1, 1, 0, 0, 0, 3, 1, 1)
In [12]: timestamp=time.mktime(time_tuple)
In [13]: timestamp
Out[13]: 14400.0
In [14]: date=dt.datetime.fromtimestamp(timestamp)
In [15]: date
Out[15]: datetime.datetime(1969, 12, 31, 23, 0)
In [16]: tuple(date.timetuple())
Out[16]: (1969, 12, 31, 23, 0, 0, 2, 365, -1)
| Best way to store a python time.struct_time in a mysql database | I am using python's feedparser module, to parse an RSS feed. Once parsed, feedparser returns dates in a python 9 tuple time format (time.struct_time).
I am want to store these values in my mysql database so I can later check the Last-Modified headers of the feed. It's import that if the times tuples are converted, that when converted back they stay the same, so I can later use them for comparison.
I tried this to convert the time tuple to datetime and then back, but it wasn't the same when converted back:
dt = datetime.fromtimestamp(time.mktime(struct))
time_tuple = dt.timetuple()
What do you think is the method to do this?
| [
"Store the datetime as UTC in the database, along with the timezone. Convert back to a local time when pulling from the database if needed.\n",
"I believe the reason why your method is not preserving the time tuple is because the is_dst value was changed. time.mktime respected the is_dst in struct, but dt.timetup... | [
1,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004180280_mysql_python.txt |
Q:
Python: Organization of user-defined exceptions in a complete project
I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.
I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):
/docs (Documentation)
/apidocs (generated API documentation)
/askindex (my application package)
/test (Unit tests directory)
test_utils.py
... (more tests)
/workers (various worker classes)
communicators.py
processes.py
threads.py
utils.py
main.py (contains the starting point)
data_objects.py (various objects used all around the application)
settings.py (settings of the application)
README.txt
I would like to implement my own Exception to use them in the modules of the 'workers' package for specific errors.
Where should I place these exceptions ? I know that I should have my own base exception which subclasses the standard Exception class and subclass it for my other exceptions. Should I create a new 'exceptions' module under 'workers' ? Put exception classes in the module in which they're raised ? In this case, where should I put my base class ? Is my application structure appropriated ?
I am new to exceptions in Python, so please excuse me if the answer is obvious...
A:
In general I've found with my own work that when I want a custom type of exception, it's specific to a particular module or package. If it's relevant to a module, I put it just in that module. I haven't yet found a case where it would be neater to have a module or package dedicated to exceptions.
Examples: if I have a jester module, with a class Juggler in it with a method juggle which can raise a DroppedBall (cue throwing rotten tomatoes or similar), the DroppedBall would be in the jester module. Then the crowd.Person instances could try watching the juggler and except jester.DroppedBall.
If I had a package food, with various modules in it, fruit, vegetable, etc. which all have an eat method (inherited from food.Foodstuff, doubtless), they might be able to raise a RottenException, which would naturally belong in the root of the food package: __init__.py.
| Python: Organization of user-defined exceptions in a complete project | I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.
I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):
/docs (Documentation)
/apidocs (generated API documentation)
/askindex (my application package)
/test (Unit tests directory)
test_utils.py
... (more tests)
/workers (various worker classes)
communicators.py
processes.py
threads.py
utils.py
main.py (contains the starting point)
data_objects.py (various objects used all around the application)
settings.py (settings of the application)
README.txt
I would like to implement my own Exception to use them in the modules of the 'workers' package for specific errors.
Where should I place these exceptions ? I know that I should have my own base exception which subclasses the standard Exception class and subclass it for my other exceptions. Should I create a new 'exceptions' module under 'workers' ? Put exception classes in the module in which they're raised ? In this case, where should I put my base class ? Is my application structure appropriated ?
I am new to exceptions in Python, so please excuse me if the answer is obvious...
| [
"In general I've found with my own work that when I want a custom type of exception, it's specific to a particular module or package. If it's relevant to a module, I put it just in that module. I haven't yet found a case where it would be neater to have a module or package dedicated to exceptions.\nExamples: if I h... | [
8
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0004181708_exception_exception_handling_python.txt |
Q:
What will be the upgrade path to Python 3.x for Google App Engine Applications?
What is required to make the transition to Python 3.x for Google App Engine?
I know Google App Engine requires the use of at least Python 2.5.
Is it possible to use Python 3.0 already on Google App Engine?
A:
It is impossible to currently use Python 3.x applications on Google App Engine. It's simply not supported, and I'd expect to see support for Java (or Perl, or PHP) before Python 3.x.
That said, the upgrade path is likely to be very simple from Python 2.5 to Python 3.x on App Engine. If/when the capability is added, as long as you've coded your application anticipating the changes in Python itself, it should be very straightforward. The heavy lifting has to be done by the Google Engineers. And you'll no doubt be able to keep your application at Python 2.5 for a long while after Python 3.0 is available.
A:
At least at the being, Guido was working closely with the team at Google who is building AppEngine. When this option does become available, you will have to edit your main XAML file.
I agree with Chris B. that Python 3.0 support may not be forthcoming too soon, but I'm not sure I agree that it will come sooner than Perl or PHP. At the Google I/O conference last year, they were very mum on what future languages they would support on AppEngine but they were pretty clear on the fact that they're actively exploring how to safely allow other code to run. One of the main reason they chose to support Python is that they due to it's dynamically compiled nature, they could support 3rd party library extensions with the minimal restriction that all add-ons must be in pure Python.
I wouldn't be surprised if Python 3.0 support was introduced sooner than new languages.
A:
The app.yaml syntax already supports multiple languages and multiple API versions, though only one of each (Python, API version 1) is currently supported. Presumably, one of those extension mechanisms will be used to specify that you want Python 3, and it'll be up to you to port your app over to work in Python 3, then change that setting.
A:
As it does not look like that google updates app engine to python 3 soon it might be worth to keep an eye on Jython. As of now they still work on 2.6, but that would already be better than 2.5.
| What will be the upgrade path to Python 3.x for Google App Engine Applications? | What is required to make the transition to Python 3.x for Google App Engine?
I know Google App Engine requires the use of at least Python 2.5.
Is it possible to use Python 3.0 already on Google App Engine?
| [
"It is impossible to currently use Python 3.x applications on Google App Engine. It's simply not supported, and I'd expect to see support for Java (or Perl, or PHP) before Python 3.x.\nThat said, the upgrade path is likely to be very simple from Python 2.5 to Python 3.x on App Engine. If/when the capability is ad... | [
5,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000625042_google_app_engine_python.txt |
Q:
Making Matplotlib run faster
Snippet:
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = self.prop * np.outer(np.cos(u), np.sin(v))
y = self.prop * np.outer(np.sin(u), np.sin(v))
z = self.prop * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=6, cstride=6,color='lightgreen',linewidth=0)
self.canvas.draw()
The above snippet graphs a sphere in tkinter using matplotlib. I've found that higher rstride and cstride values allow the graph to have a bit better performance. However, they give the sphere a weird ribbed shape. I was wondering what other things could be adjusted in the above code to help improve performance.
A:
Really, the problem is more within plot_surface. There are a lot of things that can be done to improve it. For instance, the shading takes a lot of time and just by changing one line:
colors = [color * (0.5 + norm(v) * 0.5) for v in shade]
to
colors = np.outer(0.5+norm(shade)*0.5,color)
within one of the functions used by plot_surface, I got a reduction of about 28% in the overall runtime. Why? The norm function (well, class kind of) is set-up for vectorization, but wasn't being used in that manner. I know that there are many such things within these functions that aren't very optimal. Changing the two lines:
for rs in np.arange(0, rows-1, rstride):
for cs in np.arange(0, cols-1, cstride):
to
for rs in xrange(0,rows-1,rstride):
for cs in xrange(0,cols-1,cstride):
in the plot_surface function itself gives another substantial improvement - now we're down 33% from the original runtime.
From what I've seen, the code isn't really written for efficiency so much as to just get it working from what I can tell - there are plenty of places where things which could be made to be more vectorized using Numpy and aren't. I'm afraid that what really is needed is some optimization of the matplotlib functions.
A:
At this point is the visualization package that has the bottleneck. The number of points are defined and constant.
Try if using psyco can speed up it (is only 32bit though).
A:
I'm not sure if it would help, but maybe you could try a different rendering backend for matplotlib. But maybe one of them will give you better performance.
http://matplotlib.sourceforge.net/faq/installing_faq.html#what-is-a-backend
| Making Matplotlib run faster | Snippet:
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = self.prop * np.outer(np.cos(u), np.sin(v))
y = self.prop * np.outer(np.sin(u), np.sin(v))
z = self.prop * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=6, cstride=6,color='lightgreen',linewidth=0)
self.canvas.draw()
The above snippet graphs a sphere in tkinter using matplotlib. I've found that higher rstride and cstride values allow the graph to have a bit better performance. However, they give the sphere a weird ribbed shape. I was wondering what other things could be adjusted in the above code to help improve performance.
| [
"Really, the problem is more within plot_surface. There are a lot of things that can be done to improve it. For instance, the shading takes a lot of time and just by changing one line:\ncolors = [color * (0.5 + norm(v) * 0.5) for v in shade]\n\nto\ncolors = np.outer(0.5+norm(shade)*0.5,color)\n\nwithin one of the f... | [
13,
1,
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0004181294_matplotlib_python_tkinter.txt |
Q:
Making maps and pathfinding AI
I want to retrace maps from google earth these maps would then be used for calculating fastest route from A to B as well as location probability defined by some factors. How would i go about doing these? My first thought is pygame and using some already made ones or using them as a template.
A:
I've worked on a routing application for a while. The most common algorithm for this is to start on both ends (start and finish) and move towards each other, traversing all possible methods of travel. The branches that meet in the middle will be your ideal path.
You can weight things appropriately, like speed limit, by setting checks in the code to only move x distance every time step.
These should do you:
Good graph traversal algorithm
Link
http://en.wikipedia.org/wiki/A*_search_algorithm/
Map Routing, a la Google Maps?
A:
Have you looked at Google Maps, rather than Google Earth? This has roads and a routing engine.
| Making maps and pathfinding AI | I want to retrace maps from google earth these maps would then be used for calculating fastest route from A to B as well as location probability defined by some factors. How would i go about doing these? My first thought is pygame and using some already made ones or using them as a template.
| [
"I've worked on a routing application for a while. The most common algorithm for this is to start on both ends (start and finish) and move towards each other, traversing all possible methods of travel. The branches that meet in the middle will be your ideal path.\nYou can weight things appropriately, like speed l... | [
4,
0
] | [] | [] | [
"path_finding",
"python"
] | stackoverflow_0004175287_path_finding_python.txt |
Q:
A trouble with python 'self' argument in functions
This is the code for a simple test:
class ECollector:
#error msg collector
#this class should be used as 'global'
msgs = []
def addmsg(self,msg):
self.msgs.append(msg)
def clear(self):
self.msgs = []
class test(ECollector):
dcodes = []
ECollector
def new(self):
ECollector.addmsg("test!")
And this is what I ran on the python console
(BTW, I'm using pyscripter 2.3 and Python 3.12)
>>>a = test()
>>>a.new()
and the following is what I got:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\...\test.py", line 14, in new
ECollector.addmsg("test!")
TypeError: addmsg() takes exactly 2 positional arguments (1 given)
I'm a newbie to python...and I'm rather confused about this whole thing;;;
I thought the 'self' argument is something you don't need to fill-up when calling a def function.
Please rescue this poor newbie from this troublesome 'phenomenon' by giving him solutions.
Thank you :)
A:
You have defined addmsg to be an instance method. You probably meant self.addmsg("test!") instead of ECollector.addmsg("test!").
A:
There's lots of things that might be wrong with this. lets start at the top. It looks like you are really just using ECollector as a namespace to group some functions. That's ok, but you want to make a call to ECollector.some_method you need to change things around a bit, by making those methods into class methods:
class ECollector:
"""error msg collector
this class should be used as 'global'"""
msgs = []
@classmethod
def addmsg(cls,msg):
cls.msgs.append(msg)
@classmethod
def clear(cls):
cls.msgs = []
This means that any time you invoke addmsg or clear, they get an implicit first argument of the class itself. In this particular way that i've converted it, each subclass will get its own msgs. If you want all of the subclasses to share a single msgs attribute, then you can change cls to ECollector
Also, you will want to change your subclass around just a little bit, because you are subclassing from ECollector, but then calling its methods directly. You can do this instead:
class test(ECollector):
dcodes = []
def new(self):
self.addmsg("test!")
A:
The way in which you are calling ECollector.addMsg looks like you're using it as a python static method, which means it won't pass through a "self" parameter (let me know if you're a newcomer to programming languages in general and don't understand what a static method is). However, my guess is that you want to use it as an instance method rather than as a static method.
Instead, you probably want to do it as follows:
self.addmsg("test!")
| A trouble with python 'self' argument in functions | This is the code for a simple test:
class ECollector:
#error msg collector
#this class should be used as 'global'
msgs = []
def addmsg(self,msg):
self.msgs.append(msg)
def clear(self):
self.msgs = []
class test(ECollector):
dcodes = []
ECollector
def new(self):
ECollector.addmsg("test!")
And this is what I ran on the python console
(BTW, I'm using pyscripter 2.3 and Python 3.12)
>>>a = test()
>>>a.new()
and the following is what I got:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\...\test.py", line 14, in new
ECollector.addmsg("test!")
TypeError: addmsg() takes exactly 2 positional arguments (1 given)
I'm a newbie to python...and I'm rather confused about this whole thing;;;
I thought the 'self' argument is something you don't need to fill-up when calling a def function.
Please rescue this poor newbie from this troublesome 'phenomenon' by giving him solutions.
Thank you :)
| [
"You have defined addmsg to be an instance method. You probably meant self.addmsg(\"test!\") instead of ECollector.addmsg(\"test!\").\n",
"There's lots of things that might be wrong with this. lets start at the top. It looks like you are really just using ECollector as a namespace to group some functions. That... | [
3,
2,
1
] | [] | [] | [
"arguments",
"function",
"python",
"python_3.x"
] | stackoverflow_0004182200_arguments_function_python_python_3.x.txt |
Q:
Python regular expression
str1 = abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>
We need the contents inside the h1 tag and h2 tag.
What is the best way to do that? Thanks
Thanks for the help!
A:
The best way if it needs to scale at all would be with something like BeautifulSoup.
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')
>>> soup.h1
<h1>The content we need</h1>
>>> soup.h1.text
u'The content we need'
>>> soup.h2
<h2>The content we need2</h2>
>>> soup.h2.text
u'The content we need2'
It could be done with a regular expression too but this is probably more what you want. A larger example of what you are wanting could be good. Without knowing quite what you're wanting to parse it's hard to help properly.
A:
First bit of advice: DON'T USE REGULAR EXPRESSIONS FOR HTML/XML PARSING!
Now that we've cleared that up, I'd suggest you look at Beautiful Soup. There are other SGML/XML/HTML parsers available for Python. However this one is the favorite for dealing with the sloppy "tag soup" that most of us find out in the real world. It doesn't require that the inputs be standards conformant nor well-formed. If your browser can manage to render it than Beautiful Soup can probably manage to parse it for you.
(Still tempted to use regular expressions for this task? Thinking "it can't be that bad, I just want to extract just what's in the <h1>...</h1> and <h2>...</h2> containers." and ... "I'll never need to handle any other corner cases" That way lies madness. The code you write based on that line of reasoning will be fragile. It'll work just well enough to pass your tests and then it will get worse and worse every time you need to fix "just one more thing." Seriously, import a real parser and use it).
| Python regular expression | str1 = abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>
We need the contents inside the h1 tag and h2 tag.
What is the best way to do that? Thanks
Thanks for the help!
| [
"The best way if it needs to scale at all would be with something like BeautifulSoup.\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')\n>>> soup.h1\n<h1>The content we need</h1>\n>>> soup.h1.text\nu'The content we need'\... | [
6,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004182331_python_regex.txt |
Q:
ld can't link with a main executable
On OSX 10.6.4 with i686-apple-darwin10-g++-4.2.1 compiling using TextMate and a Makefile which in the first place has been made für a Linux and I am trying to translate for OSX.
When compiling a c++ project I get the "can't link with a main executable" error:
g++ -Wall -g -I ~/svnX-Repository/axp-Projekte/xrlfupa/trunk/src/ -I ~/svnX-Repository/boost_1_44_0 -I /opt/local/var/macports/software/boost/1.44.0_0/opt/local/lib/ -I /opt/local/var/macports/software/gsl/1.14_0/opt/local/include/ -o xrfLibTest xrfLibTest.o excitFunctions.o xrfFunctions.o filterFunctions.o detectorFunctions.o -L/opt/local/var/macports/software/boost/1.44.0_0/opt/local/lib/ -L/opt/local/var/macports/software/gsl/1.14_0/opt/local/lib/ -lm -lxrlTUB -lboost_serialization -lgsl -lgslcblas # Debug 1
ld: in /usr/local/lib/libxrlTUB.so, can't link with a main executable
collect2: ld returned 1 exit status
make: *** [prog] Error 1
The library that is mentioned (libxrlTUB.so) is in its place (/usr/local/lib/libxrlTUB.so) but, possibly that is where the problem came from, the libxrlTUB.so has been compiled by myself beforehand as well.
The compile process went through, it was generated by swig, though there was a warning:
g++ -arch x86_64 -m32 -g -fpic -I /usr/include/python2.6 -c PyXrl_wrap.cxx
In function 'void SWIG_Python_AddErrorMsg(const char*)':
warning: format not a string literal and no format arguments
which, as far as I could find out, shouldnt be a problem. (Or is it?)
Unfortunately this whole thing is part of a project from the university. Actually I am supposed to write an X-ray-analysis script in python, which would be fine, if... well if I wouldn't be expected to use the librarys that are meant to result from this c++ project.
(Afterwards they should be used via import in python.)
I am not really experienced with c++, neither with compiling on OSX systems. So far I have been bothering with scipting (python, bash, etc). So Maybe I am just missing something simple. Hopefully someone can give me an hint where I can continue reading in order to deal with the above "can't link with a main executable" error...
Thanx in advance,
Liam
A:
The error message is telling you the problem—it is that /usr/local/lib/libxrlTUB.so is not a shared library; it's an executable. You can't link against an executable. Probably whatever build process you used for libxrlTUB.so didn't understand how to build shared libraries on the Mac (it's more suspect because .dylib is the correct extension to use.)
Take a look at Apple's documentation on compiling dynamic libraries. You can use file to make sure your output is of the correct type, for example:
% gcc -c foo.c
% gcc -dynamiclib foo.o -o foo.dylib
% file foo.dylib
foo.dylib: Mach-O 64-bit dynamically linked shared library x86_64
Without -dynamiclib you end up with an executable, which may be the problem you've run into.
| ld can't link with a main executable | On OSX 10.6.4 with i686-apple-darwin10-g++-4.2.1 compiling using TextMate and a Makefile which in the first place has been made für a Linux and I am trying to translate for OSX.
When compiling a c++ project I get the "can't link with a main executable" error:
g++ -Wall -g -I ~/svnX-Repository/axp-Projekte/xrlfupa/trunk/src/ -I ~/svnX-Repository/boost_1_44_0 -I /opt/local/var/macports/software/boost/1.44.0_0/opt/local/lib/ -I /opt/local/var/macports/software/gsl/1.14_0/opt/local/include/ -o xrfLibTest xrfLibTest.o excitFunctions.o xrfFunctions.o filterFunctions.o detectorFunctions.o -L/opt/local/var/macports/software/boost/1.44.0_0/opt/local/lib/ -L/opt/local/var/macports/software/gsl/1.14_0/opt/local/lib/ -lm -lxrlTUB -lboost_serialization -lgsl -lgslcblas # Debug 1
ld: in /usr/local/lib/libxrlTUB.so, can't link with a main executable
collect2: ld returned 1 exit status
make: *** [prog] Error 1
The library that is mentioned (libxrlTUB.so) is in its place (/usr/local/lib/libxrlTUB.so) but, possibly that is where the problem came from, the libxrlTUB.so has been compiled by myself beforehand as well.
The compile process went through, it was generated by swig, though there was a warning:
g++ -arch x86_64 -m32 -g -fpic -I /usr/include/python2.6 -c PyXrl_wrap.cxx
In function 'void SWIG_Python_AddErrorMsg(const char*)':
warning: format not a string literal and no format arguments
which, as far as I could find out, shouldnt be a problem. (Or is it?)
Unfortunately this whole thing is part of a project from the university. Actually I am supposed to write an X-ray-analysis script in python, which would be fine, if... well if I wouldn't be expected to use the librarys that are meant to result from this c++ project.
(Afterwards they should be used via import in python.)
I am not really experienced with c++, neither with compiling on OSX systems. So far I have been bothering with scipting (python, bash, etc). So Maybe I am just missing something simple. Hopefully someone can give me an hint where I can continue reading in order to deal with the above "can't link with a main executable" error...
Thanx in advance,
Liam
| [
"The error message is telling you the problem—it is that /usr/local/lib/libxrlTUB.so is not a shared library; it's an executable. You can't link against an executable. Probably whatever build process you used for libxrlTUB.so didn't understand how to build shared libraries on the Mac (it's more suspect because .d... | [
3
] | [] | [] | [
"c++",
"linker",
"macos",
"python",
"swig"
] | stackoverflow_0004179804_c++_linker_macos_python_swig.txt |
Q:
Formatting data quantity/capacity as string
A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB".
Are there any libraries that contain functionality to perform these conversions? In Python? In C? In pseudocode? Are there any best practises regarding the "most readable" form, such as number of significant characters, precision etc.?
A:
Here's a method that uses logarithms to determine the file size unit exponent:
from math import log
byteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
def filesizeformat(value):
exponent = int(log(value, 1024))
return "%.1f %s" % (float(value) / pow(1024, exponent), byteunits[exponent])
A:
I'm not sure that there is such a thing as best practice here, but there are some issues to consider. There are two questions you need to answer:
Is it appropriate to use base-1000 or base-1024 units?
When does precision start to become redundant?
Regarding the use of units, there are two guidelines. Firstly, always use the appropriate binary prefix so at least your users can figure out what is going on. Secondly, go with the principle of least surprise, and use whatever units are common in your problem domain. Thus, if you are reporting a file size on Windows, use base-1024 as that is what Windows uses. If you are reporting RAM sizes, use base-1024, as that is how RAM sizes are always reported. If you are reporting hard-disk sizes, use base-1000, as that is how they are commonly reported.
Regarding precision, I think this is a judgement call. I am loath to report more than one significant digit, because in any situation in which more precision is required, the number of bytes is the measure you want to report.
A:
Well, I usually go for this:
<?php
$factor = 0;
$units = ['B','KiB','MiB','GiB','TiB']
while( $size > 1024 && $factor<count($units-1)) {
$factor++;
$size /= 1024; // or $size >>= 10;
}
echo round($size,2).$units[$factor];
?>
Hope this helps!
| Formatting data quantity/capacity as string | A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB".
Are there any libraries that contain functionality to perform these conversions? In Python? In C? In pseudocode? Are there any best practises regarding the "most readable" form, such as number of significant characters, precision etc.?
| [
"Here's a method that uses logarithms to determine the file size unit exponent:\nfrom math import log\n\nbyteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')\n\ndef filesizeformat(value):\n exponent = int(log(value, 1024))\n return \"%.1f %s\" % (float(value) / pow(1024, exponent), byteun... | [
7,
1,
0
] | [] | [] | [
"c",
"python",
"readability",
"stringification"
] | stackoverflow_0004180980_c_python_readability_stringification.txt |
Q:
Python API to know the location
Is there an Python API from which if we input the ipadress, will we be able to know the location and place of the access
A:
Take a look at the MaxMind python API
A:
GeoDjango looks like it will suit your needs. I'm not sure exactly how you would want to direct users, but using the GeoIP API, you can do something like:
from django.contrib.gis.utils import GeoIP
g = GeoIP()
ip = request.META.get('REMOTE_ADDR', None)
if ip:
city = g.city(ip)['city']
print "ip:",ip," city:",city
The Docs explain things in great detail (http://docs.djangoproject.com/en/dev/ref/contrib/gis/); I would take a moment to read through them thoroughly
| Python API to know the location | Is there an Python API from which if we input the ipadress, will we be able to know the location and place of the access
| [
"Take a look at the MaxMind python API\n",
"GeoDjango looks like it will suit your needs. I'm not sure exactly how you would want to direct users, but using the GeoIP API, you can do something like:\nfrom django.contrib.gis.utils import GeoIP\n\ng = GeoIP()\n\nip = request.META.get('REMOTE_ADDR', None)\n\nif ip:\... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004181828_python.txt |
Q:
Using HTMLParser in Python efficiently
In response to Python regular expression I tried to implement an HTML parser using HTMLParser:
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagname == 'h1' or tagname == 'h2'
def handle_starttag(self, tag, attrs):
if self.is_relevant(tag):
self.in_heading = True
self.text = ''
def handle_endtag(self, tag):
if self.is_relevant(tag):
self.headings += [self.text]
self.text = None
def handle_data(self, data):
if self.text != None:
self.text += data
def handle_charref(self, name):
if self.text != None:
if name[0] == 'x':
self.text += chr(int(name[1:], 16))
else:
self.text += chr(int(name))
def handle_entityref(self, name):
if self.text != None:
print 'TODO: entity %s' % name
def extract_headings(text):
parser = ExtractHeadings()
parser.feed(text)
return parser.headings
print extract_headings('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')
print extract_headings('before<h1>Hello</h1>after')
Doing that I wondered if the API of this module is bad or if I didn't notice some important things. My questions are:
Why does my implementation of handle_charref have to be that complex? I would have expected that a good API passes the codepoint as a parameter, not either x6c or 72 as string.
Why doesn't the default implementation of handle_charref call handle_data with an appropriate string?
Why is there no utility implementation of handle_entityref that I could just call? It could be named handle_entityref_HTML4 and would lookup the entities defined in HTML 4 and then call handle_data on them.
If that API were provided, writing custom HTML parsers would be much easier. So where is my misunderstanding?
A:
Well, I tend to agree that it's a horrible oversight for the HTMLParser not to include code to convert HTML entity references into normal ASCII and/or other characters. I gather that this is remedied by completely different work in Python3.
However, it seems we can write a fairly simple entity handler something like:
import htmlentitydefs
def entity2char(x):
if x.startswith('&#x'):
# convert from hexadecimal
return chr(int(x[3:-1], 16))
elif x.startswith('&#'):
# convert from decimal
return chr(int(x[2:-1]))
elif x[1:-1] in htmlentitydefs.entitydefs:
return htmlentitydefs.entitydefs[x[1:-1]]
else:
return x
... though we should wrap to further input validation, and wrap the integer conversions in exception handling code.
But this should handle the very minimum in about 10 lines of code. Adding the exception handling would, perhaps, double its line count.
A:
Do you need to implement your own parser or you can get already created? Look at beautiful soup.
| Using HTMLParser in Python efficiently | In response to Python regular expression I tried to implement an HTML parser using HTMLParser:
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagname == 'h1' or tagname == 'h2'
def handle_starttag(self, tag, attrs):
if self.is_relevant(tag):
self.in_heading = True
self.text = ''
def handle_endtag(self, tag):
if self.is_relevant(tag):
self.headings += [self.text]
self.text = None
def handle_data(self, data):
if self.text != None:
self.text += data
def handle_charref(self, name):
if self.text != None:
if name[0] == 'x':
self.text += chr(int(name[1:], 16))
else:
self.text += chr(int(name))
def handle_entityref(self, name):
if self.text != None:
print 'TODO: entity %s' % name
def extract_headings(text):
parser = ExtractHeadings()
parser.feed(text)
return parser.headings
print extract_headings('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')
print extract_headings('before<h1>Hello</h1>after')
Doing that I wondered if the API of this module is bad or if I didn't notice some important things. My questions are:
Why does my implementation of handle_charref have to be that complex? I would have expected that a good API passes the codepoint as a parameter, not either x6c or 72 as string.
Why doesn't the default implementation of handle_charref call handle_data with an appropriate string?
Why is there no utility implementation of handle_entityref that I could just call? It could be named handle_entityref_HTML4 and would lookup the entities defined in HTML 4 and then call handle_data on them.
If that API were provided, writing custom HTML parsers would be much easier. So where is my misunderstanding?
| [
"Well, I tend to agree that it's a horrible oversight for the HTMLParser not to include code to convert HTML entity references into normal ASCII and/or other characters. I gather that this is remedied by completely different work in Python3.\nHowever, it seems we can write a fairly simple entity handler something ... | [
1,
0
] | [] | [] | [
"api",
"html_parsing",
"python"
] | stackoverflow_0004182521_api_html_parsing_python.txt |
Q:
Regular expression for checking
I am facing a problem with regular expression in Python.
The problem is that "Have to check a list and have to find out space containing strings."
The code is:
def testFunction(self, func):
a = re.findall(r'\w+[\ ]*\(.*?\)', func)
j = len(a)
print j
if j<=1:
return True
else:
s = re.findall(r"function *()", func) # cheking
t = len(s) # calculating the lenth
if t<=0:
return True
else:
return False
It returns all time true whether there is a gap or nor.
Example:it detects both "test()" & "test ()"
With in a word i am searching for a regular expression it will search for the gap inside a string.It will detect only "test ()" not "test()"
I tried with regex = r'\w+[\ ](.?)'
regex = r'^\s*'
but unfortunately does not work.
The work can be done by a regular expression that will differ between test(arg1) &
test (arg1).
Thanks.
A:
if all you care about is whether there are any spaces, why not just do something like
return " " in func
A:
how about this r'.*\s+.*'
A:
[\ ]* matches zero or more occurrences of space. Try [\ ]+ instead
A:
re.findall(r"function\ *\(\)", func)
A:
HI,
I have done this by
def testFunction(self, func):
#this function looks for a "function",looks for "function" both with and without parameter & with parameter
a = re.findall(r'\s', func)
j = len(a)
if j<=1:
return True
else:
return False
Thanks a lot :)
| Regular expression for checking | I am facing a problem with regular expression in Python.
The problem is that "Have to check a list and have to find out space containing strings."
The code is:
def testFunction(self, func):
a = re.findall(r'\w+[\ ]*\(.*?\)', func)
j = len(a)
print j
if j<=1:
return True
else:
s = re.findall(r"function *()", func) # cheking
t = len(s) # calculating the lenth
if t<=0:
return True
else:
return False
It returns all time true whether there is a gap or nor.
Example:it detects both "test()" & "test ()"
With in a word i am searching for a regular expression it will search for the gap inside a string.It will detect only "test ()" not "test()"
I tried with regex = r'\w+[\ ](.?)'
regex = r'^\s*'
but unfortunately does not work.
The work can be done by a regular expression that will differ between test(arg1) &
test (arg1).
Thanks.
| [
"if all you care about is whether there are any spaces, why not just do something like\nreturn \" \" in func\n\n",
"how about this r'.*\\s+.*'\n",
"[\\ ]* matches zero or more occurrences of space. Try [\\ ]+ instead\n",
"re.findall(r\"function\\ *\\(\\)\", func)\n\n",
"HI,\nI have done this by\n def testFu... | [
2,
2,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004182528_python_regex.txt |
Q:
python: Why this happen?
Below is the full log, the problem is in
23 dd.append(str(msg.get_json()))
I have some utf-8 returned from msg.get_json()...
Will str() try to encode the parameter using ASCII?
<type 'exceptions.UnicodeEncodeError'> Python 2.6.5: /usr/bin/python
Mon Nov 15 18:53:39 2010
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/usr/lib/pymodules/python2.6/flup/server/fcgi_base.py in run(self=<flup.server.fcgi_base.Request object>)
556 """Runs the handler, flushes the streams, and ends the request."""
557 try:
558 protocolStatus, appStatus = self.server.handler(self)
559 except:
560 traceback.print_exc(file=self.stderr)
protocolStatus undefined, appStatus undefined, self = <flup.server.fcgi_base.Request object>, self.server = <flup.server.fcgi.WSGIServer object>, self.server.handler = <bound method WSGIServer.handler of <flup.server.fcgi.WSGIServer object>>
/usr/lib/pymodules/python2.6/flup/server/fcgi_base.py in handler(self=<flup.server.fcgi.WSGIServer object>, req=<flup.server.fcgi_base.Request object>)
1116 try:
1117 try:
1118 result = self.application(environ, start_response)
1119 try:
1120 for data in result:
result = None, self = <flup.server.fcgi.WSGIServer object>, self.application = <function app>, environ = {'CONTENT_LENGTH': '81', 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8', 'DOCUMENT_ROOT': '/usr/local/nginx/html', 'DOCUMENT_URI': '/a.bc', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/json, text/javascript, */*', 'HTTP_ACCEPT_CHARSET': 'GB2312,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-cn,zh;q=0.5', 'HTTP_CACHE_CONTROL': 'no-cache', ...}, start_response = <function start_response>
/root/bc/trunk/python/server.py in app(environ={'CONTENT_LENGTH': '81', 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8', 'DOCUMENT_ROOT': '/usr/local/nginx/html', 'DOCUMENT_URI': '/a.bc', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/json, text/javascript, */*', 'HTTP_ACCEPT_CHARSET': 'GB2312,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-cn,zh;q=0.5', 'HTTP_CACHE_CONTROL': 'no-cache', ...}, start_response=<function start_response>)
125 config.dbg(cmd_name)
126 if cmd_name in cmd_map:
127 ret = cmd_map[cmd_name](q)
128 else:
129 ret = '{"' + cmd_name + '": {"result":"error"}}';
ret = 'cmd=get_room_updates&room=room2&connectionid=90125080-f0a6-11df-9dcb-0800279f1ca2', global cmd_map = {'chat_message': <function chat_message_cmd>, 'enter_room': <function enter_room_cmd>, 'get_room_updates': <function get_room_updates_cmd>, 'login_user': <function login_user_cmd>, 'register_user': <function register_user_cmd>}, cmd_name = 'get_room_updates', q = {'cmd': ['get_room_updates'], 'connectionid': ['90125080-f0a6-11df-9dcb-0800279f1ca2'], 'room': ['room2']}
/root/bc/trunk/python/server.py in get_room_updates_cmd(qs={'cmd': ['get_room_updates'], 'connectionid': ['90125080-f0a6-11df-9dcb-0800279f1ca2'], 'room': ['room2']})
88 room = config.gOnlineRooms[room_name]
89 conn = room.chat_connections[connectionid]
90 remaining = conn.get_pending_message()
91
92 return remaining
remaining = '[]', conn = <ChatConnection.ChatConnection instance>, conn.get_pending_message = <bound method ChatConnection.get_pending_message of <ChatConnection.ChatConnection instance>>
/root/bc/trunk/python/ChatConnection.py in get_pending_message(self=<ChatConnection.ChatConnection instance>)
21 for msg in self.pending_message:
22 txt = txt + msg.get_json() + ","
23 dd.append(str(msg.get_json()))
24
25 config.dbg("dd = " + str(dd))
dd = [], dd.append = <built-in method append of list object>, builtin str = <type 'str'>, msg = <Message.Message instance>, msg.get_json = <bound method Message.get_json of <Message.Message instance>>
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode characters in position 79-80: ordinal not in range(128)
args = ('ascii', u'{"id":"168", "username":"binc2", "ctime":"2010-11-15 18:53:37.165260", "body":"\u4e2d\u56fd", "room":"room2"}', 79, 81, 'ordinal not in range(128)')
encoding = 'ascii'
end = 81
message = ''
object = u'{"id":"168", "username":"binc2", "ctime":"2010-11-15 18:53:37.165260", "body":"\u4e2d\u56fd", "room":"room2"}'
reason = 'ordinal not in range(128)'
start = 79
A:
The problem is most likely ocurring in str(msg.get_json()) or one of the other places where you use str. The object contains unicode data and str is not built to handle unicode. You should be able to use json.dumps(msg.get_json()) instead. Alternatively use str(msg.get_json().decode('utf-8')).
A:
Try the unicode() builtin
unicode([object[, encoding[, errors]]])
...
Return the Unicode string version of object using one of the following modes:
If no optional parameters are given, unicode() will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings. More precisely, if object is a Unicode string or subclass it will return that Unicode string without any additional decoding applied.
| python: Why this happen? | Below is the full log, the problem is in
23 dd.append(str(msg.get_json()))
I have some utf-8 returned from msg.get_json()...
Will str() try to encode the parameter using ASCII?
<type 'exceptions.UnicodeEncodeError'> Python 2.6.5: /usr/bin/python
Mon Nov 15 18:53:39 2010
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/usr/lib/pymodules/python2.6/flup/server/fcgi_base.py in run(self=<flup.server.fcgi_base.Request object>)
556 """Runs the handler, flushes the streams, and ends the request."""
557 try:
558 protocolStatus, appStatus = self.server.handler(self)
559 except:
560 traceback.print_exc(file=self.stderr)
protocolStatus undefined, appStatus undefined, self = <flup.server.fcgi_base.Request object>, self.server = <flup.server.fcgi.WSGIServer object>, self.server.handler = <bound method WSGIServer.handler of <flup.server.fcgi.WSGIServer object>>
/usr/lib/pymodules/python2.6/flup/server/fcgi_base.py in handler(self=<flup.server.fcgi.WSGIServer object>, req=<flup.server.fcgi_base.Request object>)
1116 try:
1117 try:
1118 result = self.application(environ, start_response)
1119 try:
1120 for data in result:
result = None, self = <flup.server.fcgi.WSGIServer object>, self.application = <function app>, environ = {'CONTENT_LENGTH': '81', 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8', 'DOCUMENT_ROOT': '/usr/local/nginx/html', 'DOCUMENT_URI': '/a.bc', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/json, text/javascript, */*', 'HTTP_ACCEPT_CHARSET': 'GB2312,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-cn,zh;q=0.5', 'HTTP_CACHE_CONTROL': 'no-cache', ...}, start_response = <function start_response>
/root/bc/trunk/python/server.py in app(environ={'CONTENT_LENGTH': '81', 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8', 'DOCUMENT_ROOT': '/usr/local/nginx/html', 'DOCUMENT_URI': '/a.bc', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/json, text/javascript, */*', 'HTTP_ACCEPT_CHARSET': 'GB2312,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-cn,zh;q=0.5', 'HTTP_CACHE_CONTROL': 'no-cache', ...}, start_response=<function start_response>)
125 config.dbg(cmd_name)
126 if cmd_name in cmd_map:
127 ret = cmd_map[cmd_name](q)
128 else:
129 ret = '{"' + cmd_name + '": {"result":"error"}}';
ret = 'cmd=get_room_updates&room=room2&connectionid=90125080-f0a6-11df-9dcb-0800279f1ca2', global cmd_map = {'chat_message': <function chat_message_cmd>, 'enter_room': <function enter_room_cmd>, 'get_room_updates': <function get_room_updates_cmd>, 'login_user': <function login_user_cmd>, 'register_user': <function register_user_cmd>}, cmd_name = 'get_room_updates', q = {'cmd': ['get_room_updates'], 'connectionid': ['90125080-f0a6-11df-9dcb-0800279f1ca2'], 'room': ['room2']}
/root/bc/trunk/python/server.py in get_room_updates_cmd(qs={'cmd': ['get_room_updates'], 'connectionid': ['90125080-f0a6-11df-9dcb-0800279f1ca2'], 'room': ['room2']})
88 room = config.gOnlineRooms[room_name]
89 conn = room.chat_connections[connectionid]
90 remaining = conn.get_pending_message()
91
92 return remaining
remaining = '[]', conn = <ChatConnection.ChatConnection instance>, conn.get_pending_message = <bound method ChatConnection.get_pending_message of <ChatConnection.ChatConnection instance>>
/root/bc/trunk/python/ChatConnection.py in get_pending_message(self=<ChatConnection.ChatConnection instance>)
21 for msg in self.pending_message:
22 txt = txt + msg.get_json() + ","
23 dd.append(str(msg.get_json()))
24
25 config.dbg("dd = " + str(dd))
dd = [], dd.append = <built-in method append of list object>, builtin str = <type 'str'>, msg = <Message.Message instance>, msg.get_json = <bound method Message.get_json of <Message.Message instance>>
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode characters in position 79-80: ordinal not in range(128)
args = ('ascii', u'{"id":"168", "username":"binc2", "ctime":"2010-11-15 18:53:37.165260", "body":"\u4e2d\u56fd", "room":"room2"}', 79, 81, 'ordinal not in range(128)')
encoding = 'ascii'
end = 81
message = ''
object = u'{"id":"168", "username":"binc2", "ctime":"2010-11-15 18:53:37.165260", "body":"\u4e2d\u56fd", "room":"room2"}'
reason = 'ordinal not in range(128)'
start = 79
| [
"The problem is most likely ocurring in str(msg.get_json()) or one of the other places where you use str. The object contains unicode data and str is not built to handle unicode. You should be able to use json.dumps(msg.get_json()) instead. Alternatively use str(msg.get_json().decode('utf-8')).\n",
"Try the unico... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004183631_python.txt |
Q:
str to time in python
time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"
How to convert the above from string to time stamp?
I need to subtract the above timestamps time2-time1.
A:
For Python 2.5+
from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) -
datetime.strptime(time1, format)
# 1 day, 0:00:00
Edit: for Python 2.4
import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) -
time.mktime(time.strptime(time1, format))
# 86400.0
A:
>>> t1 = datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
>>> t2 = datetime.strptime(time2, "%Y-%m-%d %H:%M:%S")
>>> t2-t1
datetime.timedelta(1)
>>> (t2-t1).days
1
>>> (t2-t1).seconds
0
A:
If you're stuck on Python 2.4 system like me:
from time import strptime
from datetime import datetime
str_to_datetime = lambda st: datetime(*strptime(st, '%Y-%m-%d %H:%M:%S')[:6])
str_to_datetime('2010-04-20 10:07:30')
Otherwise datetime.strptime() will work just fine.
| str to time in python | time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"
How to convert the above from string to time stamp?
I need to subtract the above timestamps time2-time1.
| [
"For Python 2.5+\nfrom datetime import datetime\nformat = '%Y-%m-%d %H:%M:%S'\nprint datetime.strptime(time2, format) - \n datetime.strptime(time1, format)\n# 1 day, 0:00:00\n\nEdit: for Python 2.4\nimport time\nformat = '%Y-%m-%d %H:%M:%S'\nprint time.mktime(time.strptime(time2, format)) - \n time.mk... | [
24,
3,
3
] | [
"import time\n\ntime1 = \"2010-04-20 10:07:30\"\n\ntime_tuple = time.strptime(time1, \"%Y-%m-%d %H:%M:%S\")\n\ntimestamp = time.mktime(time_tuple)\n\n"
] | [
-1
] | [
"datetime",
"python",
"strptime"
] | stackoverflow_0004183793_datetime_python_strptime.txt |
Q:
Data insertion error: invalid literal for int() with base 10
I'm using Django-nonrel on Google App Engine. I'm trying to add a row to the database but I get this error when trying to use save():
invalid literal for int() with base 10
Here's my code:
views.py
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import SayForm
from models import Saying, Category
import datetime
def say_something(request):
if request.method == 'POST':
form = SayForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
content = cd['content']
category_temp = "Uncategorized"
category = Category.objects.get(name = category_temp)
added_date = datetime.datetime.now()
added_user = request.user
saying = Saying(content, category, added_date, added_user)
saying.save()
return HttpResponseRedirect('/contribute/success')
else:
form = SayForm()
return render_to_response('say_form.html', {'form' : form})
models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length = 50)
def __unicode__(self):
return self.name
class Saying(models.Model):
content = models.CharField(max_length = 160)
category = models.ForeignKey(Category)
added_date = models.DateField()
added_user = models.ForeignKey(User)
forms.py
from django import forms
class SayForm(forms.Form):
content = forms.CharField(widget = forms.Textarea)
def clean_message(self):
content = self.cleaned_data['content']
num_characters = len(content)
if num_characters > 160:
raise forms.ValidationError("Please limit your saying to 160 characters only.")
num_words = len(content.split())
if num_words < 4:
raise forms.ValidationError("This doesn't make sense. Say something longer.")
return content
Edit: here's the backtrace
Traceback: File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/core/handlers/base.py"
in get_response
107. response = callback(request,
*callback_args, **callback_kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/contrib/auth/decorators.py"
in _wrapped_view
25. return view_func(request, *args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/core/views.py"
in say_something
36. saying.save()
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save
452. self.save_base(using=using,
force_insert=force_insert,
force_update=force_update)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save_base
550. for f in meta.local_fields]
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_save
280. return self.get_db_prep_value(value,
connection=connection, prepared=False)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
53. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_value
492. return connection.ops.value_to_db_auto(value)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/djangotoolbox/db/base.py"
in value_to_db_auto
68. return super(NonrelDatabaseOperations,
self).value_to_db_auto(value)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/backends/init.py"
in value_to_db_auto
485. return int(value)
Exception Type: ValueError at
/contribute/ Exception Value: invalid
literal for int() with base 10: 'test'
My gut feeling tells me that the problem lies somewhere around how I save the object to the database. Maybe the foreign key part? I can't pinpoint the problem since I just started learning Django recently. Does this problem have anything to do with Django-nonrel using GAE's backend? Can anyone tell me where I went wrong here?
A:
The problem is here:
saying = Saying(content, category, added_date, added_user)
You've forgotten that Django adds an automatic id field to the model definition. If you did this in the shell, then printed saying.__dict__, you would see that the content has been assigned to id, the category to content, and so on.
Instead, always use keyword arguments when instantiating a model:
saying = Saying(content=content,
category=category,
added_date=added_date,
added_user=added_user)
A:
Creating an instance like this will set the primary key of your model to content:
saying = Saying(content, category, added_date, added_user)
Which won't work, because your model has a numeric primary key, as do all models by default unless you explicitly tell it to use some other field for the primary key. When Django tries to call int() on the value to cast it to integer, it crashes with a type error.
You should instead use keyword arguments, like this:
saying = Saying(content = content, ... = ...)
The idiomatic way to do this, as you want to save the object anyway:
saying = Saying.objects.create(content = content, ... = ..)
| Data insertion error: invalid literal for int() with base 10 | I'm using Django-nonrel on Google App Engine. I'm trying to add a row to the database but I get this error when trying to use save():
invalid literal for int() with base 10
Here's my code:
views.py
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import SayForm
from models import Saying, Category
import datetime
def say_something(request):
if request.method == 'POST':
form = SayForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
content = cd['content']
category_temp = "Uncategorized"
category = Category.objects.get(name = category_temp)
added_date = datetime.datetime.now()
added_user = request.user
saying = Saying(content, category, added_date, added_user)
saying.save()
return HttpResponseRedirect('/contribute/success')
else:
form = SayForm()
return render_to_response('say_form.html', {'form' : form})
models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length = 50)
def __unicode__(self):
return self.name
class Saying(models.Model):
content = models.CharField(max_length = 160)
category = models.ForeignKey(Category)
added_date = models.DateField()
added_user = models.ForeignKey(User)
forms.py
from django import forms
class SayForm(forms.Form):
content = forms.CharField(widget = forms.Textarea)
def clean_message(self):
content = self.cleaned_data['content']
num_characters = len(content)
if num_characters > 160:
raise forms.ValidationError("Please limit your saying to 160 characters only.")
num_words = len(content.split())
if num_words < 4:
raise forms.ValidationError("This doesn't make sense. Say something longer.")
return content
Edit: here's the backtrace
Traceback: File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/core/handlers/base.py"
in get_response
107. response = callback(request,
*callback_args, **callback_kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/contrib/auth/decorators.py"
in _wrapped_view
25. return view_func(request, *args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/core/views.py"
in say_something
36. saying.save()
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save
452. self.save_base(using=using,
force_insert=force_insert,
force_update=force_update)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save_base
550. for f in meta.local_fields]
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_save
280. return self.get_db_prep_value(value,
connection=connection, prepared=False)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
53. return func(*args, **kwargs)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_value
492. return connection.ops.value_to_db_auto(value)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/djangotoolbox/db/base.py"
in value_to_db_auto
68. return super(NonrelDatabaseOperations,
self).value_to_db_auto(value)
File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/backends/init.py"
in value_to_db_auto
485. return int(value)
Exception Type: ValueError at
/contribute/ Exception Value: invalid
literal for int() with base 10: 'test'
My gut feeling tells me that the problem lies somewhere around how I save the object to the database. Maybe the foreign key part? I can't pinpoint the problem since I just started learning Django recently. Does this problem have anything to do with Django-nonrel using GAE's backend? Can anyone tell me where I went wrong here?
| [
"The problem is here:\nsaying = Saying(content, category, added_date, added_user)\n\nYou've forgotten that Django adds an automatic id field to the model definition. If you did this in the shell, then printed saying.__dict__, you would see that the content has been assigned to id, the category to content, and so on... | [
5,
3
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0004183702_django_django_nonrel_google_app_engine_python.txt |
Q:
Python Traits UI (Enthought)
I am working with some code that uses Traits UI to show a dialog from which the user is able to select two files:
class Files(HasTraits):
filename_1 = File(exists=True)
filename_2 = File(exists=True)
traits_ui = View(
'filename_1', 'filename_2',
title = 'Select Geometry Files',
buttons = ['OK', 'Cancel']
)
files = Files()
ui = files.edit_traits(kind='modal')
When editing the filename_1 or filename_2 values, a file chooser dialog is displayed with the title ‘Save As’. I’ve been asked to change the title to ‘Open’ or even ‘Select File’. Unfortunately, I can’t seem to find out how I can change this. Can anyone help?
A:
At some point after Traits 3.2, a new trait was added to the FileEditor ToolkitEditorFactory that enables you set whether editing the trait is an 'open' or 'save' dialog. Try this:
from enthought.traits.ui.api import FileEditor
save_file_editor = FileEditor(dialog_style='save')
class Files(HasTraits):
filename_1 = File(exists=True)
filename_2 = File(exists=True)
traits_ui = View(
Item('filename_1', editor=save_file_editor),
Item('filename_2', editor=save_file_editor),
title = 'Select Geometry Files',
buttons = ['OK', 'Cancel']
)
files = Files()
ui = files.edit_traits(kind='modal')
| Python Traits UI (Enthought) | I am working with some code that uses Traits UI to show a dialog from which the user is able to select two files:
class Files(HasTraits):
filename_1 = File(exists=True)
filename_2 = File(exists=True)
traits_ui = View(
'filename_1', 'filename_2',
title = 'Select Geometry Files',
buttons = ['OK', 'Cancel']
)
files = Files()
ui = files.edit_traits(kind='modal')
When editing the filename_1 or filename_2 values, a file chooser dialog is displayed with the title ‘Save As’. I’ve been asked to change the title to ‘Open’ or even ‘Select File’. Unfortunately, I can’t seem to find out how I can change this. Can anyone help?
| [
"At some point after Traits 3.2, a new trait was added to the FileEditor ToolkitEditorFactory that enables you set whether editing the trait is an 'open' or 'save' dialog. Try this:\nfrom enthought.traits.ui.api import FileEditor \n\nsave_file_editor = FileEditor(dialog_style='save')\n\nclass Files(HasTraits):\n... | [
3
] | [] | [] | [
"enthought",
"python",
"traits",
"user_interface"
] | stackoverflow_0001867194_enthought_python_traits_user_interface.txt |
Q:
jquery: how to decode the stringized utf-8 character?
My python server uses json.dumps() to dump the json object into the string, but it also converts the binary utf-8 code which is not ascii, into the stringized thing, like "\u4e2d". So what my client see is this string, is there any api to convert "\u4e2d" back to utf-8 character?
A:
In jQuery you can use $.parseJSON to decode a JSON-formatted object. That includes decoding encoded characters. Using dataType: 'json' with $.ajax (or $.post) or using $.getJSON will do that for you if you are trying to make AJAX requests.
| jquery: how to decode the stringized utf-8 character? | My python server uses json.dumps() to dump the json object into the string, but it also converts the binary utf-8 code which is not ascii, into the stringized thing, like "\u4e2d". So what my client see is this string, is there any api to convert "\u4e2d" back to utf-8 character?
| [
"In jQuery you can use $.parseJSON to decode a JSON-formatted object. That includes decoding encoded characters. Using dataType: 'json' with $.ajax (or $.post) or using $.getJSON will do that for you if you are trying to make AJAX requests.\n"
] | [
1
] | [] | [] | [
"javascript",
"jquery",
"python"
] | stackoverflow_0004184208_javascript_jquery_python.txt |
Q:
Unable to install and build PyAudio
I've build and installed PortAudio using this tarball: 'pa_stable_v19_20071207.tar.gz'
After this step, when I'm trying to install PyAudio via the tarball from this URL:
http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.4.tar.gz
I'm getting the following error. What might be going wrong in this case?
enter code here
root@carmack:~/Desktop/PyAudio-0.2.4# python setup.py install
running install
running build
running build_py
running build_ext
building '_portaudio' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/_portaudiomodule.c -o build/temp.linux-i686-2.6 /src/_portaudiomodule.o -fno-strict-aliasing
src/_portaudiomodule.c:30:20: error: Python.h: No such file or directory
In file included from src/_portaudiomodule.c:32:
src/_portaudiomodule.h:33: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:36: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:40: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:43: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:47: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:50: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:53: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:56: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:59: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:63: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:69: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:72: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:77: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:80: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:83: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:86: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:92: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:95: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:98: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:101: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:104: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:107: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:110: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:115: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:118: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:121: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:124: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:71: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘paMethods’
src/_portaudiomodule.c:165: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c:172: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:186: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:200: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:214: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:228: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:242: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:256: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:271: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:285: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:317: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_paDeviceInfo_antiset’:
src/_portaudiomodule.c:321: warning: implicit declaration of function ‘PyErr_SetString’
src/_portaudiomodule.c:321: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c:321: error: (Each undeclared identifier is reported only once
src/_portaudiomodule.c:321: error: for each function it appears in.)
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:326: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paDeviceInfo_getseters’
src/_portaudiomodule.c: In function ‘_pyAudio_paDeviceInfo_dealloc’:
src/_portaudiomodule.c:394: error: ‘_pyAudio_paDeviceInfo’ has no member named ‘devInfo’
src/_portaudiomodule.c:397: error: ‘_pyAudio_paDeviceInfo’ has no member named ‘ob_type’
src/_portaudiomodule.c:397: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:397: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:400: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paDeviceInfoType’
src/_portaudiomodule.c: In function ‘_create_paDeviceInfo_object’:
src/_portaudiomodule.c:448: warning: implicit declaration of function ‘PyObject_New’
src/_portaudiomodule.c:448: error: expected expression before ‘_pyAudio_paDeviceInfo’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:464: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c:470: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:484: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:498: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:512: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:526: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:540: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:556: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_paHostApiInfo_antiset’:
src/_portaudiomodule.c:560: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c: In function ‘_pyAudio_paHostApiInfo_dealloc’:
src/_portaudiomodule.c:569: error: ‘_pyAudio_paHostApiInfo’ has no member named ‘apiInfo’
src/_portaudiomodule.c:572: error: ‘_pyAudio_paHostApiInfo’ has no member named ‘ob_type’
src/_portaudiomodule.c:572: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:572: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:575: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paHostApiInfo_getseters’
src/_portaudiomodule.c:615: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paHostApiInfoType’
src/_portaudiomodule.c: In function ‘_create_paHostApiInfo_object’:
src/_portaudiomodule.c:663: error: expected expression before ‘_pyAudio_paHostApiInfo’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:908: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c: In function ‘_is_open’:
src/_portaudiomodule.c:921: error: ‘_pyAudio_Stream’ has no member named ‘is_open’
src/_portaudiomodule.c: In function ‘_cleanup_Stream_object’:
src/_portaudiomodule.c:927: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:928: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:929: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:932: error: ‘_pyAudio_Stream’ has no member named ‘streamInfo’
src/_portaudiomodule.c:933: error: ‘_pyAudio_Stream’ has no member named ‘streamInfo’
src/_portaudiomodule.c:935: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:936: warning: implicit declaration of function ‘free’
src/_portaudiomodule.c:936: warning: incompatible implicit declaration of built-in function ‘free’
src/_portaudiomodule.c:936: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:937: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:940: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:941: warning: incompatible implicit declaration of built-in function ‘free’
src/_portaudiomodule.c:941: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:942: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:946: error: ‘_pyAudio_Stream’ has no member named ‘is_open’
src/_portaudiomodule.c: In function ‘_pyAudio_Stream_dealloc’:
src/_portaudiomodule.c:956: error: ‘_pyAudio_Stream’ has no member named ‘ob_type’
src/_portaudiomodule.c:956: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:956: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:960: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:984: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1009: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1034: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1061: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_Stream_antiset’:
src/_portaudiomodule.c:1065: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:1070: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_Stream_getseters’
src/_portaudiomodule.c:1098: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_StreamType’
src/_portaudiomodule.c: In function ‘_create_Stream_object’:
src/_portaudiomodule.c:1146: error: expected expression before ‘_pyAudio_Stream’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:1162: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1171: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1172: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1184: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1206: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1218: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1245: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1272: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1329: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1361: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1387: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1416: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1445: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1473: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1732: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1749: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1772: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1847: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1848: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1890: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1891: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘u’
src/_portaudiomodule.c:1933: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1972: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2019: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2064: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2098: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2126: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2198: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2288: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2313: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2346: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘init_portaudio’
error: command 'gcc' failed with exit status 1
A:
src/_portaudiomodule.c:30:20: error: Python.h: No such file or directory
You forgot to install the Python development files.
| Unable to install and build PyAudio | I've build and installed PortAudio using this tarball: 'pa_stable_v19_20071207.tar.gz'
After this step, when I'm trying to install PyAudio via the tarball from this URL:
http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.4.tar.gz
I'm getting the following error. What might be going wrong in this case?
enter code here
root@carmack:~/Desktop/PyAudio-0.2.4# python setup.py install
running install
running build
running build_py
running build_ext
building '_portaudio' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/_portaudiomodule.c -o build/temp.linux-i686-2.6 /src/_portaudiomodule.o -fno-strict-aliasing
src/_portaudiomodule.c:30:20: error: Python.h: No such file or directory
In file included from src/_portaudiomodule.c:32:
src/_portaudiomodule.h:33: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:36: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:40: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:43: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:47: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:50: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:53: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:56: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:59: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:63: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:69: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:72: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:77: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:80: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:83: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:86: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:92: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:95: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:98: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:101: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:104: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:107: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:110: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:115: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:118: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:121: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.h:124: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:71: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘paMethods’
src/_portaudiomodule.c:165: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c:172: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:186: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:200: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:214: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:228: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:242: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:256: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:271: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:285: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:317: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_paDeviceInfo_antiset’:
src/_portaudiomodule.c:321: warning: implicit declaration of function ‘PyErr_SetString’
src/_portaudiomodule.c:321: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c:321: error: (Each undeclared identifier is reported only once
src/_portaudiomodule.c:321: error: for each function it appears in.)
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:326: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paDeviceInfo_getseters’
src/_portaudiomodule.c: In function ‘_pyAudio_paDeviceInfo_dealloc’:
src/_portaudiomodule.c:394: error: ‘_pyAudio_paDeviceInfo’ has no member named ‘devInfo’
src/_portaudiomodule.c:397: error: ‘_pyAudio_paDeviceInfo’ has no member named ‘ob_type’
src/_portaudiomodule.c:397: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:397: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:400: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paDeviceInfoType’
src/_portaudiomodule.c: In function ‘_create_paDeviceInfo_object’:
src/_portaudiomodule.c:448: warning: implicit declaration of function ‘PyObject_New’
src/_portaudiomodule.c:448: error: expected expression before ‘_pyAudio_paDeviceInfo’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:464: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c:470: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:484: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:498: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:512: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:526: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:540: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:556: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_paHostApiInfo_antiset’:
src/_portaudiomodule.c:560: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c: In function ‘_pyAudio_paHostApiInfo_dealloc’:
src/_portaudiomodule.c:569: error: ‘_pyAudio_paHostApiInfo’ has no member named ‘apiInfo’
src/_portaudiomodule.c:572: error: ‘_pyAudio_paHostApiInfo’ has no member named ‘ob_type’
src/_portaudiomodule.c:572: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:572: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:575: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paHostApiInfo_getseters’
src/_portaudiomodule.c:615: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_paHostApiInfoType’
src/_portaudiomodule.c: In function ‘_create_paHostApiInfo_object’:
src/_portaudiomodule.c:663: error: expected expression before ‘_pyAudio_paHostApiInfo’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:908: error: expected specifier-qualifier-list before ‘PyObject_HEAD’
src/_portaudiomodule.c: In function ‘_is_open’:
src/_portaudiomodule.c:921: error: ‘_pyAudio_Stream’ has no member named ‘is_open’
src/_portaudiomodule.c: In function ‘_cleanup_Stream_object’:
src/_portaudiomodule.c:927: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:928: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:929: error: ‘_pyAudio_Stream’ has no member named ‘stream’
src/_portaudiomodule.c:932: error: ‘_pyAudio_Stream’ has no member named ‘streamInfo’
src/_portaudiomodule.c:933: error: ‘_pyAudio_Stream’ has no member named ‘streamInfo’
src/_portaudiomodule.c:935: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:936: warning: implicit declaration of function ‘free’
src/_portaudiomodule.c:936: warning: incompatible implicit declaration of built-in function ‘free’
src/_portaudiomodule.c:936: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:937: error: ‘_pyAudio_Stream’ has no member named ‘inputParameters’
src/_portaudiomodule.c:940: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:941: warning: incompatible implicit declaration of built-in function ‘free’
src/_portaudiomodule.c:941: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:942: error: ‘_pyAudio_Stream’ has no member named ‘outputParameters’
src/_portaudiomodule.c:946: error: ‘_pyAudio_Stream’ has no member named ‘is_open’
src/_portaudiomodule.c: In function ‘_pyAudio_Stream_dealloc’:
src/_portaudiomodule.c:956: error: ‘_pyAudio_Stream’ has no member named ‘ob_type’
src/_portaudiomodule.c:956: error: ‘PyObject’ undeclared (first use in this function)
src/_portaudiomodule.c:956: error: expected expression before ‘)’ token
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:960: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:984: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1009: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1034: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1061: error: expected declaration specifiers or ‘...’ before ‘PyObject’
src/_portaudiomodule.c: In function ‘_pyAudio_Stream_antiset’:
src/_portaudiomodule.c:1065: error: ‘PyExc_AttributeError’ undeclared (first use in this function)
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:1070: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_Stream_getseters’
src/_portaudiomodule.c:1098: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘_pyAudio_StreamType’
src/_portaudiomodule.c: In function ‘_create_Stream_object’:
src/_portaudiomodule.c:1146: error: expected expression before ‘_pyAudio_Stream’
src/_portaudiomodule.c: At top level:
src/_portaudiomodule.c:1162: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1171: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1172: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1184: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1206: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1218: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1245: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1272: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1329: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1361: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1387: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1416: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1445: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1473: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1732: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1749: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1772: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1847: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1848: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1890: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:1891: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘u’
src/_portaudiomodule.c:1933: error: expected ‘)’ before ‘*’ token
src/_portaudiomodule.c:1972: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2019: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2064: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2098: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2126: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2198: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2288: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2313: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
src/_portaudiomodule.c:2346: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘init_portaudio’
error: command 'gcc' failed with exit status 1
| [
"\nsrc/_portaudiomodule.c:30:20: error: Python.h: No such file or directory\n\nYou forgot to install the Python development files.\n"
] | [
3
] | [] | [] | [
"portaudio",
"pyaudio",
"python"
] | stackoverflow_0004184262_portaudio_pyaudio_python.txt |
Q:
Python module visiable only in iPython
I have used set PYTHONPATH=%PYTHONPATH%;dictionary_containing_modules to make some modules globaly visiable.
I have a script importing the modules with import my_module.
When i run the script from the iPython shell (run my_script.py), i get no errors and the script runs as intended, but when I run the script from the command promt (windows) with python my_script.py I get the error:
ImportError: No module named my_module
I checked with pwd that they use the same working directory.
A:
Remember that you can dynamically change your system path from within your script, using sys.path or the site module. So maybe you want to add them to your script...
Or maybe you want to write a BAT or Python launcher script that sets the PYTHONPATH...
Or you want to edit the Windows environment variables (somewhere inside System properties Win+Break).
| Python module visiable only in iPython | I have used set PYTHONPATH=%PYTHONPATH%;dictionary_containing_modules to make some modules globaly visiable.
I have a script importing the modules with import my_module.
When i run the script from the iPython shell (run my_script.py), i get no errors and the script runs as intended, but when I run the script from the command promt (windows) with python my_script.py I get the error:
ImportError: No module named my_module
I checked with pwd that they use the same working directory.
| [
"Remember that you can dynamically change your system path from within your script, using sys.path or the site module. So maybe you want to add them to your script...\nOr maybe you want to write a BAT or Python launcher script that sets the PYTHONPATH...\nOr you want to edit the Windows environment variables (somew... | [
1
] | [] | [] | [
"ipython",
"python",
"scope"
] | stackoverflow_0004184180_ipython_python_scope.txt |
Q:
real time gui for python using only traits
Is it possible to create a ui using traits from python to make an interface for a cellular automata simulation?
A:
Of course, you can do anything with Traits that can with Python!
Seriously though, I presume your question is really about generating a GUI in which to display the CA. In that case I can recommend Mayavi which is based on Traits. It has a surf function which plots an array of regularly-spaced data as a 3D surface. There are docs on animating the data which shows how to change the underlying surface data for very fast rendering, which I have used and works well. I have a 3D numpy array shape=(x,y,time) and then for each step I pass a slice to surface objects data object:
surf.mlab_source.scalars = array[:,:,timepoint_index]
Alternatively you could use Matplotlib's imshow for a 2D plot of the same data. There is a very good tutorial on embedding matplotlib in traits.
One issue with using these large libraries (which themselves have many, many dependencies) is being able to distribute your application along with the libraries. I have successfully frozen a Mayavi/matplotlib/traits app on Mac using py2app and Windows using py2exe, starting from the Enthought Python Distribution, but it wasn't easy. However, if you just need it to work on your computer and generate results then both of these approaches will save you time over writing a graphics system for your cellular automata.
Having said all that I also hear good things about GarlicSim (as cool-RR mentioned), which would seem to be custom-made for your purpose.
Can't post links because this is my first post, I will add them later.
| real time gui for python using only traits | Is it possible to create a ui using traits from python to make an interface for a cellular automata simulation?
| [
"Of course, you can do anything with Traits that can with Python!\nSeriously though, I presume your question is really about generating a GUI in which to display the CA. In that case I can recommend Mayavi which is based on Traits. It has a surf function which plots an array of regularly-spaced data as a 3D surface... | [
1
] | [] | [] | [
"ca",
"python",
"simulation",
"traits",
"user_interface"
] | stackoverflow_0003893576_ca_python_simulation_traits_user_interface.txt |
Q:
Difference between android sha224 and python sha224
For an application prototype I'm creating a simple user login. The Password of the user will then be hashed using sha224 and transferred to the back-end. The Problem I am facing right now is the following. The password that was stored in the DB (also hashed using sha224) seems to look a little different then the hash I am sending. I use the following code to create the hashes.
Given Password == test
Python
from hashlib import sha224
sha224("test").hexdigest()
android
MessageDigest sha224 = MessageDigest.getInstance("SHA-224");
sha224.update(key.getBytes());
byte[] digest = sha224.digest();
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < digest.length; i++) {
buffer.append(String.valueOf(Integer.toHexString(0xFF & digest[i])));
}
return buffer.toString();
What now will be produced looks like this and I will post the two hashes directly underneath each other. (The first one is python and the second android)
90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809
90a3ed9e32b2aaf4c61c41eb925426119e1a9dc53d4286ade99a89
They are almost the same but the python hash has two 0s more. Do you guys have any idea why?
A:
You're not formatting the hex values on the Android properly; leading 0s are being dropped.
buffer.append(String.format("%02x", 0xFF & digest[i]));
A:
final MessageDigest mDigest = MessageDigest.getInstance("SHA-224");
byte[] messageDigest = mDigest.digest(toEncrypt.getBytes());
final BigInteger number = new BigInteger(1, messageDigest);
final String sha = number.toString(16);
final int diff = 32 - sha.length();
final StringBuilder finalSHA = new StringBuilder(32);
for (int i=0;i<diff;i++) {
finalSHA.append("0");
}
finalSHA.append(sha);
return finalSHA.toString();
A:
You are converting the hex to string in pairs of 2 at a time. The first zero that is dropped is at 23rd i.e. an odd position. This is a leading zero. You need to zero pad the converted hex digits where necessary. Alternative implementation without BigInteger:
MessageDigest sha224 = MessageDigest.getInstance("SHA-224");
sha224.update(key.getBytes());
byte[] digest = sha224.digest();
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < digest.length; i++) {
String hex_string = Integer.toHexString(0xFF & digest[i]);
if(hex_string.length()==1) hex_string = "0"+hex_string;
buffer.append(hex_string);
}
return buffer.toString();
| Difference between android sha224 and python sha224 | For an application prototype I'm creating a simple user login. The Password of the user will then be hashed using sha224 and transferred to the back-end. The Problem I am facing right now is the following. The password that was stored in the DB (also hashed using sha224) seems to look a little different then the hash I am sending. I use the following code to create the hashes.
Given Password == test
Python
from hashlib import sha224
sha224("test").hexdigest()
android
MessageDigest sha224 = MessageDigest.getInstance("SHA-224");
sha224.update(key.getBytes());
byte[] digest = sha224.digest();
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < digest.length; i++) {
buffer.append(String.valueOf(Integer.toHexString(0xFF & digest[i])));
}
return buffer.toString();
What now will be produced looks like this and I will post the two hashes directly underneath each other. (The first one is python and the second android)
90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809
90a3ed9e32b2aaf4c61c41eb925426119e1a9dc53d4286ade99a89
They are almost the same but the python hash has two 0s more. Do you guys have any idea why?
| [
"You're not formatting the hex values on the Android properly; leading 0s are being dropped.\nbuffer.append(String.format(\"%02x\", 0xFF & digest[i]));\n\n",
"final MessageDigest mDigest = MessageDigest.getInstance(\"SHA-224\");\nbyte[] messageDigest = mDigest.digest(toEncrypt.getBytes());\nfinal BigInteger numbe... | [
4,
0,
0
] | [] | [] | [
"android",
"hash",
"python",
"sha2"
] | stackoverflow_0004184792_android_hash_python_sha2.txt |
Q:
Coloring an edge detected image by user input co-ordinates..??What's wrong with this code?
I need to color the white part surrounded by black edges!
from PIL import Image
import sys
image=Image.open("G:/ghgh.bmp")
data=image.load()
image_width,image_height=image.size
sys.setrecursionlimit(10115)
def f(x,y):
if(x<image_width and y<image_height and x>0 and y>0):
if (data[x,y]==255):
image.putpixel((x,y),150)
f(x+1,y)
f(x-1,y)
f(x,y+1)
f(x,y-1)
f(x+1,y+1)
f(x-1,y-1)
f(x+1,y-1)
f(x-1,y+1)
f(100,100)
image.show()
255 is to detect white color, 150 is used to re-color greyish, and (100,100) is the starting pixel.
It's giving "Max recursion depth" at n=10114 and python crashes on n=10115 (the setrecursionlimit(n)).
A:
What's up with the while loop? It never changes the coordinates, so it seems it would loop forever, doing recursive calls. From a quick reading it sounds like it should be a plain if.
Also: drop the parens with while and if; they're not needed in Python.
A:
"unwind" above is right. Just replace your "while" with an "if" and it should work.
| Coloring an edge detected image by user input co-ordinates..??What's wrong with this code? | I need to color the white part surrounded by black edges!
from PIL import Image
import sys
image=Image.open("G:/ghgh.bmp")
data=image.load()
image_width,image_height=image.size
sys.setrecursionlimit(10115)
def f(x,y):
if(x<image_width and y<image_height and x>0 and y>0):
if (data[x,y]==255):
image.putpixel((x,y),150)
f(x+1,y)
f(x-1,y)
f(x,y+1)
f(x,y-1)
f(x+1,y+1)
f(x-1,y-1)
f(x+1,y-1)
f(x-1,y+1)
f(100,100)
image.show()
255 is to detect white color, 150 is used to re-color greyish, and (100,100) is the starting pixel.
It's giving "Max recursion depth" at n=10114 and python crashes on n=10115 (the setrecursionlimit(n)).
| [
"What's up with the while loop? It never changes the coordinates, so it seems it would loop forever, doing recursive calls. From a quick reading it sounds like it should be a plain if.\nAlso: drop the parens with while and if; they're not needed in Python.\n",
"\"unwind\" above is right. Just replace your \"while... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004184841_python.txt |
Q:
Problems raising a ValidationError on a Django Form
I'm trying to validate that a submitted URL doesn't already exist in the database.
The relevant parts of the Form class look like this:
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
The problem is, regardless of what value I submit, I can't raise the ValidationError. And if I do something like this in the clean_url() method:
if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
then I get a DoesNotExist error, even for URLs that already exist in the Database. Any ideas?
A:
django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting:
If no URL scheme is present (eg, http://) the method prepends 'http://' to the url
the method also appends a trailing slash.
The results are returned and stored in the form's cleaned_data. So I was checking cleaned_data['url'] expecting something like example.com and actually getting http://example.com/. Suffice to say, changing my clean_url() method to the following works:
def clean_url(self):
url = self.cleaned_data['url']
bits = urlparse(url)
dom = bits[1]
try:
site=Site.objects.get(domain__iexact=dom)
except Site.DoesNotExist:
return dom
raise forms.ValidationError(u'That domain is already taken. Please choose another')
A:
I do it this way. It's slightly simpler.
try:
a = Site.objects.get(domain=url)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
pass
return url
A:
I think, you can return '' and fill _errors.
msg = u"That URL is already in the database. Please submit a unique URL."
self._errors["url"]=ErrorList([msg])
return ''
or
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
except Site.DoesNotExist:
return url
return ''
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
A:
Well I logged in cause I found this via Google with a similar issue and wanted to add a comment to Carl Meyers post noting that using self._errors is totally valid as per the Django docs:
http://docs.djangoproject.com/en/1.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
| Problems raising a ValidationError on a Django Form | I'm trying to validate that a submitted URL doesn't already exist in the database.
The relevant parts of the Form class look like this:
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean_url(self):
url = self.cleaned_data['url']
try:
a = Site.objects.get(domain=url)
except Site.DoesNotExist:
return url
else:
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
def clean(self):
# Other form cleaning stuff. I don't *think* this is causing the grief
The problem is, regardless of what value I submit, I can't raise the ValidationError. And if I do something like this in the clean_url() method:
if Site.objects.get(domain=url):
raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.")
then I get a DoesNotExist error, even for URLs that already exist in the Database. Any ideas?
| [
"django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting:\n\nIf no URL scheme is present (eg, http://) the method prepends 'http://' to the url\nthe method also appends a trailing slash.\n\nThe results are returned and stored in the form's cleaned_data. So... | [
4,
1,
0,
0
] | [] | [] | [
"cleaned_data",
"django",
"django_forms",
"python"
] | stackoverflow_0000339387_cleaned_data_django_django_forms_python.txt |
Q:
Creating an empty list to have data assigned afterwards
Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but the list index should be at 0, correct?
How do add to the list each time the while loop is ran? I'm assuming something is wrong with my list assignment.
A:
An empty list doesn't have any index yet, it's an empty list! If you want to fill it, you have to do something like this :
while count < 10:
nameList.append(raw_input("Enter a name: "))
count += 1
This way, your condition will be evaluated and with the append method, you will be able to add new items in your list.
There are a few advanced tricks to do this easily, but considering your level, I think it's better that you understand this code before moving on.
A:
Most idiomatic is to use a list comprehension:
namelist = [raw_input("Enter a name: ") for i in range(10)]
(or use _ for i, although I personally wouldn't)
This has the advantage of creating the list on the fly, while having to use neither the append() method nor explicit indexing.
A:
count = 0
while listOfNames[count] < 10:
nameList.append(raw_input("Enter a name: "))
count += 1
Use append for quick n easy...
Alternatively:
nameList[len(nameList):] = [raw_input("Enter a name: ")]
Edit: Did you mean listOfNames to be appended as opposed to nameList?
A:
Your list assignment is right, your problem is with your use of indexes which do not yet exist.
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
I'm fairly sure this code doesn't do what you intend. What this code is doing is checking the first through tenth elements of listOfNames for a number which is less than 10, but since its an empty list there is no element with index 0, or any other index for that matter hence your list index out of range exceptions.
The following will work as you intend:
count = 0
while len(listOfNames) < 10: # Keep going until the list has 10 elements
nameList.append(raw_input("Enter a name: "))
count += 1
However I'd suggest using the following which does exactly the same thing but should be more efficient as well as being more aesthetically pleasing:
for _ in range(10):
listOfNames.append(raw_input("Enter a name:"))
Note the use of append instead of an index reference. This will add the new element on to the end of the list whereas using the index as you were trying to do will fail since to assign to and index there has to be an element present in the first place.
| Creating an empty list to have data assigned afterwards | Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but the list index should be at 0, correct?
How do add to the list each time the while loop is ran? I'm assuming something is wrong with my list assignment.
| [
"An empty list doesn't have any index yet, it's an empty list! If you want to fill it, you have to do something like this :\nwhile count < 10:\n nameList.append(raw_input(\"Enter a name: \"))\n count += 1\n\nThis way, your condition will be evaluated and with the append method, you will be able to add new ite... | [
11,
5,
1,
0
] | [] | [] | [
"indexing",
"list",
"python",
"range"
] | stackoverflow_0004185462_indexing_list_python_range.txt |
Q:
How to copy a message from one imap server to another imap server using Python imaplib?
I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib.
This is the code I tried:
typ, data = connection1.uid('FETCH', uid, 'RFC822')
connection2.uid('APPEND', None, data[0][1])
But this raises an exception:
imaplib.error: UID command error: BAD ['"Delivered-To: niels@domain.com']
So the argument (data[0][1]) is not properly formatted I think.
The contents of data[0][1] look like this:
Delivered-To: niels@domain.com\r\nReceived: by 10.216.207.222 with SMTP id n27cs38120weo;\r\nFri, 12 Nov 2010 09:43:47 -0800 (PST)\r\nReceived: by 10.200.19.19 with SMTP id y19mr234526eba.52.12894526694;\r\nFri, 12 Nov 2010 09:43:46 -0800 (PST)\r\nReturn-Path: somename@domain.com\r\nReceived: from dub0-omc1-s20.dub03.hotmail.com (dub0-omc1-s20.dub03.hotmail.com [157.55.0.220])\r\n ......
How can I fix this?
Update: With the help of Wodin and Avadhesh I can append messages now, but how do I get the UID of a just appended message?
A:
You can try the follwing code:
typ, data = connection1.uid('FETCH', uid, 'RFC822')
import email
msg_str = email.message_from_string(data[0][1])
msg_create = connection2.append(str(dest_fold_code) , flags, '', str(msg_str))
where flags would be '(\Seen)' in case of seen email or '' in case of unseen email.
A:
Have you tried:
connection2.append(mailbox, flags, date_time, message)
Append message to named mailbox.
RFC3501 shows the syntax of the UID command as follows:
uid = "UID" SP (copy / fetch / search / store)
i.e. there appears not to be a "UID APPEND" command.
A:
Solved it!
First copy the message with
typ, data = connection1.uid('FETCH', uid, 'RFC822')
connection2.append('Inbox', '', '', data[0][1])
Then fetch the unique message-id from the copied message like this
from email.parser import Parser
parser = Parser()
msg = parser.parsestr(data[0][1])
Then use the message-id to find the new message in the destination mailbox like this
typ, uid = connection2.uid('SEARCH', None, 'Header', 'Message-Id', msg['message-ID'])
| How to copy a message from one imap server to another imap server using Python imaplib? | I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib.
This is the code I tried:
typ, data = connection1.uid('FETCH', uid, 'RFC822')
connection2.uid('APPEND', None, data[0][1])
But this raises an exception:
imaplib.error: UID command error: BAD ['"Delivered-To: niels@domain.com']
So the argument (data[0][1]) is not properly formatted I think.
The contents of data[0][1] look like this:
Delivered-To: niels@domain.com\r\nReceived: by 10.216.207.222 with SMTP id n27cs38120weo;\r\nFri, 12 Nov 2010 09:43:47 -0800 (PST)\r\nReceived: by 10.200.19.19 with SMTP id y19mr234526eba.52.12894526694;\r\nFri, 12 Nov 2010 09:43:46 -0800 (PST)\r\nReturn-Path: somename@domain.com\r\nReceived: from dub0-omc1-s20.dub03.hotmail.com (dub0-omc1-s20.dub03.hotmail.com [157.55.0.220])\r\n ......
How can I fix this?
Update: With the help of Wodin and Avadhesh I can append messages now, but how do I get the UID of a just appended message?
| [
"You can try the follwing code:\ntyp, data = connection1.uid('FETCH', uid, 'RFC822')\nimport email\nmsg_str = email.message_from_string(data[0][1])\nmsg_create = connection2.append(str(dest_fold_code) , flags, '', str(msg_str))\n\nwhere flags would be '(\\Seen)' in case of seen email or '' in case of unseen email... | [
2,
1,
1
] | [] | [] | [
"imap",
"imaplib",
"python",
"rfc822"
] | stackoverflow_0004179150_imap_imaplib_python_rfc822.txt |
Q:
Rewrite this loop function with range
Is it possible to rewrite this loop:
for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8],
[ca,9],[cb,10],[cc,12],[cd,13],[da,14],[db,15],[dc,16],[dd,17],...zd,220]]:
with two range functions or "list multiplication"? I have tried all sorts of approaches, but none worked so far.
Thank you.
A:
If you have the objects in a list its actually quite simple:
object_list = [aa, ab, ... ]
for n, k in enumerate( object_list, start=1):
...
So you should look for a way to put them in a list instead.
A:
If all those objects are in the modules global namespace you could do something like this:
from string import ascii_lowercase
n = 1
for a in ascii_lowercase:
for b in ascii_lowercase[0:4]:
k = globals()[a+b]
n+=1
If they are in a function's namespace you could try locals() instead of globals()
A:
You didn't give much information, so this might not be what you are looking for but:
l = [aa, ab, ... ]
for i in xrange(len(l)):
k = l[i]
n = i+1
//the rest of your code
That being said, based on the names of your variables, it looks like you have a matrix of values. If that is the case, it would make more sense you use that kind of structure and just iterate over both indices rather than having lots of named variables.
A:
Assuming you have these matplotlib in an iterable, objs:
([i, obj] for i, obj in enumerate(objs, 1))
This can be made much shorter and simpler if you used 2-tuples instead of lists of length two (you propably want this anyway!): enumerate(objs, 1).
A:
A naive approach :
alphabet = ['a','b','c','d','e',] # Continue to have a complete alphabet
# Generator that returns every combination of a given alphabet with a given length
def xcombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
gen = xcombinations(alphabet, 2)
for p,k in enumerate(gen):
print ["".join(k), p]
Edit :
xcombinations can be replaced by itertools.permutations who does the same things.
A:
try these.
[[j,i] for i,j in enumerate([c1+c2 for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]])]
[j,i] just for printing in the order you said. put function or whatever you want there.
or if you prefer loop to list-comp
for i,j in enumerate([c1+c2 for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]]):
#loop body
im guessing aa thru zd are either in global namespace or (hopefully) a dict? just put either eval() or dict name around the c1+c2
for i,j in enumerate([dictname['c1+c2'] for c1 in ascii_lowercase for c2 in ascii_lowercase[0:4]]):
#loopbody
| Rewrite this loop function with range | Is it possible to rewrite this loop:
for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8],
[ca,9],[cb,10],[cc,12],[cd,13],[da,14],[db,15],[dc,16],[dd,17],...zd,220]]:
with two range functions or "list multiplication"? I have tried all sorts of approaches, but none worked so far.
Thank you.
| [
"If you have the objects in a list its actually quite simple:\nobject_list = [aa, ab, ... ]\nfor n, k in enumerate( object_list, start=1):\n ...\n\nSo you should look for a way to put them in a list instead.\n",
"If all those objects are in the modules global namespace you could do something like this:\nfrom ... | [
4,
0,
0,
0,
0,
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"range"
] | stackoverflow_0004185976_for_loop_loops_python_range.txt |
Q:
How to find out how many clients are on a certain address range?
I tried googling for this but i didnt find anything... I am building a port scanner and i would like to make it so, that i can scan a network range e.g 192.168.2.* and find out how many computers are on that range that are online. Alot like Nmap. I am programming in python. Is this possible in Python?
A:
Use python-nmap. Basic usage:
import nmap
nm = nmap.PortScanner()
nm.scan(hosts='192.168.2.0/24', arguments='-n -sP -PE -PA21,23,80,3389')
hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
print('{0}:{1}'.format(host, status))
For further reference see http://pypi.python.org/pypi/python-nmap
A:
Here is Draft example that you can start with:
import socket
addr_range = "192.168.1.%d"
ip_address_up = []
# Use UDP.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(2.0)
for i in range(1, 254):
try:
ip = addr_range % i
socket.gethostbyaddr(ip)
ip_address_up.append(ip)
except socket.herror as ex:
pass
print ip_address_up
or something like this using ICMP (ping) rather thank UDP:
import socket
import ping
ip_address_up = []
addr_range = "192.168.1.%d"
for i in range(1, 254):
try:
ip = addr_range % i
delay = ping.do_one(ip, timeout=2)
ip_address_up.append(ip)
except (socket.herror, socket.timeout) as ex:
pass
print ip_address_up
A:
Using raw sockets you can implement something nmap-like. You will probably find that the most informative probes need to be made using specially crafted packets that do "odd" things, compared to normal programming interfaces. It's well worth reading up on the IP/UDP/TCP RFCs.
Using raw sockets you can generate byte by byte any probing packet of your choosing, with options/configurations set that are normally impossible/hard to do under normal circumstances, but which "trick" a host into revealing a wealth of information.
A:
For IPv4 on local net you can resort to ARP using say Scapy, see related question.
| How to find out how many clients are on a certain address range? | I tried googling for this but i didnt find anything... I am building a port scanner and i would like to make it so, that i can scan a network range e.g 192.168.2.* and find out how many computers are on that range that are online. Alot like Nmap. I am programming in python. Is this possible in Python?
| [
"Use python-nmap. Basic usage:\nimport nmap\nnm = nmap.PortScanner()\nnm.scan(hosts='192.168.2.0/24', arguments='-n -sP -PE -PA21,23,80,3389')\nhosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]\nfor host, status in hosts_list:\n print('{0}:{1}'.format(host, status))\n\nFor further reference se... | [
2,
1,
0,
0
] | [] | [] | [
"networking",
"nmap",
"port_scanning",
"python"
] | stackoverflow_0004186374_networking_nmap_port_scanning_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.