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:
Need help with the regular expressions in Python
Help please to make from the string like:
<a href="http://testsite.com" class="className">link_text_part1 <em>another_text</em> link_text_part2</a>
string like:
link_text_part1 another_text link_text_part2
using regular expressions in Python
!note testsite.com changes
A:
So you want to remove the <a> and <em> tags? That can be done like this:
>>> s = '<a href="http://testsite.com" class="className">link_text_part1 <em>another_text</em> link_text_part2</a>'
>>> re.sub("</?(a|em).*?>", "", s)
'link_text_part1 another_text link_text_part2'
In English, this searches for:
A < character
optionally followed by a / (to get the closing tags)
followed by 'a' or 'em'
followed by anything up to and including the first > character
and replaces them with empty strings.
However as Kos says, using regex to parse HTML is highly risky and fragile, unless you know that the format of the HTML you are parsing will never change.
A:
string = re.sub('<[^>]+>', '', string)
A:
Parsing HTML with regular expressions, even for simple cases, is generally strongly unrecommended. You'll never know when you hit some HTML code which will confuse your regex.
A light HTML parser is generally a more reliable and more elegant solution.
A:
BTW. This helped:
from scrapy.utils.markup import remove_tags
...
bbb=remove_tags(aaa)
| Need help with the regular expressions in Python | Help please to make from the string like:
<a href="http://testsite.com" class="className">link_text_part1 <em>another_text</em> link_text_part2</a>
string like:
link_text_part1 another_text link_text_part2
using regular expressions in Python
!note testsite.com changes
| [
"So you want to remove the <a> and <em> tags? That can be done like this:\n>>> s = '<a href=\"http://testsite.com\" class=\"className\">link_text_part1 <em>another_text</em> link_text_part2</a>'\n\n>>> re.sub(\"</?(a|em).*?>\", \"\", s)\n'link_text_part1 another_text link_text_part2'\n\nIn English, this searches f... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0003317328_python_scrapy.txt |
Q:
Making text bold with django
I have to send make some text bold in between plain text and send it to the template from the view. I do this:
I save a string like this <b>TextPlaintext</b> in a variable and return it to the template.
The "<b>" tags are not interpreted.
How can make some text bold in a django view?
A:
Django automatically escapes string values in templates, to improve security.
If you know that a value has HTML in it, and is trusted, then you can turn off escaping:
{{my_trusted_html|safe}}
A:
Making a text bold shouldn't be done in the view. Indeed, the view should not take care of formatting (which is the role of templates). What you can do however, is adding an extra variable to the rendering context, and depending on its value, make the text bold or not in the template.
For example :
In the view :
#...
is_important = True if something else False
extra_context.update({'is_important': is_important})
#...
In the template :
...
{% if is_important %}<b>{{ text_to_render }}</b>{% else %}{{ text_to_render }}{% endif %}
...
But more generally, deciding if a text is bold or not, is not even formatting, rather styling and should not be made in the template (so you shouldn't use the <bold> markup). So I would suggest :
...
<span {% if is_important %}class="is-important"{% endif %}>
{{ text_to_render }}
</span>
...
And a stylesheet :
.is-important{
font-weight: bold;
}
A:
You can use the autoescape tag in a django template.
Also, if you write your own filter, you can control whether or not it is escaped.
| Making text bold with django | I have to send make some text bold in between plain text and send it to the template from the view. I do this:
I save a string like this <b>TextPlaintext</b> in a variable and return it to the template.
The "<b>" tags are not interpreted.
How can make some text bold in a django view?
| [
"Django automatically escapes string values in templates, to improve security.\nIf you know that a value has HTML in it, and is trusted, then you can turn off escaping:\n{{my_trusted_html|safe}}\n\n",
"Making a text bold shouldn't be done in the view. Indeed, the view should not take care of formatting (which is ... | [
7,
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003329626_django_python.txt |
Q:
What does this stand for?
What does '\r' mean? What does it do? I have never seen it before and its giving me headaches. It doesnt seem to have any purpose, since 'a\ra' prints as 'aa', but its not the same as the string 'aa'. Im using python 2.6
A:
It's an old control character from typewriters.
It means "carriage return". In this time, when you pressed "enter", you were going to the next line, then the carriage went back to the beginning of the line (hence the carriage return).
Then with computers, different OSes made different choices to represent new lines.
On windows, you have "\r\n" (carriage return + new line).
On unices, you have "\n" only (no need to do a carriage return, it was sort of implied by the new line).
On old mac OS, you had "\r" only.
Nowadays, it's not used except for newlines (or I don't know other usages).
A:
For me (on a Mac OS X 10.5 Terminal.App, Python 2.6.5):
>>> print 'a\ra'
a
or to give a better example:
>>> print 'longstring\rshort'
shorttring
IOW, the \r "returns the cursor to the start of the line" (without initiating a new long) so that 'short' "overwrites" the beginning of 'longstring'.
This effect is nice to show to the user a single-line "current status" being update during a long operation -- use print '\rupdate', with a trailing comma to avoid emitting a new-line character, to update the status by overwriting the previous one. Of course you need to ensure each updated string thus shown is at least as long as the previous one (easy by just padding with spaces).
Do note that other responders have noticed different visual effects on their platforms (you yourself have seen \r disappear without effect, which is unprecedented in my experience) so this nice way to provide updates won't work well on every platform!-)
A:
It's the escape for Carriage Return. On my console, running on Windows, print 'a\ra' results in ...
a
a
... getting printed to stdout.
Here's a list of all valid escapes.
\newline - Ignored
\\ - Backslash ()
\' - Single quote (')
\" - Double quote (")
\a - ASCII Bell (BEL)
\b - ASCII Backspace (BS)
\f - ASCII Formfeed (FF)
\n - ASCII Linefeed (LF)
\N{name} - Character named name in the Unicode database (Unicode only)
\r - ASCII Carriage Return (CR)
\t - ASCII Horizontal Tab (TAB)
\uxxxx - Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx - Character with 32-bit hex value xxxxxxxx (Unicode only)
\v - ASCII Vertical Tab (VT)
\ooo - Character with octal value ooo
\xhh - Character with hex value hh
A:
should be a Carriage Return...something like a new line...
look http://www.wilsonmar.com/1eschars.htm
| What does this stand for? | What does '\r' mean? What does it do? I have never seen it before and its giving me headaches. It doesnt seem to have any purpose, since 'a\ra' prints as 'aa', but its not the same as the string 'aa'. Im using python 2.6
| [
"It's an old control character from typewriters.\nIt means \"carriage return\". In this time, when you pressed \"enter\", you were going to the next line, then the carriage went back to the beginning of the line (hence the carriage return).\nThen with computers, different OSes made different choices to represent ne... | [
10,
8,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003329775_python_syntax.txt |
Q:
Globbing with python rpm module?
The following code uses the rpm module to query the version of an installed package. What I would like to do is to query a set of packages specified by a glob, for example searching for "python*" rather than "python". Is this possible using the rpm module?
1 #!/usr/bin/python
2
3 import rpm
4
5 ts = rpm.TransactionSet()
6 mi = ts.dbMatch("name", "python")
7 for i in mi:
8 print i['name'], i['version']
`
A:
import rpm
ts = rpm.TransactionSet()
mi = ts.dbMatch()
mi.pattern('name', rpm.RPMMIRE_GLOB, 'py*' )
for h in mi:
# Do something with the header...
| Globbing with python rpm module? | The following code uses the rpm module to query the version of an installed package. What I would like to do is to query a set of packages specified by a glob, for example searching for "python*" rather than "python". Is this possible using the rpm module?
1 #!/usr/bin/python
2
3 import rpm
4
5 ts = rpm.TransactionSet()
6 mi = ts.dbMatch("name", "python")
7 for i in mi:
8 print i['name'], i['version']
`
| [
"import rpm\nts = rpm.TransactionSet()\nmi = ts.dbMatch()\nmi.pattern('name', rpm.RPMMIRE_GLOB, 'py*' )\nfor h in mi:\n # Do something with the header... \n\n"
] | [
5
] | [] | [] | [
"glob",
"python",
"rpm",
"search"
] | stackoverflow_0003311760_glob_python_rpm_search.txt |
Q:
data structure that can do a "select distinct X where W=w and Y=y and Z=z and ..." type lookup
I have a set of unique vectors (10k's worth). And I need to, for any chosen column, extract the set of values that are seen in that column, in rows where all the others columns are given values.
I'm hoping for a solution that is sub linear (wrt the item count) in time and at most linear (wrt the total size of all the items) in space, preferably sub linear extra space over just storing the items.
Can I get that or better?
BTW: it's going to be accessed from python and needs to simple to program or be part of an existing commonly used library.
edit: the costs are for the lookup, and do not include the time to build the structures. All the data that will ever be indexed is available before the first query will be made.
It seems I'm doing a bad job of describing what I'm looking for, so here is a solution that gets close:
class Index:
dep __init__(self, stuff): # don't care about this O() time
self.all = set(stuff)
self.index = {}
for item in stuff:
for i,v in item:
self.index.getdefault(i,set()).add(v)
def Get(self, col, have): # this O() matters
ret = []
t = array(have) # make a copy.
for i in self.index[col]:
t[col] = i
if t in self.all:
ret.append(i)
return ret
The problem is that this give really bad (O(n)) worst case perf.
A:
Since you are asking for a SQL-like query, how about using a relational database? SQLite is part of the standard library, and can be used either on-disk or fully in memory.
A:
If you have a Python set (no ordering) there is no way to select all relevant items without at least looking at all items -- so it's impossible for any solution to be "sub linear" (wrt the number of items) as you require.
If you have a list, instead of a set, then it can be ordered -- but that cannot be achieved in linear time in the general case (O(N log N) is provably the best you can do for a general-case sorting -- and building sorted indices would be similar -- unless there are constraints that let you use "bucket-sort-like" approaches). You can spread around the time it takes to keep indices over all insertions in the data structure -- but that won't reduce the total time needed to build such indices, just, as I said, spread them around.
Hash-based (not sorted) indices can be faster for your special case (where you only need to select by equality, not by "less than" &c) -- but the time to construct such indices is linear in the number of items (obviously you can't construct such an index without at least looking once at each item -- sublinear time requires some magic that lets you completely ignore certain items, and that can't happen without supporting "structure" (such as sortedness) which in turn requires time to achieve (though it can be achieved "incrementally" ahead of time, such an approach doesn't reduce the total time required).
So, taken to the letter, your requirements appear overconstrained: neither Python, nor any other language, nor any database engine, etc, can possibly achieve them -- if interpreted literally exactly as you state them. If "incremental work done ahead of time" doesn't count (as breaching your demands of linearity and sublinearity), if you take about expected/typical rather than worst-case behavior (and your items have friendly probability distributions), etc, then it might be possible to come close to achieving your very demanding requests.
For example, consider maintaining for each of the vectors' D dimensions a dictionary mapping the value an item has in that dimension, to a set of indices of such items; then, selecting the items that meet the D-1 requirements of equality for every dimension but the ith one can be done by set intersections. Does this meet your requirements? Not by taking the latter strictly to the letter, as I've explained above -- but maybe, depending on how much each requirement can perhaps be taken in a more "relaxed" sense.
BTW, I don't understand what a "group by" implies here since all the vectors in each group would be identical (since you said all dimensions but one are specified by equality), so it may be that you've skipped a COUNT(*) in your SQL-equivalent -- i.e., you need a count of how many such vectors have a given value in the i-th dimension. In that case, it would be achievable by the above approach.
Edit: as the OP has clarified somewhat in comments and an edit to his Q I can propose an approach in more details:
import collections
class Searchable(object):
def __init__(self, toindex=None):
self.toindex = toindex
self.data = []
self.indices = None
def makeindices(self):
if self.indices is not None:
return
self.indices = dict((i, collections.defaultdict(set))
for i in self.toindex)
def add(self, record):
if self.toindex is None:
self.toindex = range(len(record))
self.makeindices()
where = len(self.data)
self.data.append(record)
for i in self.toindex:
self.indices[i][record[i]].add(where)
def get(self, indices_and_values, indices_to_get):
ok = set(range(len(self.data)))
for i, v in indices_and_values:
ok.intersection_update(self.indices[i][v])
result = set()
for rec in (self.data[i] for i in ok):
t = tuple(rec[i] for i in indices_to_get)
result.add(t)
return result
def main():
c = Searchable()
for r in ((1,2,3), (1,2,4), (1,5,4)):
c.add(r)
print c.get([(0,1),(1,2)], [2])
main()
This prints
set([(3,), (4,)])
and of course could be easily specialized to return results in other formats, accept indices (to index and/or to return) in different ways, etc. I believe it meets the requirements as edited / clarified since the extra storage is, for each indexed dimension/value, a set of the indices at which said value occurs on that dimension, and the search time is one set intersection per indexed dimension plus a loop on the number of items to be returned.
A:
I'm assuming that you've tried the dictionary and you need something more flexible. Basically, what you need to do is index values of x, y and z
def build_index(vectors):
index = {x: {}, y: {}, z: {}}
for position, vector in enumerate(vectors):
if vector.x in index['x']:
index['x'][vector.x].append(position)
else:
index['x'][vector.x] = [position]
if vector.y in index['y']:
index['y'][vector.y].append(position)
else:
index['y'][vector.y] = [position]
if vector.z in index['z']:
index['z'][vector.z].append(position)
else:
index['z'][vector.z] = [position]
return index
What you have in index a lookup table. You can say, for example, select x,y,z from vectors where x=42 by doing this:
def query_by(vectors, index, property, value):
results = []
for i in index[property][value]:
results.append(vectors[i])
vecs_x_42 = query_by(index, 'x', 42)
# now vec_x_42 is a list of all vectors where x is 42
Now to do a logical conjunction, say select x,y,z from vectors where x=42 and y=3 you can use Python's sets to accomplish this:
def query_by(vectors, index, criteria):
sets = []
for k, v in criteria.iteritems():
if v not in index[k]:
return []
sets.append(index[k][v])
results = []
for i in set.intersection(*sets):
results.append(vectors[i])
return results
vecs_x_42_y_3 = query_by(index, {'x': 42, 'y': 3})
The intersection operation on sets produces values which only appear in both sets, so you are only iterating the positions which satisfy both conditions.
Now for the last part of your question, to group by x:
def group_by(vectors, property):
result = {}
for v in vectors:
value = getattr(v, property)
if value in result:
result[value].append(v)
else:
result[value] = [v]
return result
So let's bring it all together:
vectors = [...] # your vectors, as objects such that v.x, v.y produces the x and y values
index = build_index(vectors)
my_vectors = group_by(query_by(vectors, index, {'y':42, 'z': 3}), 'x')
# now you have in my_vectors a dictionary of vectors grouped by x value, where y=42 and z=3
Update
I updated the code above and fixed a few obvious errors. It works now and it does what it claims to do. On my laptop, a 2GHz core 2 duo with 4GB RAM, it takes less than 1s to build_index. Lookups are very quick, even when the dataset has 100k vectors. If I have some time I'll do some formal comparisons against MySQL.
You can see the full code at this Codepad, if you time it or improve it, let me know.
A:
Suppose you have a 'tuple' class with fields x, y, and z and you have a bunch of such tuples saved in an enumerable var named myTuples. Then:
A) Pre-population:
dct = {}
for tpl in myTuples:
tmp = (tpl.y, tpl.z)
if tmp in dct:
dct[tmp].append(tpl.x)
else:
dct[tmp] = [tpl.x]
B) Query:
def findAll(y,z):
tmp = (y,z)
if tmp not in dct: return ()
return [(x,y,z) for x in dct[tmp]]
I am sure that there is a way to optimize the code for readability, save a few cycles, etc. But essentially you want to pre-populate a dict, using a 2-tuple as a key. If I did not see a request for sub-linear then I would not have though of this :)
A) The pre-population is linear, sorry.
B) Query should be as slow as the number of items returned - most of the time sub-linear, except for weird edge cases.
A:
So you have 3 coordinates and one value for start and end of vector (x,y,z)?
How is it possible to know the seven known values? Are there many coordinate triples multiple times?
You must be doing very tight loop with the function to be so conserned of look up time considering the small size of data (10K).
Could you give example of real input for your class you posted?
| data structure that can do a "select distinct X where W=w and Y=y and Z=z and ..." type lookup | I have a set of unique vectors (10k's worth). And I need to, for any chosen column, extract the set of values that are seen in that column, in rows where all the others columns are given values.
I'm hoping for a solution that is sub linear (wrt the item count) in time and at most linear (wrt the total size of all the items) in space, preferably sub linear extra space over just storing the items.
Can I get that or better?
BTW: it's going to be accessed from python and needs to simple to program or be part of an existing commonly used library.
edit: the costs are for the lookup, and do not include the time to build the structures. All the data that will ever be indexed is available before the first query will be made.
It seems I'm doing a bad job of describing what I'm looking for, so here is a solution that gets close:
class Index:
dep __init__(self, stuff): # don't care about this O() time
self.all = set(stuff)
self.index = {}
for item in stuff:
for i,v in item:
self.index.getdefault(i,set()).add(v)
def Get(self, col, have): # this O() matters
ret = []
t = array(have) # make a copy.
for i in self.index[col]:
t[col] = i
if t in self.all:
ret.append(i)
return ret
The problem is that this give really bad (O(n)) worst case perf.
| [
"Since you are asking for a SQL-like query, how about using a relational database? SQLite is part of the standard library, and can be used either on-disk or fully in memory.\n",
"If you have a Python set (no ordering) there is no way to select all relevant items without at least looking at all items -- so it's i... | [
11,
5,
2,
1,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0003327702_data_structures_python.txt |
Q:
Really weird Cookie header behaviour? - Cookies
I'm using Firefox 3.6.8 for these tests.
I'm setting a cookie within the response headers of my web app using:
Set-Cookie: session=7878dfdsfjsdf89sd89f8df9
This does not seem to override the session Cookie.
When a request is performed instead Firefox even sends duplicate cookies:
Cookie: session=7d75cd8f55895cbccb0d31ee07c7afc0;
session=671e8448a5cebda0442005a186cf69a3;
4cb6f2d75c9ffc8916cb55bcbaafecd8
What is going on??
Any ideas would be great!! =)
This is quite disastrous in my case... if someone could explain what's going on it would really help me out!
A:
If you don't specify the path or domain for a cookie when setting it, it defaults to the current path and current hostname. If you then go ahead and try setting the same cookie name from a URL with a different path or hostname, it will add a new cookie instead of replacing the old one.
I suspect what you want to do is just set a cookie with a global path for your site and for your entire domain. So something like this:
Set-Cookie: session=7878dfdsfjsdf89sd89f8df9; path=/; domain=.mysite.com
A:
You can delete the previous cookie using the response object.
response.delete_cookie(cookie_key)
The set of cookies is available via the request object in the request.COOKIES dictionary, and you can obtain the key from there.
Since you're using Django, here's how you might do this in the view function:
def my_view(request):
# do some work and create a response object
response = HttpResponse(some_content)
# first delete any previously set cookie named "session"
if 'session' in request.COOKIES:
response.delete_cookie('session')
# set the new cookie
response.set_cookie('session', <cookie value goes here>')
return response
| Really weird Cookie header behaviour? - Cookies | I'm using Firefox 3.6.8 for these tests.
I'm setting a cookie within the response headers of my web app using:
Set-Cookie: session=7878dfdsfjsdf89sd89f8df9
This does not seem to override the session Cookie.
When a request is performed instead Firefox even sends duplicate cookies:
Cookie: session=7d75cd8f55895cbccb0d31ee07c7afc0;
session=671e8448a5cebda0442005a186cf69a3;
4cb6f2d75c9ffc8916cb55bcbaafecd8
What is going on??
Any ideas would be great!! =)
This is quite disastrous in my case... if someone could explain what's going on it would really help me out!
| [
"If you don't specify the path or domain for a cookie when setting it, it defaults to the current path and current hostname. If you then go ahead and try setting the same cookie name from a URL with a different path or hostname, it will add a new cookie instead of replacing the old one.\nI suspect what you want to... | [
6,
3
] | [] | [] | [
"cookies",
"django",
"http",
"http_headers",
"python"
] | stackoverflow_0003327152_cookies_django_http_http_headers_python.txt |
Q:
Is it common/good practice to test for type values in Python?
Is it common in Python to keep testing for type values when working in a OOP fashion?
class Foo():
def __init__(self,barObject):
self.bar = setBarObject(barObject)
def setBarObject(barObject);
if (isInstance(barObject,Bar):
self.bar = barObject
else:
# throw exception, log, etc.
class Bar():
pass
Or I can use a more loose approach, like:
class Foo():
def __init__(self,barObject):
self.bar = barObject
class Bar():
pass
A:
Nope, in fact it's overwhelmingly common not to test for type values, as in your second approach. The idea is that a client of your code (i.e. some other programmer who uses your class) should be able to pass any kind of object that has all the appropriate methods or properties. If it doesn't happen to be an instance of some particular class, that's fine; your code never needs to know the difference. This is called duck typing, because of the adage "If it quacks like a duck and flies like a duck, it might as well be a duck" (well, that's not the actual adage but I got the gist of it I think)
One place you'll see this a lot is in the standard library, with any functions that handle file input or output. Instead of requiring an actual file object, they'll take anything that implements the read() or readline() method (depending on the function), or write() for writing. In fact you'll often see this in the documentation, e.g. with tokenize.generate_tokens, which I just happened to be looking at earlier today:
The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects (see section File Objects). Each call to the function should return one line of input as a string.
This allows you to use a StringIO object (like an in-memory file), or something wackier like a dialog box, in place of a real file.
In your own code, just access whatever properties of an object you need, and if it's the wrong kind of object, one of the properties you need won't be there and it'll throw an exception.
A:
I think that it's good practice to check input for type. It's reasonable to assume that if you asked a user to give one data type they might give you another, so you should code to defend against this.
However, it seems like a waste of time (both writing and running the program) to check the type of input that the program generates independent of input. As in a strongly-typed language, checking type isn't important to defend against programmer error.
So basically, check input but nothing else so that code can run smoothly and users don't have to wonder why they got an exception rather than a result.
A:
If your alternative to the type check is an else containing exception handling, then you should really consider duck typing one tier up, supporting as many objects with the methods you require from the input, and working inside a try.
You can then except (and except as specifically as possible) that.
The final result wouldn't be unlike what you have there, but a lot more versatile and Pythonic.
Everything else that needed to be said about the actual question, whether it's common/good practice or not, I think has been answered excellently by David's.
A:
I agree with some of the above answers, in that I generally never check for type from one function to another.
However, as someone else mentioned, anything accepted from a user should be checked, and for things like this I use regular expressions. The nice thing about using regular expressions to validate user input is that not only can you verify that the data is in the correct format, but you can parse the input into a more convenient form, like a string into a dictionary.
| Is it common/good practice to test for type values in Python? | Is it common in Python to keep testing for type values when working in a OOP fashion?
class Foo():
def __init__(self,barObject):
self.bar = setBarObject(barObject)
def setBarObject(barObject);
if (isInstance(barObject,Bar):
self.bar = barObject
else:
# throw exception, log, etc.
class Bar():
pass
Or I can use a more loose approach, like:
class Foo():
def __init__(self,barObject):
self.bar = barObject
class Bar():
pass
| [
"Nope, in fact it's overwhelmingly common not to test for type values, as in your second approach. The idea is that a client of your code (i.e. some other programmer who uses your class) should be able to pass any kind of object that has all the appropriate methods or properties. If it doesn't happen to be an insta... | [
18,
1,
0,
0
] | [] | [] | [
"introspection",
"oop",
"python"
] | stackoverflow_0003327454_introspection_oop_python.txt |
Q:
Object_list always empty
the app is working this way. That i have a simple news adding model as below:
class News(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField(auto_now_add=True)
content = models.TextField()
the view
def homepage(request):
posts= News.objects.all() #.get(title="aaa")
return render_to_response('homepage.html', {'a':posts})
and finally the tamplate:
{% for b in a.object_list %}
<li> title:{{ b.title }}</li>
{%empty %}
EMPTY
{% endfor %}
Unfortunately it always sais 'EMPTY'. However if i take the '.get(title="aaa")' option instead of '.all()' (the commented part) I got the right title and content of the message with title 'aaa'.
Can anyone explain what am I doing wrong?
Thanks in advance for Your expertise.
EDIT
I'm sorry I didn't have written the template for the get option Well off course the 'get' verion of template differs. It looks like this:
{{a.title}} {{a.content}
And it works printing the expected title and message content So the 'get' works with the template and the 'for' didn't iterate over the QuerySet returned by all(). I am beginner but object_list is supposed to be the representation for querySet passed in render_on_request as a element of dictionary?
A:
When you use get, the variable posts contains an instance of News. On the other hand, if you use .all(), posts will contain a queryset. So first I would suggest you use filter instead of get, so posts would always be a queryset, and therefore you wouldn't have such an inconsistent behaviour ...
A:
Please post the exact code you are running. There is no way that either of your alternatives would work with a.object_list, because there is no definition of object_list anywhere and it's not a built-in Django property.
And assuming you actually mean that for b in a doesn't work in the first code but does in the second, this is not true either, because with .get you won't have anything to iterate through with for.
However, let's assume what you actually did was pass the results of .all() to the template, and the template didn't have the for loop. That wouldn't work, because all() - like filter() - returns a QuerySet, which must be iterated through. For the same reason, get() wouldn't work with a for loop.
Edited after comment "object_list is supposed to be the representation for querySet passed in render_on_request " - no, it isn't. Where did you get that idea? If you pass a queryset called a to the template, then you iterate through a, nothing else. object_list is the name that is used by default in generic views for the queryset itself - ie what you have called a - but in your own views you call it what you like, and use it with the name you have given it.
Edited after second comment I don't know why this should be confusing. You've invented a need for object_list where there is no such variable, and no need for one. Just do as I said originally - {% for b in a %}.
A:
When you want to iterate over something like this:
for object in object_list:
print object
object_list needs to support iterating. list, tuple, dict, and other types support that. You can define your own iterator class by giving it a iter method. See the docs for that.
Now, in your example
return render_to_response('homepage.html', {'a':posts})
posts is a Queryset instance that supports iterating. Think of it this way:
{% for b in News.objects.all %}
this is what you would like to have, but what you actually did is this:
{% for b in News.objects.all.object_list %}
But News.objects.all does not have an object_list attribute!
News.objects.all is what your object_list should be, so just write:
{% for b in a %}
| Object_list always empty | the app is working this way. That i have a simple news adding model as below:
class News(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField(auto_now_add=True)
content = models.TextField()
the view
def homepage(request):
posts= News.objects.all() #.get(title="aaa")
return render_to_response('homepage.html', {'a':posts})
and finally the tamplate:
{% for b in a.object_list %}
<li> title:{{ b.title }}</li>
{%empty %}
EMPTY
{% endfor %}
Unfortunately it always sais 'EMPTY'. However if i take the '.get(title="aaa")' option instead of '.all()' (the commented part) I got the right title and content of the message with title 'aaa'.
Can anyone explain what am I doing wrong?
Thanks in advance for Your expertise.
EDIT
I'm sorry I didn't have written the template for the get option Well off course the 'get' verion of template differs. It looks like this:
{{a.title}} {{a.content}
And it works printing the expected title and message content So the 'get' works with the template and the 'for' didn't iterate over the QuerySet returned by all(). I am beginner but object_list is supposed to be the representation for querySet passed in render_on_request as a element of dictionary?
| [
"When you use get, the variable posts contains an instance of News. On the other hand, if you use .all(), posts will contain a queryset. So first I would suggest you use filter instead of get, so posts would always be a queryset, and therefore you wouldn't have such an inconsistent behaviour ...\n",
"Please post ... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003329624_django_python.txt |
Q:
AttributeError: trying to match list of string identifiers from file1 in file2
Here is a brief summary of my aims. I have a list of data in the data text file that are basically names or identifiers. The list of names is all on one line and seperated by a space. I want to make each data a seperate line. These data are identifiers. If for instance one name from the original data text file in also present in the big file I want to have that line of data in the big file, i.e. the name and some additional information all on the same line written to a smaller data file.
This is the program that I have started to attempt such a feat. Perhaps this is pushing the limits of my skills but I hope to be able to complete this.
datafile = open ('C:\\datatext.txt', 'r')
line = [item for item in open('C:\\datatext.txt', 'r').read().split(' ')
if item.startswith("name") or item.startswith("name2")]
line_list = line.split(" ")
completedataset = open('C:\\bigfile.txt', 'r')
smallerdataset = open('C:\\smallerdataset.txt', 'w')
trials = [ line_list ]
for line in completedataset:
for t in trials:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
Here is the error that i receive when i run the program in python:
Traceback (most recent call last):
File "C:/program3.py", line 7, in <module>
line_list = line.split(" ")
AttributeError: 'list' object has no attribute 'split'
I have tried to be very thourough and look forward to your comments. If you have additional questions I will elaborate as needed promptly. All the best and enjoy the rainy weather.
EDIT:
I have made some changes to the program based on suggestions. I have this as my program now:
with open('C:\\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if item.startswith("name1") or item.startswith("othername")]
completedataset = open('C:\\bigfile.txt', 'r')
smallerdataset = open('C:\\smallerdataset.txt', 'w')
trials = [ matchedLines ]
for line in completedataset:
for t in trials:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
and i'm getting this error now:
Traceback (most recent call last):
File "C:/program5.py", line 17, in
if t in line:
TypeError: 'in ' requires string as left operand, not list
>>>
Thank you for you're continued help in this matter.
EDIT 2:
I have made several changes and now I'm getting this error:
Traceback (most recent call last):
File "C:/program6.py", line 9, in
open('C:\\smallerdataset.txt', 'w')) as (completedataset, smallerdataset):
AttributeError: 'tuple' object has no attribute '__exit__'
Here is my program as it stands now:
with open('C:\\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if item.startswith("nam1") or item.startswith("ndname")]
with (open('C:\\bigfile.txt', 'r'),
open('C:\\smallerdataset.txt', 'w')) as (completedataset, smallerdataset):
for line in completedataset:
for t in matchedLines:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
How can I get around this hurdle?
A:
line = [item for item in open('C:\chiptext.txt', 'r').read().split(' ')
if item.startswith("SNP") or item.startswith("AFFY")]
This is making line a list of strings. A list object does not have a split method.
It looks like you want a list of all the names in datatext and a subset of that list for names that match some predicate. The best way to do that is the following.
with open('C:\\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if (PREDICATE)]
As a general comment, try not to get too carried away with one-lining code. Your list comprehension line is leaving the file object open.
Edit for new edit:
matchedLines is already a list, so I'm not sure why you are wrapping it in another list when you make trials. Below is a simple example of what you are doing.
l = [1,2,3]
ll = [l]
print ll //[[1, 2, 3]]
When you get errors that don't make sense based on what you expect the value of a variable to be, you should add in print statements so you can confirm that the values are correct.
This is likely what you need:
with open('C:\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if item.startswith("name1") or item.startswith("othername")]
with open('C:\bigfile.txt', 'r') as completedataset:
with open('C:\smallerdataset.txt', 'w') as smallerdataset:
for line in completedataset:
for t in matchedLines:
if t in line:
smallerdataset.write(line)
| AttributeError: trying to match list of string identifiers from file1 in file2 | Here is a brief summary of my aims. I have a list of data in the data text file that are basically names or identifiers. The list of names is all on one line and seperated by a space. I want to make each data a seperate line. These data are identifiers. If for instance one name from the original data text file in also present in the big file I want to have that line of data in the big file, i.e. the name and some additional information all on the same line written to a smaller data file.
This is the program that I have started to attempt such a feat. Perhaps this is pushing the limits of my skills but I hope to be able to complete this.
datafile = open ('C:\\datatext.txt', 'r')
line = [item for item in open('C:\\datatext.txt', 'r').read().split(' ')
if item.startswith("name") or item.startswith("name2")]
line_list = line.split(" ")
completedataset = open('C:\\bigfile.txt', 'r')
smallerdataset = open('C:\\smallerdataset.txt', 'w')
trials = [ line_list ]
for line in completedataset:
for t in trials:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
Here is the error that i receive when i run the program in python:
Traceback (most recent call last):
File "C:/program3.py", line 7, in <module>
line_list = line.split(" ")
AttributeError: 'list' object has no attribute 'split'
I have tried to be very thourough and look forward to your comments. If you have additional questions I will elaborate as needed promptly. All the best and enjoy the rainy weather.
EDIT:
I have made some changes to the program based on suggestions. I have this as my program now:
with open('C:\\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if item.startswith("name1") or item.startswith("othername")]
completedataset = open('C:\\bigfile.txt', 'r')
smallerdataset = open('C:\\smallerdataset.txt', 'w')
trials = [ matchedLines ]
for line in completedataset:
for t in trials:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
and i'm getting this error now:
Traceback (most recent call last):
File "C:/program5.py", line 17, in
if t in line:
TypeError: 'in ' requires string as left operand, not list
>>>
Thank you for you're continued help in this matter.
EDIT 2:
I have made several changes and now I'm getting this error:
Traceback (most recent call last):
File "C:/program6.py", line 9, in
open('C:\\smallerdataset.txt', 'w')) as (completedataset, smallerdataset):
AttributeError: 'tuple' object has no attribute '__exit__'
Here is my program as it stands now:
with open('C:\\datatext.txt', 'r') as datafile:
lines = datafile.read().split(' ')
matchedLines = [item for item in lines if item.startswith("nam1") or item.startswith("ndname")]
with (open('C:\\bigfile.txt', 'r'),
open('C:\\smallerdataset.txt', 'w')) as (completedataset, smallerdataset):
for line in completedataset:
for t in matchedLines:
if t in line:
smallerdataset.write(line)
completedataset.close()
smallerdataset.close()
How can I get around this hurdle?
| [
"line = [item for item in open('C:\\chiptext.txt', 'r').read().split(' ')\n if item.startswith(\"SNP\") or item.startswith(\"AFFY\")]\n\nThis is making line a list of strings. A list object does not have a split method.\nIt looks like you want a list of all the names in datatext and a subset of that list f... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003330690_python.txt |
Q:
Limit the number of sentences in a string
A beginner's Python question:
I have a string with x number of sentences. How to I extract first 2 sentences (may end with . or ? or !)
A:
Ignoring considerations such as when a . constitutes the end of sentence:
import re
' '.join(re.split(r'(?<=[.?!])\s+', phrase, 2)[:-1])
EDIT: Another approach that just occurred to me is this:
re.match(r'(.*?[.?!](?:\s+.*?[.?!]){0,1})', phrase).group(1)
Notes:
Whereas the first solution lets you replace the 2 with some other number to choose a different number of sentences, in the second solution, you change the 1 in {0,1} to one less than the number of sentences you want to extract.
The second solution isn't quite as robust in handling, e.g., empty strings, or strings with no punctuation. It could be made so, but the regex would be even more complex than it is already, and I would favour the slightly less efficient first solution over an unreadable mess.
A:
I solved it like this: Separating sentences, though a comment on that post also points to NLTK, though I don't know how to find the sentence segmenter on their site...
A:
Here's how yo could do it:
str = "Sentence one? Sentence two. Sentence three? Sentence four. Sentence five."
sentences = str.split(".")
allSentences = []
for sentence in sentences
allSentences.extend(sentence.split("?"))
print allSentences[0:3]
There are probably better ways, I look forward to seeing them.
A:
Here is a step by step explanation of how to disassemble, choose the first two sentences, and reassemble it. As noted by others, this does not take into account that not all dot/question/exclamation characters are really sentence separators.
import re
testline = "Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5."
# split the first two sentences by the dot/question/exclamation.
sentences = re.split('([.?!])', testline, 2)
print "result of split: ", sentences
# toss everything else (the last item in the list)
firstTwo = sentences[:-1]
print firstTwo
# put the first two sentences back together
finalLine = ''.join(firstTwo)
print finalLine
A:
Generator alternative using my utility function returning piece of string until any item in search sequence:
from itertools import islice
testline = "Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5."
def multis(search_sequence,text,start=0):
""" multisearch by given search sequence values from text, starting from position start
yielding tuples of text before found item and found sequence item"""
x=''
for ch in text[start:]:
if ch in search_sequence:
if x: yield (x,ch)
else: yield ch
x=''
else:
x+=ch
else:
if x: yield x
# split the first two sentences by the dot/question/exclamation.
two_sentences = list(islice(multis('.?!',testline),2)) ## must save the result of generation
print "result of split: ", two_sentences
print '\n'.join(sentence.strip()+sep for sentence,sep in two_sentences)
| Limit the number of sentences in a string | A beginner's Python question:
I have a string with x number of sentences. How to I extract first 2 sentences (may end with . or ? or !)
| [
"Ignoring considerations such as when a . constitutes the end of sentence:\nimport re\n' '.join(re.split(r'(?<=[.?!])\\s+', phrase, 2)[:-1])\n\nEDIT: Another approach that just occurred to me is this:\nre.match(r'(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)\n\nNotes:\n\nWhereas the first solution lets you rep... | [
10,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003329386_python.txt |
Q:
Django: How to find out whether RawQuetySet has rows ? There's no count() method
I think the title speaks for itself.
I have a complex query with a subquery, but sometimes it returns no values, which is absolutely normal. But I can not prevent the ValueError message, cuz I am not able to find out whether RawQuerySet is empty or not. The RQS object is always present, but if I try to access it's first row results[0].id I get an error
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1379, in __getitem__
return list(self)[k]
IndexError: list index out of range
Suggestions ?!
A:
Catch the exception?
try:
return results[0].id
except IndexError:
pass # no rows returned
or
import itertools
results_list = []
try:
for i in itertools.count(0):
results_list.append(results[i])
except IndexError:
pass # no more rows
return results_list
| Django: How to find out whether RawQuetySet has rows ? There's no count() method | I think the title speaks for itself.
I have a complex query with a subquery, but sometimes it returns no values, which is absolutely normal. But I can not prevent the ValueError message, cuz I am not able to find out whether RawQuerySet is empty or not. The RQS object is always present, but if I try to access it's first row results[0].id I get an error
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1379, in __getitem__
return list(self)[k]
IndexError: list index out of range
Suggestions ?!
| [
"Catch the exception?\ntry:\n return results[0].id\nexcept IndexError:\n pass # no rows returned\n\nor\nimport itertools\n\nresults_list = []\ntry:\n for i in itertools.count(0):\n results_list.append(results[i])\nexcept IndexError:\n pass # no more rows\nreturn results_list\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003330933_django_django_models_python.txt |
Q:
What is the proper method of printing Python Exceptions?
except ImportError as xcpt:
print "Import Error: " + xcpt.message
Gets you a deprecation warning in 2.6 because message is going away.
Stackoverflow
How should you be dealing with ImportError? (Note, this is a built-in exception, not one of my making....)
A:
The correct approach is
xcpt.args
Only the message attribute is going away. The exception will continue to exist and it will continue to have arguments.
Read this: http://www.python.org/dev/peps/pep-0352/ which has some rational for removing the messages attribute.
A:
If you want to print the exception:
print "Couldn't import foo.bar.baz: %s" % xcpt
Exceptions have a __str__ method defined to create a readable version of themselves. I wouldn't bother with "Import Error:" since the exception will provide that itself. If you add text to the exception, make it be something you know based on the code you were trying to execute.
| What is the proper method of printing Python Exceptions? | except ImportError as xcpt:
print "Import Error: " + xcpt.message
Gets you a deprecation warning in 2.6 because message is going away.
Stackoverflow
How should you be dealing with ImportError? (Note, this is a built-in exception, not one of my making....)
| [
"The correct approach is \nxcpt.args\n\nOnly the message attribute is going away. The exception will continue to exist and it will continue to have arguments.\nRead this: http://www.python.org/dev/peps/pep-0352/ which has some rational for removing the messages attribute.\n",
"If you want to print the exception:... | [
9,
2
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0003330991_exception_python.txt |
Q:
Unit testing: More Actions than Expected after calling addAction Method
Here is my class:
class ManagementReview(object):
"""Class describing ManagementReview Object.
"""
# Class attributes
id = 0
Title = 'New Management Review Object'
fiscal_year = ''
region = ''
review_date = ''
date_completed = ''
prepared_by = ''
__goals = [] # List of <ManagementReviewGoals>.
__objectives = [] # List of <ManagementReviewObjetives>.
__actions = [] # List of <ManagementReviewActions>.
__deliverables = [] # List of <ManagementReviewDeliverable>.
__issues = [] # List of <ManagementReviewIssue>.
__created = ''
__created_by = ''
__modified = ''
__modified_by = ''
def __init__(self,Title='',id=0,fiscal_year='',region='',review_date='',
date_completed='',prepared_by='',created='',created_by='',
modified='',modified_by=''):
"""Instantiate object.
"""
if id:
self.setId(id)
if Title:
self.setTitle(Title)
if fiscal_year:
self.setFiscal_year(fiscal_year)
if region:
self.setRegion(region)
if review_date:
self.setReview_date(review_date)
if date_completed:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setDate_completed(date_completed)
if prepared_by:
self.setPrepared_by(prepared_by)
if created:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setCreated(created)
else:
self.setCreated(self.getNow())
if created_by:
self.setCreated_by(created_by)
self.__modified = self.getNow()
if modified_by:
self.__modified_by = modified_by
def __str__(self):
return "<ManagementReview '%s (%s)'>" % (self.Title,self.id)
def __setattr__(self, name, value): # Override built-in setter
# set the value like usual and then update the modified attribute too
object.__setattr__(self, name, value) # Built-in
self.__dict__['__modified'] = datetime.now().isoformat()
def getActions(self):
return self.__actions
def addAction(self,mra):
self.__actions.append(mra)
def removeAction(self,id):
pass # XXX TODO
I have this test:
from datetime import datetime
import random
import unittest
from ManagementReview import ManagementReview, ManagementReviewAction
# Default Values for ManagementReviewAction Object Type
DUMMY_ID = 1
DUMMY_ACTION = 'Action 1'
DUMMY_OWNER = 'Owner 1'
DUMMY_TITLE = 'Test MR'
DUMMY_FISCAL_YEAR = '2011'
DUMMY_REGION = 'WO'
DUMMY_REVIEW_DATE = '2009-01-18T10:50:21.766169',
DUMMY_DATE_COMPLETED = '2008-07-18T10:50:21.766169'
DUMMY_PREPARED_BY = 'test user'
DUMMY_CREATED = '2002-07-18T10:50:21.766169'
DUMMY_CREATED_BY = 'test user 2'
DUMMY_MODIFIED = datetime.now().isoformat()
DUMMY_MODIFIED_BY = 'test user 3'
class TestManagementReviewSetAction(unittest.TestCase):
def setUp(self):
self.mr = ManagementReview(DUMMY_TITLE,DUMMY_ID,fiscal_year=DUMMY_FISCAL_YEAR,region=DUMMY_REGION,
review_date=DUMMY_REVIEW_DATE,date_completed=DUMMY_DATE_COMPLETED,
prepared_by=DUMMY_PREPARED_BY,created=DUMMY_CREATED,
created_by=DUMMY_CREATED_BY,modified=DUMMY_MODIFIED,
modified_by=DUMMY_MODIFIED_BY)
def tearDown(self):
self.mr = None
def test_add_action(self):
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.assertEqual(len(self.mr.getActions()),10)
def test_remove_action(self):
print len(self.mr.getActions())
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.mr.removeAction(3)
self.assertEqual(len(self.mr.getActions()),9)
if __name__ == '__main__':
unittest.main()
The first test passes. That is, self.mr.getActions() has 10 actions.
However, when I run the 2nd test, test_remove_action, the value for len(self.mr.getActions()) is 10. At this point, though, it should be 0.
Why is this?
Thanks
A:
see if you are keeping track of actions in a class attribute of ManagementReview as opposed to an instance attribute
A class attribute will be something like
class Spam(object):
actions = []
and an instance attribute will look something like
class Spam(object):
def __init__(self):
self.actions = []
What happens is that actions = [] is executed when the class is created and all instances of the class share the same list.
EDIT:
In light of your update, I can see that this is definitely what is going on
| Unit testing: More Actions than Expected after calling addAction Method | Here is my class:
class ManagementReview(object):
"""Class describing ManagementReview Object.
"""
# Class attributes
id = 0
Title = 'New Management Review Object'
fiscal_year = ''
region = ''
review_date = ''
date_completed = ''
prepared_by = ''
__goals = [] # List of <ManagementReviewGoals>.
__objectives = [] # List of <ManagementReviewObjetives>.
__actions = [] # List of <ManagementReviewActions>.
__deliverables = [] # List of <ManagementReviewDeliverable>.
__issues = [] # List of <ManagementReviewIssue>.
__created = ''
__created_by = ''
__modified = ''
__modified_by = ''
def __init__(self,Title='',id=0,fiscal_year='',region='',review_date='',
date_completed='',prepared_by='',created='',created_by='',
modified='',modified_by=''):
"""Instantiate object.
"""
if id:
self.setId(id)
if Title:
self.setTitle(Title)
if fiscal_year:
self.setFiscal_year(fiscal_year)
if region:
self.setRegion(region)
if review_date:
self.setReview_date(review_date)
if date_completed:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setDate_completed(date_completed)
if prepared_by:
self.setPrepared_by(prepared_by)
if created:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setCreated(created)
else:
self.setCreated(self.getNow())
if created_by:
self.setCreated_by(created_by)
self.__modified = self.getNow()
if modified_by:
self.__modified_by = modified_by
def __str__(self):
return "<ManagementReview '%s (%s)'>" % (self.Title,self.id)
def __setattr__(self, name, value): # Override built-in setter
# set the value like usual and then update the modified attribute too
object.__setattr__(self, name, value) # Built-in
self.__dict__['__modified'] = datetime.now().isoformat()
def getActions(self):
return self.__actions
def addAction(self,mra):
self.__actions.append(mra)
def removeAction(self,id):
pass # XXX TODO
I have this test:
from datetime import datetime
import random
import unittest
from ManagementReview import ManagementReview, ManagementReviewAction
# Default Values for ManagementReviewAction Object Type
DUMMY_ID = 1
DUMMY_ACTION = 'Action 1'
DUMMY_OWNER = 'Owner 1'
DUMMY_TITLE = 'Test MR'
DUMMY_FISCAL_YEAR = '2011'
DUMMY_REGION = 'WO'
DUMMY_REVIEW_DATE = '2009-01-18T10:50:21.766169',
DUMMY_DATE_COMPLETED = '2008-07-18T10:50:21.766169'
DUMMY_PREPARED_BY = 'test user'
DUMMY_CREATED = '2002-07-18T10:50:21.766169'
DUMMY_CREATED_BY = 'test user 2'
DUMMY_MODIFIED = datetime.now().isoformat()
DUMMY_MODIFIED_BY = 'test user 3'
class TestManagementReviewSetAction(unittest.TestCase):
def setUp(self):
self.mr = ManagementReview(DUMMY_TITLE,DUMMY_ID,fiscal_year=DUMMY_FISCAL_YEAR,region=DUMMY_REGION,
review_date=DUMMY_REVIEW_DATE,date_completed=DUMMY_DATE_COMPLETED,
prepared_by=DUMMY_PREPARED_BY,created=DUMMY_CREATED,
created_by=DUMMY_CREATED_BY,modified=DUMMY_MODIFIED,
modified_by=DUMMY_MODIFIED_BY)
def tearDown(self):
self.mr = None
def test_add_action(self):
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.assertEqual(len(self.mr.getActions()),10)
def test_remove_action(self):
print len(self.mr.getActions())
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.mr.removeAction(3)
self.assertEqual(len(self.mr.getActions()),9)
if __name__ == '__main__':
unittest.main()
The first test passes. That is, self.mr.getActions() has 10 actions.
However, when I run the 2nd test, test_remove_action, the value for len(self.mr.getActions()) is 10. At this point, though, it should be 0.
Why is this?
Thanks
| [
"see if you are keeping track of actions in a class attribute of ManagementReview as opposed to an instance attribute\nA class attribute will be something like\nclass Spam(object):\n actions = []\n\nand an instance attribute will look something like\nclass Spam(object):\n def __init__(self):\n self.act... | [
0
] | [] | [] | [
"class_design",
"python",
"unit_testing"
] | stackoverflow_0003331059_class_design_python_unit_testing.txt |
Q:
IronPython: Is there an alternative to significant whitespace?
For rapidly changing business rules, I'm storing IronPython fragments in XML files. So far this has been working out well, but I'm starting to get to the point where I need more that just one-line expressions.
The problem is that XML and significant whilespace don't play well together. Before I abandon it for another language, I would like to know if IronPython has an alternative syntax.
A:
IronPython doesn't have an alternate syntax. It's an implementation of Python, and Python uses significant indentation (all languages use significant whitespace, not sure why we talk about whitespace when it's only indentation that's unusual in the Python case).
A:
>>> from __future__ import braces
File "<stdin>", line 1
from __future__ import braces
^
SyntaxError: not a chance
A:
All I want is something that will let my users write code like
Ummm... Don't do this. You don't actually want this. In the long run, this will cause endless little issues because you're trying to force too much content into an attribute.
Do this.
<Rule Name="Markup">
<Formula>(Account.PricingLevel + 1) * .05</Formula>
</Rule>
You should try not to have significant, meaningful stuff in attributes. As a general XML design policy, you should use tags and save attributes for names and ID's and the like. When you look at well-done XSD's and DTD's, you see that attributes are used minimally.
Having the body of the rule in a separate tag (not an attribute) saves much pain. And it allows a tool to provide correct CDATA sections. Use a tool like Altova's XML Spy to assure that your tags have space preserved properly.
A:
I think you can set the xml:space="preserve" attribute or use a <![CDATA[ to avoid other issues, with for example quotes and greater equal signs.
A:
Apart from the already mentioned CDATA sections, there's pindent.py which can, among others, fix broken indentation based on comments a la #end if - to quote the linked file:
When called as "pindent -r" it assumes its input is a Python program with block-closing comments but with its indentation messed up, and outputs a properly indented version.
...
A "block-closing comment" is a comment of the form '# end <keyword>' where is the keyword that opened the block. If the opening keyword is 'def' or 'class', the function or class name may be repeated in the block-closing comment as well. Here is an example of a program fully augmented with block-closing comments:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
It's bundeled with CPython, but if IronPython doesn't have it, just grab it from the repository.
| IronPython: Is there an alternative to significant whitespace? | For rapidly changing business rules, I'm storing IronPython fragments in XML files. So far this has been working out well, but I'm starting to get to the point where I need more that just one-line expressions.
The problem is that XML and significant whilespace don't play well together. Before I abandon it for another language, I would like to know if IronPython has an alternative syntax.
| [
"IronPython doesn't have an alternate syntax. It's an implementation of Python, and Python uses significant indentation (all languages use significant whitespace, not sure why we talk about whitespace when it's only indentation that's unusual in the Python case).\n",
">>> from __future__ import braces\n File \"... | [
5,
4,
3,
2,
2
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0003330983_ironpython_python.txt |
Q:
Strip the last character sent by JavaScript through websockets to Python
I'm currently trying out websockets, creating a client in JavaScript and a server in Python.
I'm stuck on a simple problem, though: when I send something from the client to the server it always contains a special ending character, but I don't know how to remove it.
I've tried data[:-1] thinking that would get rid of it, but it didn't.
With the character my JSON code won't validate.
This is what I send through JavaScript:
ws.send('{"test":"test"}');
This is what I get in python:
{"test":"test"}�
I thought the ending character was \xff
A:
The expression "data[:-1]" is an expression that produces a copy of data missing the last character. It doesn't modify the "data" variable. To do that, you have to assign back to "data", like so:
data = data[:-1]
My suspicion is the "special ending character" is a bug, somewhere, either in your code or how you're using the APIs. Network code does not generally introduce random characters into the data stream. Good luck!
| Strip the last character sent by JavaScript through websockets to Python | I'm currently trying out websockets, creating a client in JavaScript and a server in Python.
I'm stuck on a simple problem, though: when I send something from the client to the server it always contains a special ending character, but I don't know how to remove it.
I've tried data[:-1] thinking that would get rid of it, but it didn't.
With the character my JSON code won't validate.
This is what I send through JavaScript:
ws.send('{"test":"test"}');
This is what I get in python:
{"test":"test"}�
I thought the ending character was \xff
| [
"The expression \"data[:-1]\" is an expression that produces a copy of data missing the last character. It doesn't modify the \"data\" variable. To do that, you have to assign back to \"data\", like so:\ndata = data[:-1]\n\nMy suspicion is the \"special ending character\" is a bug, somewhere, either in your code ... | [
1
] | [] | [] | [
"javascript",
"python",
"websocket"
] | stackoverflow_0003331220_javascript_python_websocket.txt |
Q:
How would an irc bot written in tcl stack up against a python/node.js clone?
I believe eggdrop is the most active/popular bot and it's written in tcl ( and according to wiki the core is C but I haven't confirmed that ).
I'm wondering if there would be any performance benefit of recoding it's functionality in node.js or Python, in addition to making it more accessible since Python and JS are arguably more popular languages and not many are familiar with tcl.
So, how would they stack up vs tcl in general, performance-wise?
A:
As you suspected, eggdrop is not written in tcl, it is written in C, however it does use tcl as its scripting/extension language.
I would expect that in the case of an eggdrop, the performance difference between using tcl as a scripting language, and using Python, Lua, JS, or virtually anything else would be negligible, as eggdrops generally aren't performing high load tasks.
In the event it really was an issue, your question would need more specifics. Performance for what task under what conditions? Memory use? CPU efficiency? Latency? And the answer would probably be "measure and find out". Given the typical use of an eggdrop, it doesn't take particularly efficient code to respond to the occasional IRC trigger command once every few minutes or hours.
As a more general case, I'm sure you could find benchmark comparisons of specific algorithms or tasks performed by various scripting languages on particular operating systems or environments, at which point it wouldn't really have anything to do with IRC or eggdrop.
A:
If you're not doing much other than waiting on a quiet channel for something to happen, performance is pretty much irrelevant. You could probably write that in BF (well, with network connectivity primitives added) and have it perform OK.
If you're running on lots of busy channels with many things being watched for, that's different. Tcl's very good at event-driven IO, which is ideal for this sort of situation. (Python can do that, but needs external libraries, as does Lua. I don't know JS enough to comment there.)
If you're needing to do significant non-IO-bound processing for some message responses, you're into needing threads. I know that both Tcl and Python support threads, but with utterly different threading models (Python has a shared-memory model which makes it easier to pass some types of task around, especially when the data is large, and Tcl has an apartment model which greatly reduces the amount of locking required in the implementation for a good performance boost in CPU-bound code).
How is that relevant for IRC bots? Well, it all depends on what you're doing in the bot.
| How would an irc bot written in tcl stack up against a python/node.js clone? | I believe eggdrop is the most active/popular bot and it's written in tcl ( and according to wiki the core is C but I haven't confirmed that ).
I'm wondering if there would be any performance benefit of recoding it's functionality in node.js or Python, in addition to making it more accessible since Python and JS are arguably more popular languages and not many are familiar with tcl.
So, how would they stack up vs tcl in general, performance-wise?
| [
"As you suspected, eggdrop is not written in tcl, it is written in C, however it does use tcl as its scripting/extension language.\nI would expect that in the case of an eggdrop, the performance difference between using tcl as a scripting language, and using Python, Lua, JS, or virtually anything else would be negl... | [
6,
4
] | [] | [] | [
"eggdrop",
"irc",
"node.js",
"python",
"tcl"
] | stackoverflow_0003331027_eggdrop_irc_node.js_python_tcl.txt |
Q:
Django aggregate and grouping : code cleanliness problem
Here is a small problem I am having.
3 very simple models :
>>> class Instrument(models.Model):
... name = models.CharField(max_length=100)
...
>>> class Musician(models.Model):
... instrument = models.ForeignKey(Instrument)
...
>>> class Song(models.Model):
... author = models.ForeignKey(Musician)
I would like to count the number of songs, grouped by instrument name and by author
I have solutions to it, but I would like to know what is the best way to write it in pure django-orm, such as the code would be clean, concise and reusable (I mean something that you can easily re-use to group by different attributes). What I am actually trying to see is if some code I have written to solve this problem generically is really useful, or if I just missed something big ...
Here's the first solution I think of :
results = []
for instrument_name in Instrument.objects.values_list('instrument', flat=True):
for musician in Musician.objects.filter(instrument__name=instrument_name):
results.append((
instrument_name,
musician,
Song.objects.filter(author=musician).count())
)
Thank you for your help !!!
A:
from Django docs:
from django.db.models import Count
Song.objects.values('author','author__instrument').annotate(Count("id"))
I'm not 100% sure it will work (it's 2:20 AM), but I hope so.
| Django aggregate and grouping : code cleanliness problem | Here is a small problem I am having.
3 very simple models :
>>> class Instrument(models.Model):
... name = models.CharField(max_length=100)
...
>>> class Musician(models.Model):
... instrument = models.ForeignKey(Instrument)
...
>>> class Song(models.Model):
... author = models.ForeignKey(Musician)
I would like to count the number of songs, grouped by instrument name and by author
I have solutions to it, but I would like to know what is the best way to write it in pure django-orm, such as the code would be clean, concise and reusable (I mean something that you can easily re-use to group by different attributes). What I am actually trying to see is if some code I have written to solve this problem generically is really useful, or if I just missed something big ...
Here's the first solution I think of :
results = []
for instrument_name in Instrument.objects.values_list('instrument', flat=True):
for musician in Musician.objects.filter(instrument__name=instrument_name):
results.append((
instrument_name,
musician,
Song.objects.filter(author=musician).count())
)
Thank you for your help !!!
| [
"from Django docs:\nfrom django.db.models import Count\nSong.objects.values('author','author__instrument').annotate(Count(\"id\"))\n\nI'm not 100% sure it will work (it's 2:20 AM), but I hope so.\n"
] | [
4
] | [] | [] | [
"django",
"group_by",
"python"
] | stackoverflow_0003331299_django_group_by_python.txt |
Q:
Python: Unpacking an inner nested tuple/list while still getting its index number
I am familiar with using enumerate():
>>> seq_flat = ('A', 'B', 'C')
>>> for num, entry in enumerate(seq_flat):
print num, entry
0 A
1 B
2 C
I want to be able to do the same for a nested list:
>>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat'))
I can unpack it with:
>>> for letter, word in seq_nested:
print letter, word
A Apple
B Boat
C Cat
How should I unpack it to get the following?
0 A Apple
1 B Boat
2 C Cat
The only way I know is to use a counter/incrementor, which is un-Pythonic as far as I know. Is there a more elegant way to do it?
A:
for i, (letter, word) in enumerate(seq_nested):
print i, letter, word
| Python: Unpacking an inner nested tuple/list while still getting its index number | I am familiar with using enumerate():
>>> seq_flat = ('A', 'B', 'C')
>>> for num, entry in enumerate(seq_flat):
print num, entry
0 A
1 B
2 C
I want to be able to do the same for a nested list:
>>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat'))
I can unpack it with:
>>> for letter, word in seq_nested:
print letter, word
A Apple
B Boat
C Cat
How should I unpack it to get the following?
0 A Apple
1 B Boat
2 C Cat
The only way I know is to use a counter/incrementor, which is un-Pythonic as far as I know. Is there a more elegant way to do it?
| [
"for i, (letter, word) in enumerate(seq_nested):\n print i, letter, word\n\n"
] | [
84
] | [] | [] | [
"enumerate",
"iterable_unpacking",
"list",
"python",
"tuples"
] | stackoverflow_0003331643_enumerate_iterable_unpacking_list_python_tuples.txt |
Q:
Resuming a large file write in Python
I have a big file transfer (say 4gb or so) and rather than using shutil, I'm just opening and writing it the normal file way so I can include a progress percentage as it moves along.
It then occurred to me to try to attempt to resume the file write, if for some reason it borked out during the process. I haven't had any luck though. I presumed it would be some clever combination of offsetting the read of the source file and using seek, but I haven't had any luck so far. Any ideas?
Additionally, is there some sort of dynamic way to figure what block size to use when reading and writing files? I'm fairly novice to that area, and just read to use a larger size for larger file (I'm using 65536 at the moment). Is there a smart way to do it, or does one simply guess..? Thanks guys.
Here is the code snippet of the appending file transfer:
newsrc = open(src, 'rb')
dest_size = os.stat(destFile).st_size
print 'Dest file exists, resuming at block %s' % dest_size
newsrc.seek(dest_size)
newdest = open(destFile, 'a')
cur_block_pos = dest_size
# Start copying file
while True:
cur_block = newsrc.read(131072)
cur_block_pos += 131072
if not cur_block:
break
else:
newdest.write(cur_block)
It does append and start writing, but it then writes dest_size more data at the end than it should for probably obvious reasons to the rest of you. Any ideas?
A:
For the second part of your question, data is typically read from and written to a hard drive in blocks of 512 bytes. So using a block size that is a multiple of that should give the most efficient transfer. Other than that, it doesn't matter much. Just keep in mind that whatever block size you specify is the amount of data that the I/O operation stores in memory at any given time, so don't choose something so large that it uses up a lot of your RAM. I think 8K (8192) is a common choice, but 64K should be fine. (I don't think the size of the file being transferred matters much when you're choosing the best block size)
| Resuming a large file write in Python | I have a big file transfer (say 4gb or so) and rather than using shutil, I'm just opening and writing it the normal file way so I can include a progress percentage as it moves along.
It then occurred to me to try to attempt to resume the file write, if for some reason it borked out during the process. I haven't had any luck though. I presumed it would be some clever combination of offsetting the read of the source file and using seek, but I haven't had any luck so far. Any ideas?
Additionally, is there some sort of dynamic way to figure what block size to use when reading and writing files? I'm fairly novice to that area, and just read to use a larger size for larger file (I'm using 65536 at the moment). Is there a smart way to do it, or does one simply guess..? Thanks guys.
Here is the code snippet of the appending file transfer:
newsrc = open(src, 'rb')
dest_size = os.stat(destFile).st_size
print 'Dest file exists, resuming at block %s' % dest_size
newsrc.seek(dest_size)
newdest = open(destFile, 'a')
cur_block_pos = dest_size
# Start copying file
while True:
cur_block = newsrc.read(131072)
cur_block_pos += 131072
if not cur_block:
break
else:
newdest.write(cur_block)
It does append and start writing, but it then writes dest_size more data at the end than it should for probably obvious reasons to the rest of you. Any ideas?
| [
"For the second part of your question, data is typically read from and written to a hard drive in blocks of 512 bytes. So using a block size that is a multiple of that should give the most efficient transfer. Other than that, it doesn't matter much. Just keep in mind that whatever block size you specify is the amou... | [
1
] | [] | [] | [
"file_io",
"python",
"resume"
] | stackoverflow_0003331825_file_io_python_resume.txt |
Q:
certain utf characters do not show up on browsers and fails python script
I generated a SQL script from a C# application on Windows 7. The name entries have utf8 characters. It works find on Windows machine where I use a python script to populate the db. Now the same script fails on Linux platform complaining about those special characters.
Similar things happened when I generated XML file containing utf chars on Windows 7 but fails to show up on browsers (IE, Firefox.).
I used to generate such scripts on Windows XP and it worked perfect everywhere.
A:
Please give a small example of a script with "utf8 characters" in the "name entries". Are you sure that they are utf8 and not some windows encoding like `cp1252'? What makes you sure? Try this in Python at the command prompt:
... python -c "print repr(open('small_script.sql', 'rb').read())"
The interesting parts of the output are where it uses \xhh (where h is any hex digit) to represent non-ASCII characters e.g. \xc3\xa2 is the UTF-8 encoding of the small a with circumflex accent. Show us a representative sample of such output. Also tell us the exact error message(s) that you get from that sample script.
Update: It appears that you have data encoded in cp1252 or similar (Latin1 aka ISO-8859-1 is as rare as hen's teeth on Windows). To get that into UTF-8 using Python, you'd do fixed_data = data.decode('cp1252').encode('utf8'); I can't help you with C# -- you may like to ask a separate question about that.
A:
Assuming you're using python, make sure you are using Unicode strings.
For example:
s = "Hello world" # Regular String
u = u"Hello Unicode world" # Unicdoe String
Edit:
Here's an example of reading from a UTF-8 file from the linked site:
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file
| certain utf characters do not show up on browsers and fails python script | I generated a SQL script from a C# application on Windows 7. The name entries have utf8 characters. It works find on Windows machine where I use a python script to populate the db. Now the same script fails on Linux platform complaining about those special characters.
Similar things happened when I generated XML file containing utf chars on Windows 7 but fails to show up on browsers (IE, Firefox.).
I used to generate such scripts on Windows XP and it worked perfect everywhere.
| [
"Please give a small example of a script with \"utf8 characters\" in the \"name entries\". Are you sure that they are utf8 and not some windows encoding like `cp1252'? What makes you sure? Try this in Python at the command prompt:\n... python -c \"print repr(open('small_script.sql', 'rb').read())\"\n\nThe interesti... | [
1,
0
] | [] | [] | [
"c#",
"character_encoding",
"python",
"utf_8",
"windows_7"
] | stackoverflow_0003331850_c#_character_encoding_python_utf_8_windows_7.txt |
Q:
Hierarchical Task Network Planner in Python
Is anyone aware of a hierarchical task network planner implemented in Python or Java? I've found a few open source systems, but they're all seemingly dead projects and haven't been maintained in years.
A:
How about JSHOP2?
| Hierarchical Task Network Planner in Python | Is anyone aware of a hierarchical task network planner implemented in Python or Java? I've found a few open source systems, but they're all seemingly dead projects and haven't been maintained in years.
| [
"How about JSHOP2?\n"
] | [
1
] | [] | [] | [
"artificial_intelligence",
"java",
"machine_learning",
"planning",
"python"
] | stackoverflow_0003326310_artificial_intelligence_java_machine_learning_planning_python.txt |
Q:
How do I get python.vim to work with vim?
I am playing around with vim and I heard that python.vim has some nifty settings for python.
Link to python.vim
http://www.vim.org/scripts/script.php?script_id=790
Q1: How do I integrate python.vim with vim?
Q2: Because I am not familiar with vim, if I use something like python.vim will it have a crazy effect on non-python files or will the settings just apply to python files?
Update:
I already places the file in the appropriate directory as instructed by the link I posted. It doesn't appear to be working with vim. Do I have to source it some how from vim? From outside of vim? I feel like I have tried both and neither are working.
Also the directory the ~/.vim/syntax/ folder did not exist. I had to create it.
FYI - I'm doing this on a MAC.
A:
Q1:
Follow the installation details in the python.vim files description
"install details
Place python.vim file in ~/.vim/syntax/ folder."
Q2:
python.vim is a filetype plugin so it will only work when you are editing .py files.
Regarding your update:
Try issuing the command:
:syntax on
This will turn on syntax highlighting. If you want this to always be on you can add it to ~/.vimrc
In addition to this you may need to add this to your .vimrc as well:
filetype plugin on
A:
install details
Place python.vim file in ~/.vim/syntax/ folder.
Quoted from http://www.vim.org/scripts/script.php?script_id=790
And it only applies to .py files.
| How do I get python.vim to work with vim? | I am playing around with vim and I heard that python.vim has some nifty settings for python.
Link to python.vim
http://www.vim.org/scripts/script.php?script_id=790
Q1: How do I integrate python.vim with vim?
Q2: Because I am not familiar with vim, if I use something like python.vim will it have a crazy effect on non-python files or will the settings just apply to python files?
Update:
I already places the file in the appropriate directory as instructed by the link I posted. It doesn't appear to be working with vim. Do I have to source it some how from vim? From outside of vim? I feel like I have tried both and neither are working.
Also the directory the ~/.vim/syntax/ folder did not exist. I had to create it.
FYI - I'm doing this on a MAC.
| [
"Q1: \nFollow the installation details in the python.vim files description\n\"install details\nPlace python.vim file in ~/.vim/syntax/ folder.\"\nQ2:\npython.vim is a filetype plugin so it will only work when you are editing .py files.\nRegarding your update:\nTry issuing the command:\n:syntax on\n\nThis will turn... | [
4,
0
] | [] | [] | [
"python",
"settings",
"vim"
] | stackoverflow_0003332144_python_settings_vim.txt |
Q:
Prepend prefix to list elements with list comprehension
Having a list like this:
['foo','spam','bar']
is it possible, using list comprehension, to obtain this list as result?
['foo','ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']
A:
In [67]: alist = ['foo','spam', 'bar']
In [70]: [prefix+elt for elt in alist for prefix in ('','ok.') ]
Out[70]: ['foo', 'ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']
A:
With list comprehensions, you're creating new lists, not appending elements to an existing list (which may be relevant on really large datasets)
Why does it have to be a list comprehension anyway? Just because python has them doesn't make it bad coding practice to use a for-loop.
| Prepend prefix to list elements with list comprehension | Having a list like this:
['foo','spam','bar']
is it possible, using list comprehension, to obtain this list as result?
['foo','ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']
| [
"In [67]: alist = ['foo','spam', 'bar']\n\nIn [70]: [prefix+elt for elt in alist for prefix in ('','ok.') ]\nOut[70]: ['foo', 'ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']\n\n",
"With list comprehensions, you're creating new lists, not appending elements to an existing list (which may be relevant on really large ... | [
31,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0003330880_list_comprehension_python.txt |
Q:
pyxmpp: quick tutorial for creating a muc client?
I'm attempting to write a quick load-test script for our ejabberd cluster that simply logs into a chat room, posts a couple of random messages, then exits.
We had attempted this particular test with tsung, but according to the authors, the muc functionality did not make it into this release.
pyxmpp seems to have this functionality, but darned if I can figure out how to make it work. Here's hoping someone has a quick explanation of how to build the client and join/post to the muc.
Thanks!
A:
Hey I stumbled over your question a few times, while trying the same thing.
Here is my answer:
Using http://pyxmpp.jajcus.net/svn/pyxmpp/trunk/examples/echobot.py as a quickstart, all you have to do is import the MUC-Stuff
from pyxmpp.jabber.muc import MucRoomState, MucRoomManager
And once your Client is connected, you can connect to your room:
def session_started(self):
"""Handle session started event. May be overriden in derived classes.
This one requests the user's roster and sends the initial presence."""
print u'SESSION STARTED'
self.request_roster()
p=Presence()
self.stream.send(p)
print u'ConnectToParty'
self.connectToMUC()
def connectToMUC(self):
self.roomManager = MucRoomManager(self.stream);
self.roomHandler = MucRoomHandler()
self.roomState = self.roomManager.join(
room=JID('room@conference.server.domain'),
nick='PartyBot',
handler=self.roomHandler,
history_maxchars=0,
password = None)
self.roomManager.set_handlers()
To send a message, all you have to do is call self.roomState.send_message("Sending this Message")
To do stuff, inherit from MucRoomHandler and react on events. Notice the "set_handlers()" to roomManager though, it's is important, otherwise callbacks will not be called..
| pyxmpp: quick tutorial for creating a muc client? | I'm attempting to write a quick load-test script for our ejabberd cluster that simply logs into a chat room, posts a couple of random messages, then exits.
We had attempted this particular test with tsung, but according to the authors, the muc functionality did not make it into this release.
pyxmpp seems to have this functionality, but darned if I can figure out how to make it work. Here's hoping someone has a quick explanation of how to build the client and join/post to the muc.
Thanks!
| [
"Hey I stumbled over your question a few times, while trying the same thing.\nHere is my answer:\nUsing http://pyxmpp.jajcus.net/svn/pyxmpp/trunk/examples/echobot.py as a quickstart, all you have to do is import the MUC-Stuff\nfrom pyxmpp.jabber.muc import MucRoomState, MucRoomManager\n\nAnd once your Client is con... | [
6
] | [] | [] | [
"ejabberd",
"multiuserchat",
"python",
"xmpp"
] | stackoverflow_0002364039_ejabberd_multiuserchat_python_xmpp.txt |
Q:
Python for-loop counter error
I am attempting to script a short code to figure out the number of days it takes to reach a given principal in the bank due to daily interest. Using my code below does not yield any errors when run in IDLE, but the counter returns 0. Any ideas what I missed?
def main():
# irrelevant code elided by msw, Bal, Int and Tar are numeric
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
print counter
A:
I'm not sure what you're getting at with this loop:
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
range(0) is an empty list, so the loop won't execute at all.
counter + 1 simply calculates one more than counter, it won't increment counter, you probably mean counter += 1
There's nothing in the loop that changes at each iteration, so if you ever get into it, it will be an infinite loop.
A:
I believe the formula to calculate final balance with interest is:
Final = Principal * ( 1 + interest ) ** interest_period
Assuming I got this correct, then you can find out how many interest periods it will take by:
def how_long(start_money, interest_rate, final_money):
day = 0
money = start_money
while True:
if money >= final_money:
break
day += 1
money = start_money * (1 + interest_rate)**day
return day, money
A:
In [5]: def test():
...: for i in range(0):
...: return '1'
...:
...:
In [6]: x = test()
In [7]: print x
------> print(x)
None
See the return value is 'None'.
I don't know what are you trying to do. But The basic mistake is the Argument of range(x) function. The range(0) always return empty list.
A:
That's because you put range(0) which is an empty loop. Perhaps you could consider a while loop?
A:
Your loop for i in range(0) doesn't actually execute. range(0) returns an empty list [] which will skip the body of your for loop.
A:
Please explain what you think this does? Please update your question with an English-language explanation of how many times you think this look will work.
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
Hint. The answer is zero. The question is "why?" and "what were you trying to do?"
A:
You have been told the three or more problems with your code. If there's no particular reason to use a loop, it's better calculated with a formula:
future_value = present_value * (1 + interest_rate_per_period) ** number_of periods
or, for short,
f = p * (1 + i) ** n
f / p = (1 + i) ** n
log(f / p) = n * log(1 + i)
n = log(f / p) / log(i + i)
Example: I have $5000; how many years will it take to grow to $10000 at 10% per annum?
>>> from math import log
>>> f = 10000.0
>>> p = 5000.0
>>> i = 0.1
>>> n = log(f / p) / log(1 + i)
>>> n
7.272540897341713
>>>
| Python for-loop counter error | I am attempting to script a short code to figure out the number of days it takes to reach a given principal in the bank due to daily interest. Using my code below does not yield any errors when run in IDLE, but the counter returns 0. Any ideas what I missed?
def main():
# irrelevant code elided by msw, Bal, Int and Tar are numeric
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
print counter
| [
"I'm not sure what you're getting at with this loop:\nfor i in range(0):\n if (Bal * Int) == Tar:\n print '1'\n else:\n counter + 1\n\n\nrange(0) is an empty list, so the loop won't execute at all.\ncounter + 1 simply calculates one more than counter, it won't increment counter, you probably mea... | [
6,
3,
2,
0,
0,
0,
0
] | [] | [] | [
"counter",
"for_loop",
"python"
] | stackoverflow_0003331591_counter_for_loop_python.txt |
Q:
How can I search a text in some website (not from the source) with Python?
I want to make an "autofill" that works like this:
The site contains the Name and down the Name has the field to write it.
So, I want to make a program the search the "Name" in the website, and before that, click down the "Name" and write the name (easy part)...
How can I search for it?
I can't use the site forms, because, everysite has different forms
A:
Try: Automate firefox with python? and https://addons.mozilla.org/en-US/firefox/addon/7620
| How can I search a text in some website (not from the source) with Python? | I want to make an "autofill" that works like this:
The site contains the Name and down the Name has the field to write it.
So, I want to make a program the search the "Name" in the website, and before that, click down the "Name" and write the name (easy part)...
How can I search for it?
I can't use the site forms, because, everysite has different forms
| [
"Try: Automate firefox with python? and https://addons.mozilla.org/en-US/firefox/addon/7620\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003331032_python.txt |
Q:
Python: How to override data attributes in method calls?
My question is how to use data attributes in a method but allow them to be overridden individually when calling the method. This example demonstrates how I tried to do it:
class Class:
def __init__(self):
self.red = 1
self.blue = 2
self.yellow = 3
def calculate(self, red=self.red, blue=self.blue, yellow=self.yellow):
return red + blue + yellow
C = Class
print C.calculate()
print C.calculate(red=4)
Does it makes sense what I am trying to accomplish? When the calculate function is called, I want it to use the data attributes for red, blue, and yellow by default. But if the method call explicitly specifies a different parameter (red=4), I want it to use that specified value instead. When I run this, it gives an error for using 'self.' in the parameters field (saying it's not defined). Is there a way to make this work? Thanks.
A:
You cannot refer to self since it's not in scope there yet.
The idiomatic way is to do this instead:
def calculate(self, red=None, blue=None, yellow=None):
if red is None:
red = self.red
if blue is None:
blue = self.blue
if yellow is None:
yellow = self.yellow
return red + blue + yellow
"Idiomatic", alas, doesn't always mean "nice, concise and Pythonic".
Edit: this doesn't make it any better, does it...
def calculate(self, red=None, blue=None, yellow=None):
red, blue, yellow = map(
lambda (a, m): m if a is None else a,
zip([red, blue, yellow], [self.red, self.blue, self.yellow]))
return red + blue + yellow
A:
Another option would be to use **kwargs and a class attribute:
class Calc:
defaults = {
'red': 1, 'blue': 2, 'yellow': 3
}
def __init__(self, **kwargs):
self.__dict__.update(self.defaults)
self.__dict__.update(kwargs)
A:
You can write it in less lines:
def calculate(self, red=None, blue=None, yellow=None):
red = self.red if red is None else red
blue = self.blue if blue is None else blue
yellow = self.yellow if yellow is None else yellow
return red + blue + yellow
| Python: How to override data attributes in method calls? | My question is how to use data attributes in a method but allow them to be overridden individually when calling the method. This example demonstrates how I tried to do it:
class Class:
def __init__(self):
self.red = 1
self.blue = 2
self.yellow = 3
def calculate(self, red=self.red, blue=self.blue, yellow=self.yellow):
return red + blue + yellow
C = Class
print C.calculate()
print C.calculate(red=4)
Does it makes sense what I am trying to accomplish? When the calculate function is called, I want it to use the data attributes for red, blue, and yellow by default. But if the method call explicitly specifies a different parameter (red=4), I want it to use that specified value instead. When I run this, it gives an error for using 'self.' in the parameters field (saying it's not defined). Is there a way to make this work? Thanks.
| [
"You cannot refer to self since it's not in scope there yet.\nThe idiomatic way is to do this instead:\ndef calculate(self, red=None, blue=None, yellow=None):\n if red is None:\n red = self.red\n if blue is None:\n blue = self.blue\n if yellow is None:\n yellow = self.yellow\n retur... | [
4,
1,
0
] | [] | [] | [
"attributes",
"methods",
"python"
] | stackoverflow_0003330874_attributes_methods_python.txt |
Q:
how to get started with google app-engine?
I m starting to build python application in windows platform using google appengine
whats the steps to debug and run my application
A:
On Windows I use Aptana.
Once you've installed that, run it, go to the Plugins tab and get Pydev.
Pydev has inbuilt support for google app engine - so you can create an app engine project, and then run or debug it. See these posts for more details:
http://pydev.blogspot.com/2009/05/testing-on-pydev-146-google-app-engine.html
http://pydev.blogspot.com/2009/05/pydev-146-released-google-app-engine-on.html
| how to get started with google app-engine? | I m starting to build python application in windows platform using google appengine
whats the steps to debug and run my application
| [
"On Windows I use Aptana.\nOnce you've installed that, run it, go to the Plugins tab and get Pydev.\nPydev has inbuilt support for google app engine - so you can create an app engine project, and then run or debug it. See these posts for more details:\nhttp://pydev.blogspot.com/2009/05/testing-on-pydev-146-google-a... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003332900_google_app_engine_python.txt |
Q:
How to capture the text wthin the brackets: (), using regex maybe?
any way would be fine. Perl, python, ruby...
A:
You can match this regex
\(.*?\)
Edit:
The above regex will also include the brackets as a part of matched string. To avoid getting the brackets as a part of match (i.e. only match string inside the starting and ending bracket, excluding brackets) you may use below regex.
(?<=\().*?(?=\))
A:
In perl, you can use this one,
Have a look
my $test = "Hello (Stack Overflow)";
$test =~ /\(([^)]+)\)/;
my $matched_string = $1;
print "$matched_string\n";
OUTPUT:
Stack Overflow
A:
Do you only want to match outer braces?
For example:
In Python:
s = "(here is some text for you (and me))"
import re
print ''.join(re.split(r"^\(|\)$", s))
# Returns "here is some text for you (and me)"
Otherwise:
s = "(here is some text for you (and me))"
import re
print [text for text in re.split(r"[()]", s) if text]
# Returns "['here is some text for you ', 'and me']"
A:
On capturing groups
A capturing group, usually denoted with surrounding round brackets, can capture what a pattern matches. These matches can then be queried after a successful match of the overall pattern.
Here's a simple pattern that contains 2 capturing groups:
(\d+) (cats|dogs)
\___/ \_________/
1 2
Given i have 16 cats, 20 dogs, and 13 turtles, there are 2 matches (as seen on rubular.com):
16 cats is a match: group 1 captures 16, group 2 captures cats
20 dogs is a match: group 1 captures 20, group 2 captures dogs
You can nest capturing groups, and there are rules specifying how they're numbered. Some flavors also allow you to explicitly name them.
References
regular-expressions.info/Use Round Brackets for Capturing
On repeated captures
Now consider this slight modification on the pattern:
(\d)+ (cats|dogs)
\__/ \_________/
1 2
Now group 1 matches \d, i.e. a single digit. In most flavor, a group that matches repeatedly (thanks to the + in this case) only gets to keep the last match. Thus, in most flavors, only the last digit that was matched is captured by group 1 (as seen on rubular.com):
16 cats is a match: group 1 captures 6, group 2 captures cats
20 dogs is a match: group 1 captures 0, group 2 captures dogs
References
regular-expressions.info/Repeating a Capturing Group vs Capturing a Repeated Group
Related questions specific to .NET
Is there a regex flavor that allows me to count the number of repetitions matched by * and +?
What’s the difference between “groups” and “captures” in .NET regular expressions?
Differences among .NET Capture, Group, Match
| How to capture the text wthin the brackets: (), using regex maybe? | any way would be fine. Perl, python, ruby...
| [
"You can match this regex\n\\(.*?\\)\n\nEdit:\nThe above regex will also include the brackets as a part of matched string. To avoid getting the brackets as a part of match (i.e. only match string inside the starting and ending bracket, excluding brackets) you may use below regex. \n(?<=\\().*?(?=\\))\n\n",
"In pe... | [
3,
2,
1,
0
] | [] | [] | [
"perl",
"python",
"regex",
"ruby"
] | stackoverflow_0003332442_perl_python_regex_ruby.txt |
Q:
NameError for using timeit in python
I got NameError when I try to run this codes."global name j is not defined". How can I fix it?
def test(j):
for i in range(j):
j = i**2
if __name__=='__main__':
from timeit import Timer
j = 30
t = Timer("test(j)","from __main__ import test")
print( t.timeit(j))
A:
Timer doesn't know about j. You need to do something like "test(%d)" % j (or from __main__ import j or put the definition of j inside the string, too).
Also, the argument to timeit is different from the argument to your test function (so the different uses of j are probably not what you should do or mean). The timeit argument gives the number of executions for the test function.
p.s. Note that you need to indent any code in your question to get it formatted
p.p.s. There used to be a comment here about not using from __main__ import but that actually does work!
| NameError for using timeit in python | I got NameError when I try to run this codes."global name j is not defined". How can I fix it?
def test(j):
for i in range(j):
j = i**2
if __name__=='__main__':
from timeit import Timer
j = 30
t = Timer("test(j)","from __main__ import test")
print( t.timeit(j))
| [
"Timer doesn't know about j. You need to do something like \"test(%d)\" % j (or from __main__ import j or put the definition of j inside the string, too).\nAlso, the argument to timeit is different from the argument to your test function (so the different uses of j are probably not what you should do or mean). The ... | [
3
] | [] | [] | [
"python",
"timeit"
] | stackoverflow_0003333256_python_timeit.txt |
Q:
Speeding up parsing of HUGE lists of dictionaries - Python
I'm using MongoDB an nosql database. Basically as a result of a query I have a list of dicts which themselves contains lists of dictionaries... which I need to work with.
Unfortunately dealing with all this data within Python can be brought to a crawl when the data is too much.
I have never had to deal with this problem, and it would be great if someone with experience could give a few suggestions. =)
A:
Do you really want all of that data back in your Python program? If so fetch it back a little at a time, but if all you want to do is summarise the data then use mapreduce in MongoDB to distribute the processing and just return the summarised data.
After all, the point about using a NoSQL database that cleanly shards all the data across multiple machines is precisely to avoid having to pull it all back onto a single machine for processing.
A:
Are you loading all the data into memory at once? If so you could be causing the OS to swap memory to disk, which can bring any system to a crawl. Dictionaries are hashtables so even an empty dict will use up a lot of memory, and from what you say you are creating a lot of them at once. I don't know the MongoDB API, but I presume there is a way of iterating through the results one at a time instead of reading in the entire set of result at once - try using that. Or rewrite your query to return a subset of the data.
If disk swapping is not the problem then profile the code to see what the bottleneck is, or put some sample code in your question. Without more specific information it is hard to give a more specific answer.
A:
If CPU is your bottleneck (and your problem can be parallelized), you can also consider using Python's multiprocessing module, Disco project or Parallel Python to utilize multiple cores and/or multiple machines.
| Speeding up parsing of HUGE lists of dictionaries - Python | I'm using MongoDB an nosql database. Basically as a result of a query I have a list of dicts which themselves contains lists of dictionaries... which I need to work with.
Unfortunately dealing with all this data within Python can be brought to a crawl when the data is too much.
I have never had to deal with this problem, and it would be great if someone with experience could give a few suggestions. =)
| [
"Do you really want all of that data back in your Python program? If so fetch it back a little at a time, but if all you want to do is summarise the data then use mapreduce in MongoDB to distribute the processing and just return the summarised data.\nAfter all, the point about using a NoSQL database that cleanly sh... | [
3,
1,
1
] | [] | [] | [
"dictionary",
"list",
"parsing",
"python",
"sorting"
] | stackoverflow_0003330668_dictionary_list_parsing_python_sorting.txt |
Q:
python: overriding access a var
I have a class:
class A:
s = 'some string'
b = <SOME OTHER INSTANCE>
now I want this class to have the functionality of a string whenever it can. That is:
a = A()
print a.b
will print b's value. But I want functions that expect a string (for example replace) to work. For example:
'aaaa'.replace('a', a)
to actually do:
'aaa'.replace('a', a.s)
I tried overidding __get__ but this isn't correct.
I see that you can do this by subclassing str, but is there a way without it?
A:
If you want your class to have the functionality of a string, just extend the built in string class.
>>> class A(str):
... b = 'some other value'
...
>>> a = A('x')
>>> a
'x'
>>> a.b
'some other value'
>>> 'aaa'.replace('a',a)
'xxx'
A:
Override __str__ or __unicode__ to set the string representation of an object (Python documentation).
A:
I found an answer in Subclassing Python tuple with multiple __init__ arguments .
I used Dave's solution and extended str, and then added a new function:
def __new__(self,a,b):
s=a
return str.__new__(A,s)
| python: overriding access a var | I have a class:
class A:
s = 'some string'
b = <SOME OTHER INSTANCE>
now I want this class to have the functionality of a string whenever it can. That is:
a = A()
print a.b
will print b's value. But I want functions that expect a string (for example replace) to work. For example:
'aaaa'.replace('a', a)
to actually do:
'aaa'.replace('a', a.s)
I tried overidding __get__ but this isn't correct.
I see that you can do this by subclassing str, but is there a way without it?
| [
"If you want your class to have the functionality of a string, just extend the built in string class.\n>>> class A(str):\n... b = 'some other value'\n...\n>>> a = A('x')\n>>> a\n'x'\n>>> a.b\n'some other value'\n>>> 'aaa'.replace('a',a)\n'xxx'\n\n",
"Override __str__ or __unicode__ to set the string represent... | [
7,
1,
1
] | [] | [] | [
"overriding",
"python"
] | stackoverflow_0003333101_overriding_python.txt |
Q:
Problem porting sudoku solver from C to Python
I recently wrote a sudoku solver in C to practice programming. After completing it I decided to write an equivalent program in Python for a comparison between the languages and more practice and this is where the problem is. It seems to be that a global variable (sudokupossibilities[][][]) I declared outside the while loop isn't available within the loop. I've tried adding print statements for debugging and it seems that it's set correctly (all ones) outside of the while loop, but once it enters the loop, the values are mostly zeros, with a few ones. The only way I've found to fix this is adding a statement after "for k in range(9):" setting it to a one there - which makes the following statement obsolete and slowing the program. Ive included the source code for the Python version below and the C version after it.
#! /usr/bin/python3.1
sudoku = [[0] * 9] * 9
sudokupossibilities = [[[1] * 9] * 9] * 9
completion = 0
#Input a set of values, storing them in the list "sudoku".
print("Input sudoku, using spaces to separate individual values and return \
to separate lines.")
for i in range(9):
string = input()
values = string.split(" ")
sudoku[i] = [int(y) for y in values]
for i in range(9):
for j in range(9):
for k in range(9):
print(i+1, j+1, k+1, "=", sudokupossibilities[i][j][k])
#Solve the puzzle.
while True:
for i in range(9):
for j in range(9):
#If the number is already known, go to the next.
if sudoku[i][j] != 0:
continue
#Check which values are possible.
for k in range(9):
#If the value is already eliminated, skip it.
if sudokupossibilities[i][j][k] == 0:
continue
print(i+1, j+1, k+1, "=", sudokupossibilities[i][j][k])
#If it overlaps horizontally, eliminate that possibility.
for l in range(9):
if ((sudoku[i][l]) == (k + 1)) & (l != j):
sudokupossibilities[i][j][k] = 0
#If it overlaps vertically, eliminate that possibility.
for l in range(9):
if ((sudoku[l][j]) == (k + 1)) & (l != i):
sudokupossibilities[i][j][k] = 0
#If it overlaps in the same 3x3 box, set to 0.
x = 0
y = 0
#Find which box it's in on the x axis.
for m in [0, 3, 6]:
for n in range(3):
if (m + n) == i:
x = m
#Find which box it's in on the y axis.
for m in [0, 3, 6]:
for n in range(3):
if (m + n) == j:
y = m
#Check for overlap.
for m in range(3):
for n in range(3):
if (sudoku[x+m][y+n] == (k + 1)) & ((x+m) != i) & ((y+n) != j):
sudokupossibilities[i][j][k] = 0
#Count the values possible for the square. If only one is possible, set it.
valuespossible = 0
valuetoset = 0
for l in range(9):
if sudokupossibilities[i][j][l] == 1:
valuespossible += 1
valuetoset = l + 1
if valuespossible == 1:
sudoku[i][j] = valuetoset
#Count the unsolved squares, if this is zero, the puzzle is solved.
completion = 0
for x in sudoku:
for y in x:
if y == 0:
completion += 1
if completion == 0:
break
else:
print(completion)
continue
#Print the array.
for x in sudoku:
for y in x:
print(y, end=" ")
print(end="\n")
C version:
#include <stdio.h>
int main() {
int sudoku[9][9];
int sudokupossibilities[9][9][9];
int completion = 0;
int valuespossible = 0;
int valuetoset = 0;
int x = 0;
int y = 0;
//Set sudoku to all zeros.
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
sudoku[i][j] = 0;
}
}
//Set sudokupossibilities to all ones.
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
for (int k = 0; k <= 8; k++) {
sudokupossibilities[i][j][k] = 1;
}
}
}
//Take an unsolved puzzle as input.
printf("Please input unsolved sudoku with spaces between each number, pressing enter after each line. Use zeros for unknowns.\n");
for (int i = 0; i <= 8; i++) {
scanf("%d %d %d %d %d %d %d %d %d", &sudoku[i][0], &sudoku[i][1],
&sudoku[i][2], &sudoku[i][3], &sudoku[i][4], &sudoku[i][5],
&sudoku[i][6], &sudoku[i][7], &sudoku[i][8]);
}
//Solve the puzzle.
while (1) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
//If the number is already known, go to the next.
if (sudoku[i][j] != 0) {
continue;
}
//Check which values are possible.
for (int k = 0; k <= 8; k++) {
//If it's already eliminated, it doesn't need to be checked.
if (sudokupossibilities[i][j][k] == 0) {
continue;
}
//If it overlaps horizontally, eliminate that possibility.
for (int l = 0; l <= 8; l++) {
if ((sudoku[i][l] == (k + 1)) && (l != j)) {
sudokupossibilities[i][j][k] = 0;
}
}
//If it overlaps vertically, eliminate that possibility.
for (int l = 0; l <= 8; l++) {
if ((sudoku[l][j] == (k + 1)) && (l != i)) {
sudokupossibilities[i][j][k] = 0;
}
}
//If it overlaps in the same 3x3 box, set to 0.
x = 0;
y = 0;
for (int m = 0; m <= 6; m += 3) {
for (int n = 0; n <= 2; n++) {
if ((m + n) == i) {
x = m;
}
}
}
for (int m = 0; m <= 6; m += 3) {
for (int n = 0; n <= 2; n++) {
if ((m + n) == j) {
y = m;
}
}
}
for (int m = 0; m <= 2; m++) {
for (int n = 0; n <= 2; n++) {
if ((sudoku[x+m][y+n] == (k + 1)) && ((x+m) != i) && ((y+n) != j)) {
sudokupossibilities[i][j][k] = 0;
}
}
}
}
//Count the values possible for the square. If only
//one is possible, set it.
valuespossible = 0;
valuetoset = 0;
for (int l = 0; l <= 8; l++) {
if (sudokupossibilities[i][j][l] == 1) {
valuespossible++;
valuetoset = l + 1;
}
}
if (valuespossible == 1) {
sudoku[i][j] = valuetoset;
}
}
}
//Count the unsolved squares, if this is zero, the puzzle is solved.
completion = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (sudoku[i][j] == 0) {
completion++;
}
}
}
if (completion == 0) {
break;
}
else {
continue;
}
}
//Print the completed puzzle.
printf("+-------+-------+-------+\n");
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (j == 0) {
printf("| ");
}
printf("%d ", sudoku[i][j]);
if ((j == 2) || (j == 5)) {
printf("| ");
}
if (j == 8) {
printf("|");
}
}
printf("\n");
if (((i + 1) % 3) == 0) {
printf("+-------+-------+-------+\n");
}
}
}
I'm using Python 3.1 and C99.
I'd also appreciate anything to do with the quality of my code (although I know my programs are lacking in functions - I've added them to the C version and plan to add them to the Python version after it's working).
Thanks.
Edit: an unsolved puzzle below.
0 1 0 9 0 0 0 8 7
0 0 0 2 0 0 0 0 6
0 0 0 0 0 3 2 1 0
0 0 1 0 4 5 0 0 0
0 0 2 1 0 8 9 0 0
0 0 0 3 2 0 6 0 0
0 9 3 8 0 0 0 0 0
7 0 0 0 0 1 0 0 0
5 8 0 0 0 6 0 9 0
A:
This line does not do what you think:
sudokupossibilities = [[[1] * 9] * 9] * 9
Try this simple program:
sudokupossibilities = [[[1] * 9] * 9] * 9
sudokupossibilities
sudokupossibilities[1][1][1]=2
sudokupossibilities
(And the output of a much-simplified version:)
>>> s=[[[1] * 3] * 3] * 3
>>> s
[[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]]]
>>> s[1][1][1]=2
>>> s
[[[1, 2, 1], [1, 2, 1], [1, 2, 1]], [[1, 2, 1], [1, 2, 1], [1, 2, 1]], [[1, 2, 1], [1, 2, 1], [1, 2, 1]]]
The elements in your array are not independent; it is an artifact of the * method. When used to clone a list, * gives you references to the list, rather than new copies. Hilarity ensues.
| Problem porting sudoku solver from C to Python | I recently wrote a sudoku solver in C to practice programming. After completing it I decided to write an equivalent program in Python for a comparison between the languages and more practice and this is where the problem is. It seems to be that a global variable (sudokupossibilities[][][]) I declared outside the while loop isn't available within the loop. I've tried adding print statements for debugging and it seems that it's set correctly (all ones) outside of the while loop, but once it enters the loop, the values are mostly zeros, with a few ones. The only way I've found to fix this is adding a statement after "for k in range(9):" setting it to a one there - which makes the following statement obsolete and slowing the program. Ive included the source code for the Python version below and the C version after it.
#! /usr/bin/python3.1
sudoku = [[0] * 9] * 9
sudokupossibilities = [[[1] * 9] * 9] * 9
completion = 0
#Input a set of values, storing them in the list "sudoku".
print("Input sudoku, using spaces to separate individual values and return \
to separate lines.")
for i in range(9):
string = input()
values = string.split(" ")
sudoku[i] = [int(y) for y in values]
for i in range(9):
for j in range(9):
for k in range(9):
print(i+1, j+1, k+1, "=", sudokupossibilities[i][j][k])
#Solve the puzzle.
while True:
for i in range(9):
for j in range(9):
#If the number is already known, go to the next.
if sudoku[i][j] != 0:
continue
#Check which values are possible.
for k in range(9):
#If the value is already eliminated, skip it.
if sudokupossibilities[i][j][k] == 0:
continue
print(i+1, j+1, k+1, "=", sudokupossibilities[i][j][k])
#If it overlaps horizontally, eliminate that possibility.
for l in range(9):
if ((sudoku[i][l]) == (k + 1)) & (l != j):
sudokupossibilities[i][j][k] = 0
#If it overlaps vertically, eliminate that possibility.
for l in range(9):
if ((sudoku[l][j]) == (k + 1)) & (l != i):
sudokupossibilities[i][j][k] = 0
#If it overlaps in the same 3x3 box, set to 0.
x = 0
y = 0
#Find which box it's in on the x axis.
for m in [0, 3, 6]:
for n in range(3):
if (m + n) == i:
x = m
#Find which box it's in on the y axis.
for m in [0, 3, 6]:
for n in range(3):
if (m + n) == j:
y = m
#Check for overlap.
for m in range(3):
for n in range(3):
if (sudoku[x+m][y+n] == (k + 1)) & ((x+m) != i) & ((y+n) != j):
sudokupossibilities[i][j][k] = 0
#Count the values possible for the square. If only one is possible, set it.
valuespossible = 0
valuetoset = 0
for l in range(9):
if sudokupossibilities[i][j][l] == 1:
valuespossible += 1
valuetoset = l + 1
if valuespossible == 1:
sudoku[i][j] = valuetoset
#Count the unsolved squares, if this is zero, the puzzle is solved.
completion = 0
for x in sudoku:
for y in x:
if y == 0:
completion += 1
if completion == 0:
break
else:
print(completion)
continue
#Print the array.
for x in sudoku:
for y in x:
print(y, end=" ")
print(end="\n")
C version:
#include <stdio.h>
int main() {
int sudoku[9][9];
int sudokupossibilities[9][9][9];
int completion = 0;
int valuespossible = 0;
int valuetoset = 0;
int x = 0;
int y = 0;
//Set sudoku to all zeros.
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
sudoku[i][j] = 0;
}
}
//Set sudokupossibilities to all ones.
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
for (int k = 0; k <= 8; k++) {
sudokupossibilities[i][j][k] = 1;
}
}
}
//Take an unsolved puzzle as input.
printf("Please input unsolved sudoku with spaces between each number, pressing enter after each line. Use zeros for unknowns.\n");
for (int i = 0; i <= 8; i++) {
scanf("%d %d %d %d %d %d %d %d %d", &sudoku[i][0], &sudoku[i][1],
&sudoku[i][2], &sudoku[i][3], &sudoku[i][4], &sudoku[i][5],
&sudoku[i][6], &sudoku[i][7], &sudoku[i][8]);
}
//Solve the puzzle.
while (1) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
//If the number is already known, go to the next.
if (sudoku[i][j] != 0) {
continue;
}
//Check which values are possible.
for (int k = 0; k <= 8; k++) {
//If it's already eliminated, it doesn't need to be checked.
if (sudokupossibilities[i][j][k] == 0) {
continue;
}
//If it overlaps horizontally, eliminate that possibility.
for (int l = 0; l <= 8; l++) {
if ((sudoku[i][l] == (k + 1)) && (l != j)) {
sudokupossibilities[i][j][k] = 0;
}
}
//If it overlaps vertically, eliminate that possibility.
for (int l = 0; l <= 8; l++) {
if ((sudoku[l][j] == (k + 1)) && (l != i)) {
sudokupossibilities[i][j][k] = 0;
}
}
//If it overlaps in the same 3x3 box, set to 0.
x = 0;
y = 0;
for (int m = 0; m <= 6; m += 3) {
for (int n = 0; n <= 2; n++) {
if ((m + n) == i) {
x = m;
}
}
}
for (int m = 0; m <= 6; m += 3) {
for (int n = 0; n <= 2; n++) {
if ((m + n) == j) {
y = m;
}
}
}
for (int m = 0; m <= 2; m++) {
for (int n = 0; n <= 2; n++) {
if ((sudoku[x+m][y+n] == (k + 1)) && ((x+m) != i) && ((y+n) != j)) {
sudokupossibilities[i][j][k] = 0;
}
}
}
}
//Count the values possible for the square. If only
//one is possible, set it.
valuespossible = 0;
valuetoset = 0;
for (int l = 0; l <= 8; l++) {
if (sudokupossibilities[i][j][l] == 1) {
valuespossible++;
valuetoset = l + 1;
}
}
if (valuespossible == 1) {
sudoku[i][j] = valuetoset;
}
}
}
//Count the unsolved squares, if this is zero, the puzzle is solved.
completion = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (sudoku[i][j] == 0) {
completion++;
}
}
}
if (completion == 0) {
break;
}
else {
continue;
}
}
//Print the completed puzzle.
printf("+-------+-------+-------+\n");
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (j == 0) {
printf("| ");
}
printf("%d ", sudoku[i][j]);
if ((j == 2) || (j == 5)) {
printf("| ");
}
if (j == 8) {
printf("|");
}
}
printf("\n");
if (((i + 1) % 3) == 0) {
printf("+-------+-------+-------+\n");
}
}
}
I'm using Python 3.1 and C99.
I'd also appreciate anything to do with the quality of my code (although I know my programs are lacking in functions - I've added them to the C version and plan to add them to the Python version after it's working).
Thanks.
Edit: an unsolved puzzle below.
0 1 0 9 0 0 0 8 7
0 0 0 2 0 0 0 0 6
0 0 0 0 0 3 2 1 0
0 0 1 0 4 5 0 0 0
0 0 2 1 0 8 9 0 0
0 0 0 3 2 0 6 0 0
0 9 3 8 0 0 0 0 0
7 0 0 0 0 1 0 0 0
5 8 0 0 0 6 0 9 0
| [
"This line does not do what you think:\nsudokupossibilities = [[[1] * 9] * 9] * 9\n\nTry this simple program:\nsudokupossibilities = [[[1] * 9] * 9] * 9\nsudokupossibilities\nsudokupossibilities[1][1][1]=2\nsudokupossibilities\n\n(And the output of a much-simplified version:)\n>>> s=[[[1] * 3] * 3] * 3\n>>> s\n[[[1... | [
12
] | [] | [] | [
"c",
"porting",
"python",
"scope",
"sudoku"
] | stackoverflow_0003333627_c_porting_python_scope_sudoku.txt |
Q:
Load c++ memory file into Python
I have a file that in C++ I load into array using below code:
int SomeTable[10000];
int LoadTable()
{
memset(SomeTable, 0, sizeof(SomeTable));
FILE * fin = fopen("SomeFile.dar", "rb");
size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
fclose(fin);
}
The file is binary code of 10000 integers, so in C++ it could be directly loaded into memory. Is there a fansy way of doing that in Python?
best regards,
Rok
A:
Let's write an array into a file using a short C code:
int main ()
{
FILE * pFile;
int a[3] = {1,2,3};
pFile = fopen ( "file.bin" , "wb" );
fwrite (a , 1 , sizeof(a) , pFile );
fclose (pFile);
return 0;
}
The binary file can be loaded directly into a python array
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import array
>>> a=array.array('l') # 'l' is the type code for signed integer
>>> file=open('file.bin','rb')
>>> a.read(file,3)
>>> print a
array('l', [1, 2, 3])
>>> print a[0]
1
| Load c++ memory file into Python | I have a file that in C++ I load into array using below code:
int SomeTable[10000];
int LoadTable()
{
memset(SomeTable, 0, sizeof(SomeTable));
FILE * fin = fopen("SomeFile.dar", "rb");
size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
fclose(fin);
}
The file is binary code of 10000 integers, so in C++ it could be directly loaded into memory. Is there a fansy way of doing that in Python?
best regards,
Rok
| [
"Let's write an array into a file using a short C code:\nint main ()\n{\n FILE * pFile;\n int a[3] = {1,2,3};\n pFile = fopen ( \"file.bin\" , \"wb\" );\n fwrite (a , 1 , sizeof(a) , pFile );\n fclose (pFile);\n return 0;\n}\n\nThe binary file can be loaded directly into a python array\nPython 2.6.5 (r265:790... | [
2
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003333604_c++_python.txt |
Q:
error on localhost
when i'm going to login i got the following error
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3199, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3142, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 524, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2449, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2401, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2438, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2309, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
for this i reinstall the google app engine but not get the result
what to do??
A:
App Engine runs Python 2.5. You need to install Python 2.5 and use that instead of 2.7.
| error on localhost | when i'm going to login i got the following error
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3199, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3142, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 524, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2449, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2401, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2438, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2309, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
for this i reinstall the google app engine but not get the result
what to do??
| [
"App Engine runs Python 2.5. You need to install Python 2.5 and use that instead of 2.7.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003333985_google_app_engine_python.txt |
Q:
Google app engine parsing xml more then 1 mb
Hi i need to parse xml file which is more then 1 mb in size, i know GAE can handle request and response up to 10 MB but as we need to use SAX parser API and API GAE has limit of 1 MB so is there way we can parse file more then 1 mb any ways.
A:
The 1MB limit doesn't apply to parsing; however, you can't fetch more than 1MB from URLfetch; you'll only get the first 1MB from the API.
It's probably not going to be possible to get the XML into your application using the URLfetch API. If the data is smaller than 10MB, you can arrange for an external process to POST it to your application and then process it. If it's between 10MB and 2GB, you'd need to use the Blobstore API to upload it, read it in to your application in 1MB chunks, and process the concatenation of those chunks.
| Google app engine parsing xml more then 1 mb | Hi i need to parse xml file which is more then 1 mb in size, i know GAE can handle request and response up to 10 MB but as we need to use SAX parser API and API GAE has limit of 1 MB so is there way we can parse file more then 1 mb any ways.
| [
"The 1MB limit doesn't apply to parsing; however, you can't fetch more than 1MB from URLfetch; you'll only get the first 1MB from the API.\nIt's probably not going to be possible to get the XML into your application using the URLfetch API. If the data is smaller than 10MB, you can arrange for an external process t... | [
2
] | [] | [] | [
"google_app_engine",
"parsing",
"python"
] | stackoverflow_0003332897_google_app_engine_parsing_python.txt |
Q:
Bitnami Trac 0.11.6 SVN Post commit hooks failing
Beating my head against a wall here for a day trying to get post commit hooks work so I can add refs/ close tickets in trac from an SVN commit.
I used the bitnami trac stack to install and am fairly happy with the way its setup.
Every commit though gives the error
svn: MERGE of "/svn/Project": 200 OK (http://10.0.0.204)
I can see from various posts that this is down to the post commit hook failing but thesvn commit succeding. I've used the standard script from the edgewall site and my files look like the below (sorry for the length these make the post but I guess the more info the better..)
post-commit.cmd
@ECHO OFF
:: POST-COMMIT HOOK
::
:: The post-commit hook is invoked after a commit. Subversion runs
:: this hook by invoking a program (script, executable, binary, etc.)
:: named 'post-commit' (for which this file is a template) with the
:: following ordered arguments:
::
:: [1] REPOS-PATH (the path to this repository)
:: [2] REV (the number of the revision just committed)
::
:: The default working directory for the invocation is undefined, so
:: the program should set one explicitly if it cares.
::
:: Because the commit has already completed and cannot be undone,
:: the exit code of the hook program is ignored. The hook program
:: can use the 'svnlook' utility to help it examine the
:: newly-committed tree.
::
:: On a Unix system, the normal procedure is to have 'post-commit'
:: invoke other programs to do the real work, though it may do the
:: work itself too.
::
:: Note that 'post-commit' must be executable by the user(s) who will
:: invoke it (typically the user httpd runs as), and that user must
:: have filesystem-level permission to access the repository.
::
:: On a Windows system, you should name the hook program
:: 'post-commit.bat' or 'post-commit.exe',
:: but the basic idea is the same.
::
:: The hook program typically does not inherit the environment of
:: its parent process. For example, a common problem is for the
:: PATH environment variable to not be set to its usual value, so
:: that subprograms fail to launch unless invoked via absolute path.
:: If you're having unexpected problems with a hook program, the
:: culprit may be unusual (or missing) environment variables.
::
:: Here is an example hook script, for a Unix /bin/sh interpreter.
:: For more examples and pre-written hooks, see those in
:: the Subversion repository at
:: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and
:: http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/
setlocal
:: Debugging setup
:: 1. Make a copy of this file.
:: 2. Enable the command below to call the copied file.
:: 3. Remove all other commands
::call %~dp0post-commit-run.cmd %* > %1/hooks/post-commit.log 2>&1
:: Call Trac post-commit hook
call %~dp0trac-post-commit-hook.cmd %* || exit 1
trac-post-commit-hook.cmd
@ECHO OFF
::
:: Trac post-commit-hook script for Windows
::
:: Contributed by markus, modified by cboos.
:: Usage:
::
:: 1) Insert the following line in your post-commit.bat script
::
:: call %~dp0\trac-post-commit-hook.cmd %1 %2
::
:: 2) Check the 'Modify paths' section below, be sure to set at least TRAC_ENV
setlocal
:: ----------------------------------------------------------
:: Modify paths here:
:: -- this one *must* be set
SET TRAC_ENV=E:\Trac\Project\Project
:: -- set if Python is not in the system path
:: SET PYTHON_PATH=
:: -- set to the folder containing trac/ if installed in a non-standard location
:: SET TRAC_PATH= "C:\Program Files\Bitnami Trac Stack\"
:: ----------------------------------------------------------
:: Do not execute hook if trac environment does not exist
IF NOT EXIST %TRAC_ENV% GOTO :EOF
set PATH=%PYTHON_PATH%;%PATH%
set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%
SET REV=%2
:: Resolve ticket references (fixes, closes, refs, etc.)
Python "%~dp0trac-post-commit-resolve-ticket-ref.py" -p "%TRAC_ENV%" -r "%REV%"
endlocal
haven't removed the comments from the trac path there but don't think it should be needed. Finally the script from edgewall..
trac-post-commit-resolve-ticket-ref.py
#!/usr/bin/env python
# trac-post-commit-hook
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
# This Subversion post-commit hook script is meant to interface to the
# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc
# system.
#
# It should be called from the 'post-commit' script in Subversion, such as
# via:
#
# REPOS="$1"
# REV="$2"
# TRAC_ENV="/path/to/tracenv"
#
# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
# -p "$TRAC_ENV" -r "$REV"
#
# (all the other arguments are now deprecated and not needed anymore)
#
# It searches commit messages for text in the form of:
# command #1
# command #1, #2
# command #1 & #2
# command #1 and #2
#
# Instead of the short-hand syntax "#1", "ticket:1" can be used as well, e.g.:
# command ticket:1
# command ticket:1, ticket:2
# command ticket:1 & ticket:2
# command ticket:1 and ticket:2
#
# In addition, the ':' character can be omitted and issue or bug can be used
# instead of ticket.
#
# You can have more than one command in a message. The following commands
# are supported. There is more than one spelling for each command, to make
# this as user-friendly as possible.
#
# close, closed, closes, fix, fixed, fixes
# The specified issue numbers are closed with the contents of this
# commit message being added to it.
# references, refs, addresses, re, see
# The specified issue numbers are left in their current status, but
# the contents of this commit message are added to their notes.
#
# A fairly complicated example of what you can do is with a commit message
# of:
#
# Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
#
# This will close #10 and #12, and add a note to #12.
import re
import os
import sys
from datetime import datetime
from optparse import OptionParser
parser = OptionParser()
depr = '(not used anymore)'
parser.add_option('-e', '--require-envelope', dest='envelope', default='',
help="""
Require commands to be enclosed in an envelope.
If -e[], then commands must be in the form of [closes #4].
Must be two characters.""")
parser.add_option('-p', '--project', dest='project',
help='Path to the Trac project.')
parser.add_option('-r', '--revision', dest='rev',
help='Repository revision number.')
parser.add_option('-u', '--user', dest='user',
help='The user who is responsible for this action '+depr)
parser.add_option('-m', '--msg', dest='msg',
help='The log message to search '+depr)
parser.add_option('-c', '--encoding', dest='encoding',
help='The encoding used by the log message '+depr)
parser.add_option('-s', '--siteurl', dest='url',
help=depr+' the base_url from trac.ini will always be used.')
(options, args) = parser.parse_args(sys.argv[1:])
if not 'PYTHON_EGG_CACHE' in os.environ:
os.environ['PYTHON_EGG_CACHE'] = os.path.join(options.project, '.egg-cache')
from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_ui import TicketModule
# TODO: move grouped_changelog_entries to model.py
from trac.util.text import to_unicode
from trac.util.datefmt import utc
from trac.versioncontrol.api import NoSuchChangeset
ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
ticket_reference = ticket_prefix + '[0-9]+'
ticket_command = (r'(?P<action>[A-Za-z]*).?'
'(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
(ticket_reference, ticket_reference))
if options.envelope:
ticket_command = r'\%s%s\%s' % (options.envelope[0], ticket_command,
options.envelope[1])
command_re = re.compile(ticket_command)
ticket_re = re.compile(ticket_prefix + '([0-9]+)')
class CommitHook:
_supported_cmds = {'close': '_cmdClose',
'closed': '_cmdClose',
'closes': '_cmdClose',
'fix': '_cmdClose',
'fixed': '_cmdClose',
'fixes': '_cmdClose',
'addresses': '_cmdRefs',
're': '_cmdRefs',
'references': '_cmdRefs',
'refs': '_cmdRefs',
'see': '_cmdRefs'}
def __init__(self, project=options.project, author=options.user,
rev=options.rev, url=options.url):
self.env = open_environment(project)
repos = self.env.get_repository()
repos.sync()
# Instead of bothering with the encoding, we'll use unicode data
# as provided by the Trac versioncontrol API (#1310).
try:
chgset = repos.get_changeset(rev)
except NoSuchChangeset:
return # out of scope changesets are not cached
self.author = chgset.author
self.rev = rev
self.msg = "(In [%s]) %s" % (rev, chgset.message)
self.now = datetime.now(utc)
cmd_groups = command_re.findall(self.msg)
tickets = {}
for cmd, tkts in cmd_groups:
funcname = CommitHook._supported_cmds.get(cmd.lower(), '')
if funcname:
for tkt_id in ticket_re.findall(tkts):
func = getattr(self, funcname)
tickets.setdefault(tkt_id, []).append(func)
for tkt_id, cmds in tickets.iteritems():
try:
db = self.env.get_db_cnx()
ticket = Ticket(self.env, int(tkt_id), db)
for cmd in cmds:
cmd(ticket)
# determine sequence number...
cnum = 0
tm = TicketModule(self.env)
for change in tm.grouped_changelog_entries(ticket, db):
if change['permanent']:
cnum += 1
ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
db.commit()
tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=0, modtime=self.now)
except Exception, e:
# import traceback
# traceback.print_exc(file=sys.stderr)
print>>sys.stderr, 'Unexpected error while processing ticket ' \
'ID %s: %s' % (tkt_id, e)
def _cmdClose(self, ticket):
ticket['status'] = 'closed'
ticket['resolution'] = 'fixed'
def _cmdRefs(self, ticket):
pass
if __name__ == "__main__":
if len(sys.argv) < 5:
print "For usage: %s --help" % (sys.argv[0])
print
print "Note that the deprecated options will be removed in Trac 0.12."
else:
CommitHook()
If anyone can see why the python script is failing in someway it would really help me out.
Thanks...
.wm
--- update
Traced out the command and got the following in the log file.
Traceback (most recent call last):
File "E:\Repos\Project\hooks\trac-post-commit-resolve-ticket-ref.py", line 209, in <module>
CommitHook()
File "E:\Repos\Project\hooks\trac-post-commit-resolve-ticket-ref.py", line 144, in __init__
repos = self.env.get_repository()
File "c:\program files\bitnami trac stack\trac\lib\site-packages\Trac-0.11.6-py2.5.egg\trac\env.py", line 305, in get_repository
return RepositoryManager(self).get_repository(authname)
File "c:\program files\bitnami trac stack\trac\lib\site-packages\Trac-0.11.6-py2.5.egg\trac\versioncontrol\api.py", line 142, in get_repository
error=to_unicode(connector.error)))
trac.core.TracError: Unsupported version control system "svn": "DLL load failed with error code 182"
As I had this working at some point before messing with SSL I'm wondering if something has been moved or deleted in error... any clues?
A:
Imports were working from command line. The problem turned out to be the path. It wasn't working setting the python path in the script file or as an system variable as PYTHON_PATH or PYTHONPATH. It would run the python command correctly like that but would then not use the correct svn bindings. Adding the python dir location to the system Path worked. thanks anyway!
| Bitnami Trac 0.11.6 SVN Post commit hooks failing | Beating my head against a wall here for a day trying to get post commit hooks work so I can add refs/ close tickets in trac from an SVN commit.
I used the bitnami trac stack to install and am fairly happy with the way its setup.
Every commit though gives the error
svn: MERGE of "/svn/Project": 200 OK (http://10.0.0.204)
I can see from various posts that this is down to the post commit hook failing but thesvn commit succeding. I've used the standard script from the edgewall site and my files look like the below (sorry for the length these make the post but I guess the more info the better..)
post-commit.cmd
@ECHO OFF
:: POST-COMMIT HOOK
::
:: The post-commit hook is invoked after a commit. Subversion runs
:: this hook by invoking a program (script, executable, binary, etc.)
:: named 'post-commit' (for which this file is a template) with the
:: following ordered arguments:
::
:: [1] REPOS-PATH (the path to this repository)
:: [2] REV (the number of the revision just committed)
::
:: The default working directory for the invocation is undefined, so
:: the program should set one explicitly if it cares.
::
:: Because the commit has already completed and cannot be undone,
:: the exit code of the hook program is ignored. The hook program
:: can use the 'svnlook' utility to help it examine the
:: newly-committed tree.
::
:: On a Unix system, the normal procedure is to have 'post-commit'
:: invoke other programs to do the real work, though it may do the
:: work itself too.
::
:: Note that 'post-commit' must be executable by the user(s) who will
:: invoke it (typically the user httpd runs as), and that user must
:: have filesystem-level permission to access the repository.
::
:: On a Windows system, you should name the hook program
:: 'post-commit.bat' or 'post-commit.exe',
:: but the basic idea is the same.
::
:: The hook program typically does not inherit the environment of
:: its parent process. For example, a common problem is for the
:: PATH environment variable to not be set to its usual value, so
:: that subprograms fail to launch unless invoked via absolute path.
:: If you're having unexpected problems with a hook program, the
:: culprit may be unusual (or missing) environment variables.
::
:: Here is an example hook script, for a Unix /bin/sh interpreter.
:: For more examples and pre-written hooks, see those in
:: the Subversion repository at
:: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and
:: http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/
setlocal
:: Debugging setup
:: 1. Make a copy of this file.
:: 2. Enable the command below to call the copied file.
:: 3. Remove all other commands
::call %~dp0post-commit-run.cmd %* > %1/hooks/post-commit.log 2>&1
:: Call Trac post-commit hook
call %~dp0trac-post-commit-hook.cmd %* || exit 1
trac-post-commit-hook.cmd
@ECHO OFF
::
:: Trac post-commit-hook script for Windows
::
:: Contributed by markus, modified by cboos.
:: Usage:
::
:: 1) Insert the following line in your post-commit.bat script
::
:: call %~dp0\trac-post-commit-hook.cmd %1 %2
::
:: 2) Check the 'Modify paths' section below, be sure to set at least TRAC_ENV
setlocal
:: ----------------------------------------------------------
:: Modify paths here:
:: -- this one *must* be set
SET TRAC_ENV=E:\Trac\Project\Project
:: -- set if Python is not in the system path
:: SET PYTHON_PATH=
:: -- set to the folder containing trac/ if installed in a non-standard location
:: SET TRAC_PATH= "C:\Program Files\Bitnami Trac Stack\"
:: ----------------------------------------------------------
:: Do not execute hook if trac environment does not exist
IF NOT EXIST %TRAC_ENV% GOTO :EOF
set PATH=%PYTHON_PATH%;%PATH%
set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%
SET REV=%2
:: Resolve ticket references (fixes, closes, refs, etc.)
Python "%~dp0trac-post-commit-resolve-ticket-ref.py" -p "%TRAC_ENV%" -r "%REV%"
endlocal
haven't removed the comments from the trac path there but don't think it should be needed. Finally the script from edgewall..
trac-post-commit-resolve-ticket-ref.py
#!/usr/bin/env python
# trac-post-commit-hook
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
# This Subversion post-commit hook script is meant to interface to the
# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc
# system.
#
# It should be called from the 'post-commit' script in Subversion, such as
# via:
#
# REPOS="$1"
# REV="$2"
# TRAC_ENV="/path/to/tracenv"
#
# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
# -p "$TRAC_ENV" -r "$REV"
#
# (all the other arguments are now deprecated and not needed anymore)
#
# It searches commit messages for text in the form of:
# command #1
# command #1, #2
# command #1 & #2
# command #1 and #2
#
# Instead of the short-hand syntax "#1", "ticket:1" can be used as well, e.g.:
# command ticket:1
# command ticket:1, ticket:2
# command ticket:1 & ticket:2
# command ticket:1 and ticket:2
#
# In addition, the ':' character can be omitted and issue or bug can be used
# instead of ticket.
#
# You can have more than one command in a message. The following commands
# are supported. There is more than one spelling for each command, to make
# this as user-friendly as possible.
#
# close, closed, closes, fix, fixed, fixes
# The specified issue numbers are closed with the contents of this
# commit message being added to it.
# references, refs, addresses, re, see
# The specified issue numbers are left in their current status, but
# the contents of this commit message are added to their notes.
#
# A fairly complicated example of what you can do is with a commit message
# of:
#
# Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
#
# This will close #10 and #12, and add a note to #12.
import re
import os
import sys
from datetime import datetime
from optparse import OptionParser
parser = OptionParser()
depr = '(not used anymore)'
parser.add_option('-e', '--require-envelope', dest='envelope', default='',
help="""
Require commands to be enclosed in an envelope.
If -e[], then commands must be in the form of [closes #4].
Must be two characters.""")
parser.add_option('-p', '--project', dest='project',
help='Path to the Trac project.')
parser.add_option('-r', '--revision', dest='rev',
help='Repository revision number.')
parser.add_option('-u', '--user', dest='user',
help='The user who is responsible for this action '+depr)
parser.add_option('-m', '--msg', dest='msg',
help='The log message to search '+depr)
parser.add_option('-c', '--encoding', dest='encoding',
help='The encoding used by the log message '+depr)
parser.add_option('-s', '--siteurl', dest='url',
help=depr+' the base_url from trac.ini will always be used.')
(options, args) = parser.parse_args(sys.argv[1:])
if not 'PYTHON_EGG_CACHE' in os.environ:
os.environ['PYTHON_EGG_CACHE'] = os.path.join(options.project, '.egg-cache')
from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_ui import TicketModule
# TODO: move grouped_changelog_entries to model.py
from trac.util.text import to_unicode
from trac.util.datefmt import utc
from trac.versioncontrol.api import NoSuchChangeset
ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
ticket_reference = ticket_prefix + '[0-9]+'
ticket_command = (r'(?P<action>[A-Za-z]*).?'
'(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
(ticket_reference, ticket_reference))
if options.envelope:
ticket_command = r'\%s%s\%s' % (options.envelope[0], ticket_command,
options.envelope[1])
command_re = re.compile(ticket_command)
ticket_re = re.compile(ticket_prefix + '([0-9]+)')
class CommitHook:
_supported_cmds = {'close': '_cmdClose',
'closed': '_cmdClose',
'closes': '_cmdClose',
'fix': '_cmdClose',
'fixed': '_cmdClose',
'fixes': '_cmdClose',
'addresses': '_cmdRefs',
're': '_cmdRefs',
'references': '_cmdRefs',
'refs': '_cmdRefs',
'see': '_cmdRefs'}
def __init__(self, project=options.project, author=options.user,
rev=options.rev, url=options.url):
self.env = open_environment(project)
repos = self.env.get_repository()
repos.sync()
# Instead of bothering with the encoding, we'll use unicode data
# as provided by the Trac versioncontrol API (#1310).
try:
chgset = repos.get_changeset(rev)
except NoSuchChangeset:
return # out of scope changesets are not cached
self.author = chgset.author
self.rev = rev
self.msg = "(In [%s]) %s" % (rev, chgset.message)
self.now = datetime.now(utc)
cmd_groups = command_re.findall(self.msg)
tickets = {}
for cmd, tkts in cmd_groups:
funcname = CommitHook._supported_cmds.get(cmd.lower(), '')
if funcname:
for tkt_id in ticket_re.findall(tkts):
func = getattr(self, funcname)
tickets.setdefault(tkt_id, []).append(func)
for tkt_id, cmds in tickets.iteritems():
try:
db = self.env.get_db_cnx()
ticket = Ticket(self.env, int(tkt_id), db)
for cmd in cmds:
cmd(ticket)
# determine sequence number...
cnum = 0
tm = TicketModule(self.env)
for change in tm.grouped_changelog_entries(ticket, db):
if change['permanent']:
cnum += 1
ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
db.commit()
tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=0, modtime=self.now)
except Exception, e:
# import traceback
# traceback.print_exc(file=sys.stderr)
print>>sys.stderr, 'Unexpected error while processing ticket ' \
'ID %s: %s' % (tkt_id, e)
def _cmdClose(self, ticket):
ticket['status'] = 'closed'
ticket['resolution'] = 'fixed'
def _cmdRefs(self, ticket):
pass
if __name__ == "__main__":
if len(sys.argv) < 5:
print "For usage: %s --help" % (sys.argv[0])
print
print "Note that the deprecated options will be removed in Trac 0.12."
else:
CommitHook()
If anyone can see why the python script is failing in someway it would really help me out.
Thanks...
.wm
--- update
Traced out the command and got the following in the log file.
Traceback (most recent call last):
File "E:\Repos\Project\hooks\trac-post-commit-resolve-ticket-ref.py", line 209, in <module>
CommitHook()
File "E:\Repos\Project\hooks\trac-post-commit-resolve-ticket-ref.py", line 144, in __init__
repos = self.env.get_repository()
File "c:\program files\bitnami trac stack\trac\lib\site-packages\Trac-0.11.6-py2.5.egg\trac\env.py", line 305, in get_repository
return RepositoryManager(self).get_repository(authname)
File "c:\program files\bitnami trac stack\trac\lib\site-packages\Trac-0.11.6-py2.5.egg\trac\versioncontrol\api.py", line 142, in get_repository
error=to_unicode(connector.error)))
trac.core.TracError: Unsupported version control system "svn": "DLL load failed with error code 182"
As I had this working at some point before messing with SSL I'm wondering if something has been moved or deleted in error... any clues?
| [
"Imports were working from command line. The problem turned out to be the path. It wasn't working setting the python path in the script file or as an system variable as PYTHON_PATH or PYTHONPATH. It would run the python command correctly like that but would then not use the correct svn bindings. Adding the python d... | [
3
] | [] | [] | [
"apache",
"bitnami",
"python",
"svn",
"trac"
] | stackoverflow_0003301079_apache_bitnami_python_svn_trac.txt |
Q:
Returning only No. of Google Search Results via Python
I wish to return only the number of google search results for a particular keyword in the fastest manner possible, avoiding (keeping to minimum) the use of third party libraries. I have already considered xgoogle.
A:
Take a look at Alex Martelli's example.
If you search for something vague like "cars", data will look something like the following. Notice that it isn't very long; you only get the top few hits, and a link to "moreResultsUrl". Therefore, it should be reasonably fast to make this query and look in
data['cursor']['estimatedResultCount'] for the estimated number of hits.
{'cursor': {'currentPageIndex': 0,
'estimatedResultCount': '168000000',
'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=cars',
'pages': [{'label': 1, 'start': '0'},
{'label': 2, 'start': '4'},
{'label': 3, 'start': '8'},
{'label': 4, 'start': '12'},
{'label': 5, 'start': '16'},
{'label': 6, 'start': '20'},
{'label': 7, 'start': '24'},
{'label': 8, 'start': '28'}]},
'results': [ <<list of 4 dicts>> ]}
| Returning only No. of Google Search Results via Python | I wish to return only the number of google search results for a particular keyword in the fastest manner possible, avoiding (keeping to minimum) the use of third party libraries. I have already considered xgoogle.
| [
"Take a look at Alex Martelli's example.\nIf you search for something vague like \"cars\", data will look something like the following. Notice that it isn't very long; you only get the top few hits, and a link to \"moreResultsUrl\". Therefore, it should be reasonably fast to make this query and look in \ndata['curs... | [
2
] | [
"You can use urllib for downloading the site and HTMLParser to parse out the \n<div id=\"resultStats\">....</div> values. Here is an example:\nHow can I use the python HTMLParser library to extract data from a specific div tag?\n"
] | [
-1
] | [
"python"
] | stackoverflow_0003334122_python.txt |
Q:
Finding what list a class instance is in, in Python
This problem is thus: I have an instance of a class, I want to know what list it is a part of, i.e. :
class test_class() :
def test() :
print 'I am a member of list', parent_list
foo = [test_class(), 52, 63]
bar = ['spam', 'eggs']
foo[0].test()
I would like to print out I am a member of list foo. There are an arbitrary number of lists that any given instance of test_class() could belong to.
A:
First of all, I don't know what could be the use-case for it, because ideally while putting objects in list, you can track them via a dict or even if you have list of all lists you can just check for objects in them, so a better design wouldn't need such search.
So lets suppose for fun we want to know which lists a object is in. We can utilize the fact that gc knows about all objects and who refers to it, so here is a which_list function which tells which lists refer to it ( that necessarily doesn't mean it contains it)
import gc
class A(object): pass
class B(A): pass
def which_list(self):
lists_referring_to_me = []
for obj in gc.get_referrers(self):
if isinstance(obj, list):
lists_referring_to_me.append(obj)
return lists_referring_to_me
a = A()
b = B()
foo = [a, 52, b]
bar = ['spam', b]
print which_list(a)
print which_list(b)
output:
[[<__main__.A object at 0x00B7FAD0>, 52, <__main__.B object at 0x00B7FAF0>]]
[[<__main__.A object at 0x00B7FAD0>, 52, <__main__.B object at 0x00B7FAF0>], ['spam', <__main__.B object at 0x00B7FAF0>]]
A:
Since lists have no names, this is not possible directly. You have to put the lists in some container which can remember the names, for example a class:
class container(object):
def locate(self, thing):
for name, member in self.__dict__:
if type(member) == type([]) and thing in member:
print 'Found it in',name
return
print 'Sorry, nothing found'
c = container()
c.foo = [test_class(), 52, 63]
c.bar = ['spam', 'eggs']
A:
You could use the globals() function to find all the currently defined global symbols, filter this to find all the lists and then check if the item is in them.
>>> class test_class():
... def test(self):
... print "I am a member of the following lists", \
... [name for (name,value) in globals().items() if isinstance(value,list) and self in value]
...
>>> foo = [test_class(), 52, 63]
>>> bar = ['spam', 'eggs']
>>> foo[0].test()
I am a member of the following lists ['foo']
A:
You can find all the lists that contain the object pretty easily, but it sounds like you are approaching this problem in entirely the wrong way. You would be much better to record in the instances a reference back to the lists that contain those objects.
However, since you ask, here's a literal answer to your question:
>>> import gc
>>> class test_class():
def test(self):
lists = [l for l in gc.get_referrers(self) if isinstance(l, list)]
print('I am in lists at ' + ','.join(str(id(l)) for l in lists))
>>> foo = [test_class(), 52, 63]
>>> bar = ['spam', 'eggs']
>>> foo[0].test()
I am in lists at 18704624
Note that of course you can find the lists, but that doesn't tell you any of the names that might be being used to reference those lists. If you need names then wrap the lists in a class which has a name and add back references to the containing classes from each test_class instance.
| Finding what list a class instance is in, in Python | This problem is thus: I have an instance of a class, I want to know what list it is a part of, i.e. :
class test_class() :
def test() :
print 'I am a member of list', parent_list
foo = [test_class(), 52, 63]
bar = ['spam', 'eggs']
foo[0].test()
I would like to print out I am a member of list foo. There are an arbitrary number of lists that any given instance of test_class() could belong to.
| [
"First of all, I don't know what could be the use-case for it, because ideally while putting objects in list, you can track them via a dict or even if you have list of all lists you can just check for objects in them, so a better design wouldn't need such search.\nSo lets suppose for fun we want to know which lists... | [
1,
0,
0,
0
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0003333494_introspection_python.txt |
Q:
commit & push to remote git repo via webhook?
I want to commit to a git repo from app-engine via webhooks. I cannot install git on appengine. Possible?
I think it should be on GitHub, because they have a browser based text editor which can commit via the browser. E.g. go here and click the edit button.
GitHub api docs imply read-only operations which doesn't seem to be true.
Also, is this a bad idea? I Know it'll be tough to scale.
A:
The tags say you're using python so this might not be particularly useful, but I do know there's a pure java implementation of git, JGit, which might work on the app engine. It doesn't look like you can really call java code from python, but you could use a separate instance that you create yourself and use some sort of secure communication channel between this and your app. Assuming there's no undocumented github API that does what you want, that is.
A:
I'm trying to do the same. I found http://samba.org/~jelmer/dulwich/ but this implementation uses the mmap module which is blocked in app engine.
@Dustin
Have you figgured a way to push into git repos from app engine
| commit & push to remote git repo via webhook? | I want to commit to a git repo from app-engine via webhooks. I cannot install git on appengine. Possible?
I think it should be on GitHub, because they have a browser based text editor which can commit via the browser. E.g. go here and click the edit button.
GitHub api docs imply read-only operations which doesn't seem to be true.
Also, is this a bad idea? I Know it'll be tough to scale.
| [
"The tags say you're using python so this might not be particularly useful, but I do know there's a pure java implementation of git, JGit, which might work on the app engine. It doesn't look like you can really call java code from python, but you could use a separate instance that you create yourself and use some s... | [
1,
0
] | [] | [] | [
"git",
"github",
"google_app_engine",
"python"
] | stackoverflow_0001989735_git_github_google_app_engine_python.txt |
Q:
Map comparison operators to function call
I'm building a DSL for form validation in Python, and one of the requirements is to be able to specify that a field should be greater than or less than a constant or another field value. As a result, I'm trying to easily map operators like <, >, <= and >= to their equivalent functions in the operator module, so that they can be called during field validation.
I realise I could just create a dictionary to map the operator to the function, but is there a nicer way to do it? Is there any way to access Python's built-in mapping?
A:
As far as I'm aware, there is no built-in dictionary mapping the string ">" to the function operator.lt, etc.
As others have pointed out, the Python interpreter itself does not make use of such a dictionary, since the process of parsing and executing Python code will first translate the character sequence ">" to a token representing that operator, which will then be translated to bytecode, and the result of executing that bytecode will execute the __lt__ method directly, rather than via the operator.lt function.
A:
Python's internal mapping of "<" to __lt__ (and so on) isn't exposed anywhere in the standard library. There's a lot about Python's internals that aren't exposed as a toolkit. I'm not even sure in general how such a mapping would be created. What maps onto __getitem__?
You'll just have to create your own mapping. It shouldn't be difficult.
| Map comparison operators to function call | I'm building a DSL for form validation in Python, and one of the requirements is to be able to specify that a field should be greater than or less than a constant or another field value. As a result, I'm trying to easily map operators like <, >, <= and >= to their equivalent functions in the operator module, so that they can be called during field validation.
I realise I could just create a dictionary to map the operator to the function, but is there a nicer way to do it? Is there any way to access Python's built-in mapping?
| [
"As far as I'm aware, there is no built-in dictionary mapping the string \">\" to the function operator.lt, etc.\nAs others have pointed out, the Python interpreter itself does not make use of such a dictionary, since the process of parsing and executing Python code will first translate the character sequence \">\"... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0003324788_python.txt |
Q:
Write a Plugin in Python for audio
I have written a script that on execution lets the user record a message by accessing their microphone and stores it.
I want to make this script useable over my website, which will require me to write a plug-in for the browser. Is there a good tutorial that will teach me how to write this plug in and set it up. is there another way.
A:
You'll definitely want to look at:
https://developer.mozilla.org/en/Plugins
and
http://code.google.com/chrome/extensions/npapi.html
That were from the post Ignacio linked: How to write a browser plugin?
| Write a Plugin in Python for audio | I have written a script that on execution lets the user record a message by accessing their microphone and stores it.
I want to make this script useable over my website, which will require me to write a plug-in for the browser. Is there a good tutorial that will teach me how to write this plug in and set it up. is there another way.
| [
"You'll definitely want to look at:\nhttps://developer.mozilla.org/en/Plugins\nand\nhttp://code.google.com/chrome/extensions/npapi.html\nThat were from the post Ignacio linked: How to write a browser plugin?\n"
] | [
0
] | [] | [] | [
"audio",
"plugins",
"python"
] | stackoverflow_0003292808_audio_plugins_python.txt |
Q:
Mysql connection with python in a class
i'm trying to connect to a database building a class connection()saved in local folder in file utils.py .This is what i worked so far of it:
class connection:
def __init__(self):
self.conn = MySQLdb.connect(host = "localhost",user = "xxx",
passwd = "xxx", db = "xxx",
cursorclass=MySQLdb.cursors.DictCursor)
def TearDown(self):
self.conn.close()
def nume(self):
return self.conn
and this is where i use it in code:
from utils import execute_sql,connection
con = connection.nume()
cursor = con.cursor()
....
cursor.execute(sql)
...
connection.TearDown()
i tryed several more but this way was the simplest, still getting some errors that i struggle with;
A:
The glaring issue is that you need to instantiate your "connection" class before calling methods.
from utils import execute_sql,connection
my_con = connection()
con = my_con.nume()
cursor = con.cursor()
....
cursor.execute(sql)
...
connection.TearDown()
As a side note - your connection class seems a bit superfluous.
| Mysql connection with python in a class | i'm trying to connect to a database building a class connection()saved in local folder in file utils.py .This is what i worked so far of it:
class connection:
def __init__(self):
self.conn = MySQLdb.connect(host = "localhost",user = "xxx",
passwd = "xxx", db = "xxx",
cursorclass=MySQLdb.cursors.DictCursor)
def TearDown(self):
self.conn.close()
def nume(self):
return self.conn
and this is where i use it in code:
from utils import execute_sql,connection
con = connection.nume()
cursor = con.cursor()
....
cursor.execute(sql)
...
connection.TearDown()
i tryed several more but this way was the simplest, still getting some errors that i struggle with;
| [
"The glaring issue is that you need to instantiate your \"connection\" class before calling methods.\nfrom utils import execute_sql,connection\nmy_con = connection()\ncon = my_con.nume()\ncursor = con.cursor()\n....\ncursor.execute(sql)\n...\nconnection.TearDown()\n\nAs a side note - your connection class seems a b... | [
2
] | [] | [] | [
"class",
"mysql",
"python"
] | stackoverflow_0003334831_class_mysql_python.txt |
Q:
TypeError when iterate over DiGraph()
Hii!
I want to get the time execution of my function ( test(G) ). when I
use Timer I need to write the type of my object : "test(% ?? )" %G
which is DiGraph here. How can I do that?
from networkx import nx
def test(G):
for e in G.edges_iter():
print(e)
if __name__=='__main__':
from timeit import Timer
G = nx.DiGraph()
G.add_edges_from([(1,2),(4,5)])
t = Timer("test(% ?? )"%G,"from __main__ import test")
print( t.timeit(1))
A:
You should import G from __main__ as well
import networkx as nx
def test(G):
for e in G.edges_iter():
print(e)
if __name__=='__main__':
from timeit import Timer
G = nx.DiGraph()
G.add_edges_from([(1,2),(4,5)])
t = Timer("test(G)","from __main__ import test,G")
print( t.timeit(1))
Note that I fixed the import statement also.
| TypeError when iterate over DiGraph() | Hii!
I want to get the time execution of my function ( test(G) ). when I
use Timer I need to write the type of my object : "test(% ?? )" %G
which is DiGraph here. How can I do that?
from networkx import nx
def test(G):
for e in G.edges_iter():
print(e)
if __name__=='__main__':
from timeit import Timer
G = nx.DiGraph()
G.add_edges_from([(1,2),(4,5)])
t = Timer("test(% ?? )"%G,"from __main__ import test")
print( t.timeit(1))
| [
"You should import G from __main__ as well\nimport networkx as nx\n\ndef test(G):\n for e in G.edges_iter():\n print(e)\n\nif __name__=='__main__':\n from timeit import Timer\n G = nx.DiGraph()\n G.add_edges_from([(1,2),(4,5)])\n t = Timer(\"test(G)\",\"from __main__ import test,G\")\n prin... | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0003335101_networkx_python.txt |
Q:
How to check if a MySQL connection is closed in Python?
The question says everything. How can I check if my MySQL connection is closed in Python?
I'm using MySQLdb, see http://mysql-python.sourceforge.net/
A:
The Connection.open field will be 1 if the connection is open and 0 otherwise. So you can say
if conn.open:
# do something
| How to check if a MySQL connection is closed in Python? | The question says everything. How can I check if my MySQL connection is closed in Python?
I'm using MySQLdb, see http://mysql-python.sourceforge.net/
| [
"The Connection.open field will be 1 if the connection is open and 0 otherwise. So you can say\nif conn.open:\n # do something\n\n"
] | [
34
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003335342_mysql_python.txt |
Q:
Using Python COM to select files in windows explorer?
Is it possible using Python COM to select files inside of the windows explorer? For example, I am trying to get all "*.txt" files inside of windows explore highlighted without having to select them with the mouse, or without other keyboard gymnastics.
thanks in advance.
A:
I am not sure if this useful for you, but you might be able to register a pyhook module and make it listen to which window you are selecting, once you get the path then you can process it with python listdir()
http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page
| Using Python COM to select files in windows explorer? | Is it possible using Python COM to select files inside of the windows explorer? For example, I am trying to get all "*.txt" files inside of windows explore highlighted without having to select them with the mouse, or without other keyboard gymnastics.
thanks in advance.
| [
"I am not sure if this useful for you, but you might be able to register a pyhook module and make it listen to which window you are selecting, once you get the path then you can process it with python listdir()\nhttp://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page\n"
] | [
1
] | [] | [] | [
"automation",
"com",
"python",
"windows"
] | stackoverflow_0002892774_automation_com_python_windows.txt |
Q:
Python access parent object instances
I'm currently trying to write a multiple-file Python (2.6.5) game using PyGame. The problem is that one of the files, "pyconsole.py", needs to be able to call methods on instances of other objects imported by the primary file, "main.py". The problem is that I have a list in the main file to hold instances of all of the game objects (player's ship, enemy ships, stations, etc.), yet I can't seem to be able to call methods from that list within "pyconsole.py" despite the fact that I'm doing a from pyconsole import * in "main.py" before the main loop starts. Is this simply not possible, and should I instead use M4 to combine every file into 1 single file and then bytecode-compile and test/distribute that?
Example:
bash$ cat test.py
#!/usr/bin/python
import math, distancefrom00
foo = 5
class BarClass:
def __init__(self):
self.baz = 10
def get(self):
print "The BAZ is ", self.baz
def switch(self)
self.baz = 15
self.get()
bar = BarClass()
def main():
bar.switch()
print distancefrom00.calculate([2, 4])
if __name__ == '__main__': main()
bash$ cat distancefrom00.py
#!/usr/bin/python
import math
import test
def calculate(otherpoint):
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
bash$ python test.py
The BAZ is 15
The BAZ is 10
Traceback (most recent call last):
File "test.py", line 24, in <module>
if __name__ == '__main__': main()
File "test.py", line 22, in main
print distancefrom00.calculate([2, 4])
File "/home/archie/Development/Python/Import Test/distancefrom00.py", line 8, in calculate
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
TypeError: cannot concatenate 'str' and 'NoneType' objects
If my somewhat limited understanding of Python names, classes, and all that stuff is correct here, the NoneType means that the name test.bar.get() - and thus, test.bar - is not assigned to anything.
A:
The problem is that one of the files,
"pyconsole.py", needs to be able to
call methods on instances of other
objects imported by the primary file,
"main.py".
This just sounds like the dependencies are wrong. Generally nothing should be calling 'backwards' up to the main file. That main.py should be the glue that holds everything else together, and nothing should depend on it. Technically the dependencies should form a directed acyclic graph. As soon as you find a cycle in your dependency graph, move out the common aspects into a new file to break the cycle.
So, move the things in 'main.py' that are used by 'pyconsole.py' out into a new file. Then have 'main.py' and 'pyconsole.py' import that new file.
A:
In addition to the other answers, note that when you run test.py as a script it is module __main__. When you import test.py from distancefrom00.py that creates a new test module. bar in the main script and test.bar accessible from distancefrom00.py are completely unrelated. They aren't even the same class: one is a __main__.BarClass while the other is a test.BarClass instance.
That's why you get the two outputs 15 followed by 10: the main script bar has had its switch method called, but the test module bar has not been switched.
Circular imports aside, importing your main script into another module has its own level of badness.
A:
Are you instantiating an object in pyconsole in main.py? If you've got a class called PyConsole in pyconsole, give its __init__ method a parameter that takes the list of game objects. That way your pyConsole object will have a reference to the objects.
Hope this helps. It seems like you've just misunderstood the way Python works with imported modules.
A:
The problem with the submitted code is that the get method of the BarClass class returns a value of None because the body of the method contains only a print statement. Therefore, in distancefrom00.py the result of the function calculate is:
str + str + str + str + None + str
Hence, the TypeError: cannot concatenate a 'str' and 'NoneType' objects
You can solve this problem by returning a string from a call to get. For example,
def get(self):
return "The BAZ is %s" % self.baz
Also, note that you have a circular import in your two files. test.py imports distancefrom00.py, and distancefrom00.py imports test.py. As Kylotan says cyclic dependences are bad
| Python access parent object instances | I'm currently trying to write a multiple-file Python (2.6.5) game using PyGame. The problem is that one of the files, "pyconsole.py", needs to be able to call methods on instances of other objects imported by the primary file, "main.py". The problem is that I have a list in the main file to hold instances of all of the game objects (player's ship, enemy ships, stations, etc.), yet I can't seem to be able to call methods from that list within "pyconsole.py" despite the fact that I'm doing a from pyconsole import * in "main.py" before the main loop starts. Is this simply not possible, and should I instead use M4 to combine every file into 1 single file and then bytecode-compile and test/distribute that?
Example:
bash$ cat test.py
#!/usr/bin/python
import math, distancefrom00
foo = 5
class BarClass:
def __init__(self):
self.baz = 10
def get(self):
print "The BAZ is ", self.baz
def switch(self)
self.baz = 15
self.get()
bar = BarClass()
def main():
bar.switch()
print distancefrom00.calculate([2, 4])
if __name__ == '__main__': main()
bash$ cat distancefrom00.py
#!/usr/bin/python
import math
import test
def calculate(otherpoint):
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
bash$ python test.py
The BAZ is 15
The BAZ is 10
Traceback (most recent call last):
File "test.py", line 24, in <module>
if __name__ == '__main__': main()
File "test.py", line 22, in main
print distancefrom00.calculate([2, 4])
File "/home/archie/Development/Python/Import Test/distancefrom00.py", line 8, in calculate
return str(math.hypot(otherpoint[0], otherpoint[1]))+" (foo = "+str(test.foo)+"; "+test.bar.get()+")"
TypeError: cannot concatenate 'str' and 'NoneType' objects
If my somewhat limited understanding of Python names, classes, and all that stuff is correct here, the NoneType means that the name test.bar.get() - and thus, test.bar - is not assigned to anything.
| [
"\nThe problem is that one of the files,\n \"pyconsole.py\", needs to be able to\n call methods on instances of other\n objects imported by the primary file,\n \"main.py\".\n\nThis just sounds like the dependencies are wrong. Generally nothing should be calling 'backwards' up to the main file. That main.py shou... | [
2,
1,
0,
0
] | [] | [] | [
"pygame",
"python",
"python_import"
] | stackoverflow_0003335230_pygame_python_python_import.txt |
Q:
Python Reportlab RML. How to split table row on two pages
I'm wondering if there is some functionality to split table row on two and more pages. Cause some information in row can be too long for one page, and if one row longer then page size then it's cause an exception.
A:
ReportLab does not text wrapping out of the box, so I am assuming you are either using a para in the table cells, or you are breaking your lines manually with simpleSplit.
If you text is one line string then you can use
from reportlab.pdfbase.pdfmetrics import stringWidth
textWidth = stringWidth(text, fontName, fontSize)
If your text was multi-lines, assuming you are working in a rectangular area with defined width, then do
from reportlab.lib.utils import simpleSplit
lines = simpleSplit(text, fontName, fontSize, maxWidth)
lines is a list of all the lines of your paragraph, if you know the line spacing value then the height of the paragraph can be calculated as lineSpacing*len(lines)
If this proved to be longer than your page then using whatever template you are in (preppy, django, ninja, etc) finds a good breaking point for your text and ends the current row and starts a new one.
I hope this helps
Meitham
p.s. you could always send your questions to the reportlab mailing list and they usually very quick in answering these questions.
| Python Reportlab RML. How to split table row on two pages | I'm wondering if there is some functionality to split table row on two and more pages. Cause some information in row can be too long for one page, and if one row longer then page size then it's cause an exception.
| [
"ReportLab does not text wrapping out of the box, so I am assuming you are either using a para in the table cells, or you are breaking your lines manually with simpleSplit.\nIf you text is one line string then you can use\nfrom reportlab.pdfbase.pdfmetrics import stringWidth\ntextWidth = stringWidth(text, fontName,... | [
1
] | [] | [] | [
"python",
"reportlab",
"row"
] | stackoverflow_0003297115_python_reportlab_row.txt |
Q:
What's the best way to get a description of the website, in Python?
Suppose I downloaded the HTML code, and I can parse it.
How do I get the "best" description of that website, if that website does not have meta-description tag?
A:
You could get the first few sentence returned from something like Readability.
Safari 5 uses it, so it must be alright :)
A:
It's very hard to come up with a rule that works 100% of the time, obviously, but my suggestion as a starting point would be to look for the first <h1> tag (or <h2>, <h3>, etc - the highest one you can find) then the bit of text after that can be used as the description. As long as the site is semantically marked-up, that should give you a good description (I guess you could also take the contents of the <h1> itself, but that's more like the "title").
It's interesting to note that Google (for example) uses a keyword-specific extract of the page contents to display as the description, rather than a static description. Not sure if that'll work for your situation, though.
A:
To follow up on the "Readability" suggestion above (which itself is inspired by the website InstaPaper), they have release the JavaScript: http://code.google.com/p/arc90labs-readability/. What's more, some guy took that and ported it to python: http://github.com/gfxmonk/python-readability. Rejoice!
| What's the best way to get a description of the website, in Python? | Suppose I downloaded the HTML code, and I can parse it.
How do I get the "best" description of that website, if that website does not have meta-description tag?
| [
"You could get the first few sentence returned from something like Readability.\nSafari 5 uses it, so it must be alright :)\n",
"It's very hard to come up with a rule that works 100% of the time, obviously, but my suggestion as a starting point would be to look for the first <h1> tag (or <h2>, <h3>, etc - the hig... | [
3,
1,
1
] | [] | [] | [
"html",
"parsing",
"python",
"string",
"templates"
] | stackoverflow_0003332494_html_parsing_python_string_templates.txt |
Q:
Is while True: a suitable way to repeat a block until an accepted case is reached?
Is while True an accepted method for looping over a block of code until an accepted case is reached as below? Is there a more elegant way to do this?
while True:
value = input()
if value == condition:
break
else:
pass
# Continue code here.
Thank you for any input.
A:
That's the way to do this in Python. You don't need the else: pass bit though.
Note, that in python 2.x you're likely to want raw_input rather than input.
A:
If it's deterministic, then yes. If it is not deterministic (thus meaning you could be stuck in a loop forever at some statistical likelihood) then no.
If you wanted to make it a little more clean and easier to debug as the code grows larger, use a boolean or integer to indicate the status of your loop condition.
| Is while True: a suitable way to repeat a block until an accepted case is reached? | Is while True an accepted method for looping over a block of code until an accepted case is reached as below? Is there a more elegant way to do this?
while True:
value = input()
if value == condition:
break
else:
pass
# Continue code here.
Thank you for any input.
| [
"That's the way to do this in Python. You don't need the else: pass bit though.\nNote, that in python 2.x you're likely to want raw_input rather than input.\n",
"If it's deterministic, then yes. If it is not deterministic (thus meaning you could be stuck in a loop forever at some statistical likelihood) then no.\... | [
8,
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0003336052_python_while_loop.txt |
Q:
Create a .txt list of IPs in a subnet
I'd like to make a very simple text (.txt) file. This python program needs to make a list of multiple ranges of IPs in a subnet, each taking up one line.
Example:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.51
10.10.27.52
10.10.27.53
10.10.27.54
The subnet mask will essentially always be a /24, so providing mask input is not necessary. The program can even default to only supporting a standard class C.
Also, I'd like to support common ranges for devices that we use. A prompt for say, "Printers?" will include .26 - .30. "Servers?" will include .5 - .7. "DHCP?" prompt always will include .51 - .100 of the subnet. "Abnormal?" will include .100 - .254.
Subnet? 10.10.27.1
Servers? Y
Printers? Y
DHCP? Y
Abnormal? N
Output being:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.7
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.30
10.10.27.51 (all the way to .100)
What is the best way to code this?
A:
It looks like a few for loops are all you need:
network = '10.10.27'
for host in xrange(100, 255):
print("{network}.{host}".format(**locals()))
A:
I would keep the script simple, just output all addresses as needed :)
def yesno(question):
output = input(question).lower()
if output == 'y':
return True
elif output == 'n':
return False
else:
print '%r is not a valid response, only "y" and "n" are allowed.' % output
return yesno(question)
addresses = []
subnet = input('Subnet? ')
# Remove the last digit and replace it with a %d for formatting later
subnet, address = subnet.rsplit('.', 1)
subnet += '%d'
addresses.append(int(address))
if yesno('Servers? '):
addresses += range(5, 8)
if yesno('Printers? '):
addresses += range(26, 31)
if yesno('DHCP? '):
addresses += range(51, 101)
if yesno('Abnormal? '):
addresses += range(100, 255)
for address in addresses:
print subnet % address
A:
Here is a quick little script I threw together...
import socket
import sys
ranges = {'servers':(5, 8), 'printers':(26, 31), 'dhcp':(51, 101), 'abnormal':(101, 256)}
subnet = raw_input("Subnet? ")
try:
socket.inet_aton(subnet)
except socket.error:
print "Not a valid subnet"
sys.exit(1)
ip_parts = subnet.split(".")
if len(ip_parts) < 3:
print "Need at least three octets"
sys.exit(1)
ip_parts = ip_parts[:3]
ip = ".".join(ip_parts)
include_groups = []
last_octets = []
servers = raw_input("Servers? ")
printers = raw_input("Printers? ")
dhcp = raw_input("DHCP? ")
abnormal = raw_input("Abnormal? ")
if servers == "Y":
include_groups.append('servers')
if printers == "Y":
include_groups.append('printers')
if dhcp == "Y":
include_groups.append('dhcp')
if abnormal == "Y":
include_groups.append('abnormal')
for group in include_groups:
last_octets.extend([x for x in xrange(ranges[group][0], ranges[group][1])])
print "%s.1" %(ip)
for octet in last_octets:
print "%s.%s" %(ip, octet)
| Create a .txt list of IPs in a subnet | I'd like to make a very simple text (.txt) file. This python program needs to make a list of multiple ranges of IPs in a subnet, each taking up one line.
Example:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.51
10.10.27.52
10.10.27.53
10.10.27.54
The subnet mask will essentially always be a /24, so providing mask input is not necessary. The program can even default to only supporting a standard class C.
Also, I'd like to support common ranges for devices that we use. A prompt for say, "Printers?" will include .26 - .30. "Servers?" will include .5 - .7. "DHCP?" prompt always will include .51 - .100 of the subnet. "Abnormal?" will include .100 - .254.
Subnet? 10.10.27.1
Servers? Y
Printers? Y
DHCP? Y
Abnormal? N
Output being:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.7
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.30
10.10.27.51 (all the way to .100)
What is the best way to code this?
| [
"It looks like a few for loops are all you need:\nnetwork = '10.10.27'\n\nfor host in xrange(100, 255):\n print(\"{network}.{host}\".format(**locals()))\n\n",
"I would keep the script simple, just output all addresses as needed :)\ndef yesno(question):\n output = input(question).lower()\n\n if output == '... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003336087_python.txt |
Q:
Python - urllib2.urlopen - Why do I get garbled characters?
Here's my problem:
import urllib2
response=urllib2.urlopen('http://proxy-heaven.blogspot.com/')
html=response.read()
print html
It's just this site, and I don't know why the result is all garbled characters. Anyone can help?
A:
Without your output it's hard to say but I'd bet it's an encoding issue : this website is encoded in utf8. If your terminal is set in iso-latin for example, it won't be possible for it to display characters properly.
A:
Works for me:
import urllib
response=urllib.urlopen('http://proxy-heaven.blogspot.com/')
a = response.read()
print a[:50]
> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Stric'
You may have an encoding problem in your terminal, though.
A:
encoding may be your problem, in which case you want this code.
import urllib
s = str(urllib.urlopen('http://proxy-heaven.blogspot.com/').read(), encoding='utf8')
| Python - urllib2.urlopen - Why do I get garbled characters? | Here's my problem:
import urllib2
response=urllib2.urlopen('http://proxy-heaven.blogspot.com/')
html=response.read()
print html
It's just this site, and I don't know why the result is all garbled characters. Anyone can help?
| [
"Without your output it's hard to say but I'd bet it's an encoding issue : this website is encoded in utf8. If your terminal is set in iso-latin for example, it won't be possible for it to display characters properly.\n",
"Works for me:\nimport urllib\nresponse=urllib.urlopen('http://proxy-heaven.blogspot.com/')\... | [
1,
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003335167_python_urllib2.txt |
Q:
Pulling Data From Multiple Tables in Django
I'm kind of new to Django and am having some trouble pulling from existing tables. I'm trying to pull data from columns on multiple joined tables. I did find a solution, but it feels a bit like cheating and am wondering if my method below is considered proper or not.
class Sig(models.Model):
sig_id = models.IntegerField(primary_key=True)
parent = models.ForeignKey('self')
state = models.CharField(max_length=2, db_column='state')
release_id = models.SmallIntegerField(choices=releaseChoices)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=255, blank=True)
zip = models.CharField(max_length=10, blank=True)
phone1 = models.CharField(max_length=255, blank=True)
fax = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
url = models.URLField(max_length=255, blank=True)
description = models.TextField(blank=True)
contactname = models.CharField(max_length=255, blank=True)
phone2 = models.CharField(max_length=255, blank=True)
ratinggroup = models.BooleanField()
state_id = models.ForeignKey(State, db_column='state_id')
usesigrating = models.BooleanField()
major = models.BooleanField()
class Meta:
db_table = u'sig'
class SigCategory(models.Model):
sig_category_id = models.IntegerField(primary_key=True)
sig = models.ForeignKey(Sig, related_name='sigcategory')
category = models.ForeignKey(Category)
class Meta:
db_table = u'sig_category'
class Category(models.Model):
category_id = models.SmallIntegerField(primary_key=True)
name = models.CharField(max_length=255)
release_id = models.SmallIntegerField()
class Meta:
db_table = u'category'
Then, this was my solution, which works, but doesn't quite feel right:
sigs = Sig.objects.only('sig_id', 'name').extra(
select = {
'category': 'category.name',
},
).filter(
sigcategory__category__category_id = categoryId,
state_id = stateId
).order_by('sigcategory__category__name', 'name')
Now since the items in filter() join the sigcategory and category models, I was able to pull category.name out by using extra(). Is this a proper way of doing this? What if I did not have the reference in filter() and the join did not take place?
A:
SigCategory has a ForeignKey pointing at Category, so you can always get from the SigCategory to the Category simply by doing mysigcategory.category (where mysigcategory is your instance of SigCategory.
If you haven't previously accessed that relationship from that instance, doing it here will cause an extra database lookup - if you're concerned about db efficiency, look into select_related.
| Pulling Data From Multiple Tables in Django | I'm kind of new to Django and am having some trouble pulling from existing tables. I'm trying to pull data from columns on multiple joined tables. I did find a solution, but it feels a bit like cheating and am wondering if my method below is considered proper or not.
class Sig(models.Model):
sig_id = models.IntegerField(primary_key=True)
parent = models.ForeignKey('self')
state = models.CharField(max_length=2, db_column='state')
release_id = models.SmallIntegerField(choices=releaseChoices)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=255, blank=True)
zip = models.CharField(max_length=10, blank=True)
phone1 = models.CharField(max_length=255, blank=True)
fax = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
url = models.URLField(max_length=255, blank=True)
description = models.TextField(blank=True)
contactname = models.CharField(max_length=255, blank=True)
phone2 = models.CharField(max_length=255, blank=True)
ratinggroup = models.BooleanField()
state_id = models.ForeignKey(State, db_column='state_id')
usesigrating = models.BooleanField()
major = models.BooleanField()
class Meta:
db_table = u'sig'
class SigCategory(models.Model):
sig_category_id = models.IntegerField(primary_key=True)
sig = models.ForeignKey(Sig, related_name='sigcategory')
category = models.ForeignKey(Category)
class Meta:
db_table = u'sig_category'
class Category(models.Model):
category_id = models.SmallIntegerField(primary_key=True)
name = models.CharField(max_length=255)
release_id = models.SmallIntegerField()
class Meta:
db_table = u'category'
Then, this was my solution, which works, but doesn't quite feel right:
sigs = Sig.objects.only('sig_id', 'name').extra(
select = {
'category': 'category.name',
},
).filter(
sigcategory__category__category_id = categoryId,
state_id = stateId
).order_by('sigcategory__category__name', 'name')
Now since the items in filter() join the sigcategory and category models, I was able to pull category.name out by using extra(). Is this a proper way of doing this? What if I did not have the reference in filter() and the join did not take place?
| [
"SigCategory has a ForeignKey pointing at Category, so you can always get from the SigCategory to the Category simply by doing mysigcategory.category (where mysigcategory is your instance of SigCategory.\nIf you haven't previously accessed that relationship from that instance, doing it here will cause an extra data... | [
2
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0003336059_django_models_python.txt |
Q:
"case sequence" in python implemented with dictionaries
i have implemented a function:
def postback(i,user,tval):
"""functie ce posteaza raspunsul bazei de date;stringul din mesaj tb sa fie mai mic de 140 de caractere"""
result = {
1:api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2:postmarket(user,tval),
3:api.PostDirectMessage(user,'Imi pare rau, dar nu stiu unde poti gasi aceste tipuri de smantana: %s' % tval)}
return result.get(i)
but it does not work as a case alternative(from c++) it executes all 3 cases no matter wha i try...i'm a begginer so there might be another error, so please help!p.s. please don't tell me that the if...else.. is the only alternative cause i know this can work
A:
If you absolutely must use a dict, use a dict of functions:
result = {
1: lambda: api.PostDirectMessage(...),
2: lambda: postmarket(...),
...
}
return result[i]()
The lambda keyword defines an anonymous inline function, and they only get called on the last line.
A:
The value expressions in the dict will be evaluated when this is compiled. If you want those things executed, you could wrap them in a lambda.
def postback(i,user,tval):
result = {
1: lambda: api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2: lambda: postmarket(user,tval),
3: lambda: api.PostDirectMessage(user,'Imi pare rau, dar nu stiu unde poti gasi aceste tipuri de smantana: %s' % tval)}
return result.get(i)
A:
It executes all three cases because you define the result dict that way! You call all three functions and assign them to the keys 1, 2, 3.
What you should instead is something like this:
functions = {
1: lambda: api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2: lambda: postmarket(user,tval),
3: lambda: api.PostDirectMessage(user,'Imi pare rau, dar nu stiu unde poti gasi aceste tipuri de smantana: %s' % tval)}
func = functions.get(i)
if func:
return func()
else:
raise ValueError("Bad index: %d!" % i)
Here I define small wrapper functions and store those in the dict instead. You then pick the right function and call on this one function.
| "case sequence" in python implemented with dictionaries | i have implemented a function:
def postback(i,user,tval):
"""functie ce posteaza raspunsul bazei de date;stringul din mesaj tb sa fie mai mic de 140 de caractere"""
result = {
1:api.PostDirectMessage(user,'Trebuie sa-mi spui si marca pe care o cauti'),
2:postmarket(user,tval),
3:api.PostDirectMessage(user,'Imi pare rau, dar nu stiu unde poti gasi aceste tipuri de smantana: %s' % tval)}
return result.get(i)
but it does not work as a case alternative(from c++) it executes all 3 cases no matter wha i try...i'm a begginer so there might be another error, so please help!p.s. please don't tell me that the if...else.. is the only alternative cause i know this can work
| [
"If you absolutely must use a dict, use a dict of functions:\nresult = {\n 1: lambda: api.PostDirectMessage(...),\n 2: lambda: postmarket(...),\n ...\n}\nreturn result[i]()\n\nThe lambda keyword defines an anonymous inline function, and they only get called on the last line.\n",
"The value expressions in... | [
2,
1,
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003336385_c++_python.txt |
Q:
Get the current value of env.hosts list with Python Fabric Library
I've got this code (foo and bar are local servers):
env.hosts = ['foo', 'bar']
def mytask():
print(env.hosts[0])
Which, of course prints foo every iteration.
As you probably know, Fabric iterates through the env.hosts list and executes mytask() on each of them this way:
fab mytask
does
task is executed on foo
task is executed on bar
I'm looking for a way to get the current host in every iteration.
Thanks,
A:
Use env.host_string. You can find a full list of env variables here.
A:
You can just do:
env.hosts = ['foo', 'bar']
def mytask():
print(env.host)
Because when you're in the task as executed by fab, you'll have that var set for free.
A:
Thanks Marcelo.
If you want to actually use env.host_string (for concatenation purpose for instance), be sure to be inside a task. Its value is None outside.
| Get the current value of env.hosts list with Python Fabric Library | I've got this code (foo and bar are local servers):
env.hosts = ['foo', 'bar']
def mytask():
print(env.hosts[0])
Which, of course prints foo every iteration.
As you probably know, Fabric iterates through the env.hosts list and executes mytask() on each of them this way:
fab mytask
does
task is executed on foo
task is executed on bar
I'm looking for a way to get the current host in every iteration.
Thanks,
| [
"Use env.host_string. You can find a full list of env variables here.\n",
"You can just do:\nenv.hosts = ['foo', 'bar']\n\ndef mytask():\n print(env.host)\n\nBecause when you're in the task as executed by fab, you'll have that var set for free.\n",
"Thanks Marcelo.\nIf you want to actually use env.host_stri... | [
40,
27,
3
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0003334936_fabric_python.txt |
Q:
When I use httplib for my OAUTH in Python, I always get "CannotSendRequest" and then "
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/ea/ea/hell/life/views.py" in linkedin_auth
274. token = oauth_linkedin.get_unauthorised_request_token()
File "/home/ea/ea/hell/life/oauth_linkedin.py" in get_unauthorised_request_token
52. resp = fetch_response(oauth_request, connection)
File "/home/ea/ea/hell/life/oauth_linkedin.py" in fetch_response
42. connection.request(oauth_request.http_method,url)
File "/usr/lib/python2.6/httplib.py" in request
874. self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py" in _send_request
891. self.putrequest(method, url, **skips)
File "/usr/lib/python2.6/httplib.py" in putrequest
778. raise CannotSendRequest()
Exception Type: CannotSendRequest at /linkedin/auth
Exception Value:
And then, sometimes I get: BadStatusLine error instead of this.
It's pretty random. I don't know when or why they happen. It happens more frequently when I'm running the Django development server (and less frequently when in APACHE2...but it still happens at random times). When this error happens, I have to restart my server.
A:
Apparently (from here) this happens if you try to reuse an httplib.HTTP object which had not been fully used. Maybe a connection pool in the library you're using, and an exception getting thrown during the request processing? Suggestion is to create new connection objects every time.
| When I use httplib for my OAUTH in Python, I always get "CannotSendRequest" and then " | Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/ea/ea/hell/life/views.py" in linkedin_auth
274. token = oauth_linkedin.get_unauthorised_request_token()
File "/home/ea/ea/hell/life/oauth_linkedin.py" in get_unauthorised_request_token
52. resp = fetch_response(oauth_request, connection)
File "/home/ea/ea/hell/life/oauth_linkedin.py" in fetch_response
42. connection.request(oauth_request.http_method,url)
File "/usr/lib/python2.6/httplib.py" in request
874. self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py" in _send_request
891. self.putrequest(method, url, **skips)
File "/usr/lib/python2.6/httplib.py" in putrequest
778. raise CannotSendRequest()
Exception Type: CannotSendRequest at /linkedin/auth
Exception Value:
And then, sometimes I get: BadStatusLine error instead of this.
It's pretty random. I don't know when or why they happen. It happens more frequently when I'm running the Django development server (and less frequently when in APACHE2...but it still happens at random times). When this error happens, I have to restart my server.
| [
"Apparently (from here) this happens if you try to reuse an httplib.HTTP object which had not been fully used. Maybe a connection pool in the library you're using, and an exception getting thrown during the request processing? Suggestion is to create new connection objects every time.\n"
] | [
0
] | [] | [] | [
"connection",
"django",
"httplib",
"oauth",
"python"
] | stackoverflow_0002310143_connection_django_httplib_oauth_python.txt |
Q:
Elegantly generating a datetime from a URL in Django?
I'm working on a web app that will allow the user to do a lookup by date, so that, for example:
results = Something.objects.filter(end = date)
I'm planning on passing in the date information via the URL, like this:
example.com/invoicer?2/9/1984
I'll then grab the date via request.GET, break off the first part and store it as the month, delete the slash, break off the second part as the date, etc. etc.
I'm not too worried about error/input checking, since only trusted administrators will have access to this, but it seems like a crappy way of going about generating the datetime.
Any better ideas?
A:
[...] break off the first part and store it as the month, delete the slash, break off the second part as the date, etc. etc.
That's indeed is not an ideal way to generate the datetime. You're better off with string parsing:
>>> datetime.datetime.strptime('2/9/1984', '%m/%d/%Y')
datetime.datetime(1984, 2, 9, 0, 0)
A:
You'll have an easier time if you use a parameter for the value:
invoicer?date=2/9/1984
and you might prefer to use an ISO8601 date:
invoicer?date=19840209
I'm not sure what your user interface to this is, or are you expecting people to type these URLs by hand? If not, IS08601 is the way to go.
A:
Seems pretty normal. One other way we do it is not to use the query string but the path:
example.com/invoicer/end_date/1984-02-09
A:
you can convert to a unix/epoch date and pass as a long integer.
super simple and no worrying about string parsing. just use python's time.gmtime to get your time from the number of seconds.
example.com/invoicer?date=1280139973
time.gmtime(1280139973)
| Elegantly generating a datetime from a URL in Django? | I'm working on a web app that will allow the user to do a lookup by date, so that, for example:
results = Something.objects.filter(end = date)
I'm planning on passing in the date information via the URL, like this:
example.com/invoicer?2/9/1984
I'll then grab the date via request.GET, break off the first part and store it as the month, delete the slash, break off the second part as the date, etc. etc.
I'm not too worried about error/input checking, since only trusted administrators will have access to this, but it seems like a crappy way of going about generating the datetime.
Any better ideas?
| [
"\n[...] break off the first part and store it as the month, delete the slash, break off the second part as the date, etc. etc.\n\nThat's indeed is not an ideal way to generate the datetime. You're better off with string parsing:\n>>> datetime.datetime.strptime('2/9/1984', '%m/%d/%Y')\ndatetime.datetime(1984, 2, 9,... | [
6,
2,
2,
2
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0003336529_datetime_django_python.txt |
Q:
In Django I have a complex query where I need only the unique values through a foreign key, is this possible?
I have the following models:
class Indicator(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey(IndicatorCategory)
weight = models.IntegerField()
industry = models.ForeignKey(Industry)
def __unicode__(self):
return self.name
class Meta:
ordering = ('name',)
class IndicatorRatingOption(models.Model):
indicator = models.ForeignKey(Indicator)
description = models.TextField()
value = models.FloatField(null=True)
def __unicode__(self):
return self.description
class Rating(models.Model):
product = models.ForeignKey(Product, null=True)
company = models.ForeignKey(Company, null=True)
rating_option = models.ForeignKey(IndicatorRatingOption)
value = models.IntegerField(null=True)
What I need to do is get all of the company rating options of two companies without having them overlap on their Indicators (rating.rating_option.indicator). If there's a conflict, company 'a' would always win over company 'b'. How do I do this?
A:
This works:
Rating.objects.filter(company__in=[company_a, company_b]).distinct()
(Original answer)
Did you try
IndicatorRatingOptions.objects.filter(company__in=[company_a, company_b]).distinct()
?
| In Django I have a complex query where I need only the unique values through a foreign key, is this possible? | I have the following models:
class Indicator(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey(IndicatorCategory)
weight = models.IntegerField()
industry = models.ForeignKey(Industry)
def __unicode__(self):
return self.name
class Meta:
ordering = ('name',)
class IndicatorRatingOption(models.Model):
indicator = models.ForeignKey(Indicator)
description = models.TextField()
value = models.FloatField(null=True)
def __unicode__(self):
return self.description
class Rating(models.Model):
product = models.ForeignKey(Product, null=True)
company = models.ForeignKey(Company, null=True)
rating_option = models.ForeignKey(IndicatorRatingOption)
value = models.IntegerField(null=True)
What I need to do is get all of the company rating options of two companies without having them overlap on their Indicators (rating.rating_option.indicator). If there's a conflict, company 'a' would always win over company 'b'. How do I do this?
| [
"This works:\nRating.objects.filter(company__in=[company_a, company_b]).distinct()\n\n\n(Original answer)\nDid you try\nIndicatorRatingOptions.objects.filter(company__in=[company_a, company_b]).distinct()\n\n?\n"
] | [
5
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003323591_django_django_models_python.txt |
Q:
How to handle HTML Arrays with App Engine Python?
I'm stuck with this problem I made an HTML Array, but I can't read it out with Python. Is it even possible to do it in App Engine? I read it was possible in PHP.
This is the html code:
<label for="hashtags">Hashtags: </label><br/>
{% for hashtag in stream.hashtags %}
<input type="text" value="{{hashtag}}" name="hashtags[]" id="hashtags" class="text ui-widget-content ui-corner-all" />
{% endfor %}
This is how I'm currently trying to read the HTML Array:
newHashTags = self.request.get('hashtags[]')
for newHashTag in newHashTags:
stream.hashtags.append(newHashTag)
This is in the post variable when I'm debugging.
MultiDict: MultiDict([('streamid', '84'), ('name', 'Akteurs'), ('description', '#stream'), ('hashtags[]', '#andretest'), ('hashtags[]', '#saab')])
A:
You don't need to include the [] at the end of the name of a field you'd like to treat as a list or array, that's some PHP-specific magic. Instead, just name the field hashtags and in your request handler do this to get a list of hashtags from the request:
newHashTags = self.request.get('hashtags', allow_multiple=True)
The allow_multiple=True argument will make get method return a list of all hashtags values in the request. See the relevant documentation for more info.
You could also avoid the for loop by doing something like this:
newHashTags = self.request.get('hashtags', allow_multiple=True)
stream.hashtags.extend(newHashTags)
| How to handle HTML Arrays with App Engine Python? | I'm stuck with this problem I made an HTML Array, but I can't read it out with Python. Is it even possible to do it in App Engine? I read it was possible in PHP.
This is the html code:
<label for="hashtags">Hashtags: </label><br/>
{% for hashtag in stream.hashtags %}
<input type="text" value="{{hashtag}}" name="hashtags[]" id="hashtags" class="text ui-widget-content ui-corner-all" />
{% endfor %}
This is how I'm currently trying to read the HTML Array:
newHashTags = self.request.get('hashtags[]')
for newHashTag in newHashTags:
stream.hashtags.append(newHashTag)
This is in the post variable when I'm debugging.
MultiDict: MultiDict([('streamid', '84'), ('name', 'Akteurs'), ('description', '#stream'), ('hashtags[]', '#andretest'), ('hashtags[]', '#saab')])
| [
"You don't need to include the [] at the end of the name of a field you'd like to treat as a list or array, that's some PHP-specific magic. Instead, just name the field hashtags and in your request handler do this to get a list of hashtags from the request:\nnewHashTags = self.request.get('hashtags', allow_multipl... | [
5
] | [] | [] | [
"google_app_engine",
"html",
"python"
] | stackoverflow_0003336891_google_app_engine_html_python.txt |
Q:
Continuing code execution after a pygtk.main() in python
I have an application where my DataFetch() class "Wraps" around my HBHTray() class for the purpose of interacting with the functions/variables of that class. Unfortunately, I can't seem to be able to get the code to continue execution after my DataFetch() class makes a instance of HBHTray and calls it, and on the Start() method of HBHTray it hangs.
This is the relevant code:
class DataFetch(): # I need the DataFetch class to be wrapping around HBHTray so I can call/edit certain variables from within functions in DataFetch
def init(self):
self.Interval, self.Username, self.Password, self.CheckShoutBox = GetOptions('.tray')
self.Gui = HBHTray()
print '1'
self.Gui.Start()
print '2'
def Login(self):
pass # Do stuff (Eg: Edit self.Gui.StatusIcon state or call self.Gui.Notify()
def Start(self):
print 'hi!'
sleep(self.Interval)
print 'Hi!'
class HBHTray():
def init(self):
self.StatusIcon = gtk.StatusIcon()
self.StatusIcon.set_from_file('img')
self.StatusIcon.set_tooltip('No new messages')
self.Menu = gtk.Menu()
self.CheckBox = gtk.CheckMenuItem('Notify')
self.CheckBox.connect('activate', self.ChangeCheckBox)
self.CheckBox.set_active(True)
self.Menu.append(self.CheckBox)
self.MenuItem = gtk.ImageMenuItem('Options')
self.MenuItem.connect('activate', self.Options, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.MenuItem = gtk.ImageMenuItem('About')
self.MenuItem.connect('activate', self.About, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.MenuItem = gtk.ImageMenuItem('Quit')
self.MenuItem.connect('activate', self.Quit, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.StatusIcon.connect('popup-menu', self.PopMenu, self.Menu)
self.StatusIcon.set_visible(1)
def PopMenu(self, widget, button, time, data = None):
if data:
data.show_all()
data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.StatusIcon)
def Notify(self, message):
pynotify.init('null')
notification = pynotify.Notification('Something', message, 'dialogue')
notification.attach_to_status_icon(self.StatusIcon)
notification.show()
def Start(self):
gtk.main()
def About(self, a, b):
self.Notify('test')
def Options(self, a, b):
print a, b
def ChangeCheckBox(self, null):
pass
def Quit(self, a, b):
raise SystemExit
if name == 'main':
try:
gobject.threads_init() # Doesn't work?
Monitor = DataFetch()
Monitor.Start()
Sorry for the terrible formatting, Stack Overflow doesn't seem to like blank lines....
Anyways, though, "1" is printed, but "2" is not. So, gtk.main() is obviously where it's hanging. Is there any way to allow me to continue execution and have gtk go do it's own thing?
A:
gobject.threads_init() does not magically put your things into separate threads. It only tells the library that you're going to use threads, and sets up some locking. You'll still have to create the threads yourself.
A:
Turns out the problem was that I couldn't find a working solution because I was utilizing the Thread module the wrong way and calling run() directly when I should have been calling start(). Because of that, I was thinking that nothing I did worked (especially with no error or complaint from anything) and figured it was a problem relating to how I was wrapping gtk.main()
| Continuing code execution after a pygtk.main() in python | I have an application where my DataFetch() class "Wraps" around my HBHTray() class for the purpose of interacting with the functions/variables of that class. Unfortunately, I can't seem to be able to get the code to continue execution after my DataFetch() class makes a instance of HBHTray and calls it, and on the Start() method of HBHTray it hangs.
This is the relevant code:
class DataFetch(): # I need the DataFetch class to be wrapping around HBHTray so I can call/edit certain variables from within functions in DataFetch
def init(self):
self.Interval, self.Username, self.Password, self.CheckShoutBox = GetOptions('.tray')
self.Gui = HBHTray()
print '1'
self.Gui.Start()
print '2'
def Login(self):
pass # Do stuff (Eg: Edit self.Gui.StatusIcon state or call self.Gui.Notify()
def Start(self):
print 'hi!'
sleep(self.Interval)
print 'Hi!'
class HBHTray():
def init(self):
self.StatusIcon = gtk.StatusIcon()
self.StatusIcon.set_from_file('img')
self.StatusIcon.set_tooltip('No new messages')
self.Menu = gtk.Menu()
self.CheckBox = gtk.CheckMenuItem('Notify')
self.CheckBox.connect('activate', self.ChangeCheckBox)
self.CheckBox.set_active(True)
self.Menu.append(self.CheckBox)
self.MenuItem = gtk.ImageMenuItem('Options')
self.MenuItem.connect('activate', self.Options, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.MenuItem = gtk.ImageMenuItem('About')
self.MenuItem.connect('activate', self.About, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.MenuItem = gtk.ImageMenuItem('Quit')
self.MenuItem.connect('activate', self.Quit, self.StatusIcon)
self.Menu.append(self.MenuItem)
self.StatusIcon.connect('popup-menu', self.PopMenu, self.Menu)
self.StatusIcon.set_visible(1)
def PopMenu(self, widget, button, time, data = None):
if data:
data.show_all()
data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.StatusIcon)
def Notify(self, message):
pynotify.init('null')
notification = pynotify.Notification('Something', message, 'dialogue')
notification.attach_to_status_icon(self.StatusIcon)
notification.show()
def Start(self):
gtk.main()
def About(self, a, b):
self.Notify('test')
def Options(self, a, b):
print a, b
def ChangeCheckBox(self, null):
pass
def Quit(self, a, b):
raise SystemExit
if name == 'main':
try:
gobject.threads_init() # Doesn't work?
Monitor = DataFetch()
Monitor.Start()
Sorry for the terrible formatting, Stack Overflow doesn't seem to like blank lines....
Anyways, though, "1" is printed, but "2" is not. So, gtk.main() is obviously where it's hanging. Is there any way to allow me to continue execution and have gtk go do it's own thing?
| [
"gobject.threads_init() does not magically put your things into separate threads. It only tells the library that you're going to use threads, and sets up some locking. You'll still have to create the threads yourself.\n",
"Turns out the problem was that I couldn't find a working solution because I was utilizing t... | [
0,
0
] | [] | [] | [
"multithreading",
"pygtk",
"python",
"wrapper"
] | stackoverflow_0003336457_multithreading_pygtk_python_wrapper.txt |
Q:
Crontab wont run python script
When I execute my python script from the command line I have no problems like so:
[rv@med240-183 db]$ python formatdb.py
[rv@med240-183 db]$
When I try to use crontab to run the script every midnight I get a series of errors:
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 2: from: command not found
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 3: from: command not found
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: syntax error near
unexpected token `('
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: `conx = MySQLdb.connect
(user = 'root', passwd = '******', db = 'vaxijen_antigens')'
The directory of my script is as follows:
/home/rv/ncbi-blast-2.2.23+/db/
Crontab looks like:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/bin/python/:/home/rv/ncbi-blast-2.2.23+/database_backup:/home/rv/ncbi-blast-2.2.23+/db/
MAILTO="******"
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * command to be executed
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/database_backup/backup.py
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/db/formatdb.py
and my python script looks like:
import MySQLdb
from subprocess import call
from subprocess import Popen
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('vdatabase.fasta', 'w')
for i in row:
f.write('>'+i[0].strip()+'\n')
#f.write(i[1].strip().replace(' ','')+'\n')
s = re.sub(r'[^\w]','',str(i[1]))
s = ''.join(s)
for k in range(0, len(s), 60):
f.write('%s\n' % (s[k:k+60]))
f.write('\n')
f.close
Popen(["formatdb", "-p", "T", "-i", "vdatabase.fasta"]).wait()
A:
Add
#!/usr/bin/env python
to the beginning of your script - right now it's trying to execute your script as a bash, that line says "I'm a python script, please use the right interpreter". It's also called a hash-bang line, but it needs to be the first line in your script.
| Crontab wont run python script | When I execute my python script from the command line I have no problems like so:
[rv@med240-183 db]$ python formatdb.py
[rv@med240-183 db]$
When I try to use crontab to run the script every midnight I get a series of errors:
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 2: from: command not found
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 3: from: command not found
import: unable to open X server `' @ import.c/ImportImageCommand/367.
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: syntax error near
unexpected token `('
/home/rv/ncbi-blast-2.2.23+/db/formatdb.py: line 6: `conx = MySQLdb.connect
(user = 'root', passwd = '******', db = 'vaxijen_antigens')'
The directory of my script is as follows:
/home/rv/ncbi-blast-2.2.23+/db/
Crontab looks like:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/bin/python/:/home/rv/ncbi-blast-2.2.23+/database_backup:/home/rv/ncbi-blast-2.2.23+/db/
MAILTO="******"
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * command to be executed
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/database_backup/backup.py
0 0 * * * root /home/rv/ncbi-blast-2.2.23+/db/formatdb.py
and my python script looks like:
import MySQLdb
from subprocess import call
from subprocess import Popen
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('vdatabase.fasta', 'w')
for i in row:
f.write('>'+i[0].strip()+'\n')
#f.write(i[1].strip().replace(' ','')+'\n')
s = re.sub(r'[^\w]','',str(i[1]))
s = ''.join(s)
for k in range(0, len(s), 60):
f.write('%s\n' % (s[k:k+60]))
f.write('\n')
f.close
Popen(["formatdb", "-p", "T", "-i", "vdatabase.fasta"]).wait()
| [
"Add \n#!/usr/bin/env python\n\nto the beginning of your script - right now it's trying to execute your script as a bash, that line says \"I'm a python script, please use the right interpreter\". It's also called a hash-bang line, but it needs to be the first line in your script.\n"
] | [
28
] | [] | [] | [
"crontab",
"python"
] | stackoverflow_0003337149_crontab_python.txt |
Q:
twisted: check whether a deferred has already been called
This is what I'm trying to accomplish. I'm making a remote call to a server for information, and I want to block to wait for the info. I created a function that returns a Deferred such that when the RPC comes in with the reply, the deferred is called. Then I have a function called from a thread that goes threads.blockingCallFromThread(reactor, deferredfunc, args).
If something goes wrong - for example, the server goes down - then the call will never un-block. I'd prefer the deferred to go off with an exception in these cases.
I partially succeeded. I have a deferred, onConnectionLost which goes off when the connection is lost. I modified my blocking call function to:
deferred = deferredfunc(args)
self.onConnectionLost.addCallback(lambda _: deferred.errback(
failure.Failure(Exception("connection lost while getting run"))))
result = threads.blockingCallFromThread(
reactor, lambda _: deferred, None)
return result
This works fine. If the server goes down, the connection is lost, and the errback is triggered. However, if the server does not go down and everything shuts down cleanly, onConnectionLost still gets fired, and the anonymous callback here attempts to trigger the errback, causing an AlreadyCalled exception to be raised.
Is there any neat way to check that a deferred has already been fired? I want to avoid wrapping it in a try/except block, but I can always resort to that if that's the only way.
A:
There are ways, but you really shouldn't do it. Your code that is firing the Deferred should be keeping track of whether it's fired the Deferred or not in the associated state. Really, when you fire the Deferred, you should lose track of it so that it can get properly garbage collected; that way you never need to worry about calling it twice, since you won't have a reference to it any more.
Also, it looks like you're calling deferredfunc from the same thread that you're calling blockingCallFromThread. Don't do that; functions which return Deferreds are most likely calling reactor APIs, and those APIs are not thread safe. In fact, Deferred itself is not thread safe. This is why it's blockingCallFromThread, not blockOnThisDeferredFromThread. You should do blockingCallFromThread(reactor, deferredfunc, args).
If you really want errback-if-it's-been-called-otherwise-do-nothing behavior, you may want to cancel the Deferred.
| twisted: check whether a deferred has already been called | This is what I'm trying to accomplish. I'm making a remote call to a server for information, and I want to block to wait for the info. I created a function that returns a Deferred such that when the RPC comes in with the reply, the deferred is called. Then I have a function called from a thread that goes threads.blockingCallFromThread(reactor, deferredfunc, args).
If something goes wrong - for example, the server goes down - then the call will never un-block. I'd prefer the deferred to go off with an exception in these cases.
I partially succeeded. I have a deferred, onConnectionLost which goes off when the connection is lost. I modified my blocking call function to:
deferred = deferredfunc(args)
self.onConnectionLost.addCallback(lambda _: deferred.errback(
failure.Failure(Exception("connection lost while getting run"))))
result = threads.blockingCallFromThread(
reactor, lambda _: deferred, None)
return result
This works fine. If the server goes down, the connection is lost, and the errback is triggered. However, if the server does not go down and everything shuts down cleanly, onConnectionLost still gets fired, and the anonymous callback here attempts to trigger the errback, causing an AlreadyCalled exception to be raised.
Is there any neat way to check that a deferred has already been fired? I want to avoid wrapping it in a try/except block, but I can always resort to that if that's the only way.
| [
"There are ways, but you really shouldn't do it. Your code that is firing the Deferred should be keeping track of whether it's fired the Deferred or not in the associated state. Really, when you fire the Deferred, you should lose track of it so that it can get properly garbage collected; that way you never need t... | [
5
] | [] | [] | [
"deferred",
"python",
"twisted"
] | stackoverflow_0003337239_deferred_python_twisted.txt |
Q:
Google App Engine: Handlers and WSGI urls
I am new to GAE and I am creating an application with the webapp framework. I was wondering when do you set handlers in your app.yaml and when you define them in your WSGI?
At first I thought you only have one main.py main file running the WSGIApplication but I notice if you want to use the GAE authorization you define that in the handlers. So that means you run multiple WSGIApplications?
I was reading the documents on "Requiring Login or Administrator Status" and it seems they have different applications for different roles.
Maybe something like this?
-- general.py - login:
-- user.py - login: required
-- admin.py: - login: admin
But maybe it's bad to have your WSGI urls spread all over the place?
If I remember correctly if you run django on GAE you point to one py file and let the framework handle everything?
I don't want to use Django yet so was wonder if anybody had some pointers/best practices on how to do url/hanlders with webapp?
A:
Either method of URL-routing is acceptable.
app.yaml-based URL routing
If you can easily structure your app to use app.yaml routing (and authorization), then it's worth trying: it'll be less code you'll have to debug, test, and maintain.
Here's an example (from Google) with multiple entry points: http://google-app-engine-samples.googlecode.com/svn/trunk/gdata_feedfetcher/
Performance should be superior with app.yaml authorization: Your Python script won't need to be run to determine if a user is an admin of the site.
one URL-mapping table
If your app needs something beyond basic URL-routing and authorization then you may find yourself having a comparatively sparse app.yaml and using a larger URL-mapping table.
For example, you want to display a page to all users, but additionally want a "login" link to show up for an admin. This code (for a simple blog) uses this structure.
| Google App Engine: Handlers and WSGI urls | I am new to GAE and I am creating an application with the webapp framework. I was wondering when do you set handlers in your app.yaml and when you define them in your WSGI?
At first I thought you only have one main.py main file running the WSGIApplication but I notice if you want to use the GAE authorization you define that in the handlers. So that means you run multiple WSGIApplications?
I was reading the documents on "Requiring Login or Administrator Status" and it seems they have different applications for different roles.
Maybe something like this?
-- general.py - login:
-- user.py - login: required
-- admin.py: - login: admin
But maybe it's bad to have your WSGI urls spread all over the place?
If I remember correctly if you run django on GAE you point to one py file and let the framework handle everything?
I don't want to use Django yet so was wonder if anybody had some pointers/best practices on how to do url/hanlders with webapp?
| [
"Either method of URL-routing is acceptable.\napp.yaml-based URL routing\nIf you can easily structure your app to use app.yaml routing (and authorization), then it's worth trying: it'll be less code you'll have to debug, test, and maintain. \nHere's an example (from Google) with multiple entry points: http://goog... | [
9
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003335446_google_app_engine_python.txt |
Q:
setDefault for Nested dictionary in python
How do I use setdefault in python for nested dictionary structures.
eg..
self.table[field] = 0
self.table[date] = []
self.table[value] = {}
I would like to setdefault for these.
A:
Assuming self.table is a dict, you could use
self.table.setdefault(field,0)
The rest are all similar. Note that if self.table already has a key field, then the value associated with that key is returned. Only if there is no key field is self.table[field] set to 0.
Edit: Perhaps this is closer to what you want:
import collections
class Foo(object):
def __init__(self):
self.CompleteAnalysis=collections.defaultdict(
lambda: collections.defaultdict(list))
def getFilledFields(self,sentence):
field, field_value, field_date = sentence.split('|')
field_value = field_value.strip('\n')
field_date = field_date.strip('\n')
self.CompleteAnalysis[field]['date'].append(field_date)
self.CompleteAnalysis[field]['value'].append(field_value)
foo=Foo()
foo.getFilledFields('A|1|2000-1-1')
foo.getFilledFields('A|2|2000-1-2')
print(foo.CompleteAnalysis['A']['date'])
# ['2000-1-1', '2000-1-2']
print(foo.CompleteAnalysis['A']['value'])
# ['1', '2']
Instead of keeping track of the count, perhaps just take the length of the list:
print(len(foo.CompleteAnalysis['A']['value']))
# 2
| setDefault for Nested dictionary in python | How do I use setdefault in python for nested dictionary structures.
eg..
self.table[field] = 0
self.table[date] = []
self.table[value] = {}
I would like to setdefault for these.
| [
"Assuming self.table is a dict, you could use\nself.table.setdefault(field,0)\n\nThe rest are all similar. Note that if self.table already has a key field, then the value associated with that key is returned. Only if there is no key field is self.table[field] set to 0.\nEdit: Perhaps this is closer to what you want... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003337512_dictionary_python.txt |
Q:
Setting Return-Path with Python sendmail for a MIME message
Hi would like to set the "Return-Path" header for a MIME message I send with Python.
Basically, I tried something like this :
message = MIMEMultipart()
message.add_header("Return-Path", "something@something.com")
#...
smtplib.SMTP().sendmail(from, to, message.as_string())
The message I receive have its "Return-Path" header set to the same content as the "From" one, even if I explicitly add "Return-Path" header.
How can I set "Return-Path" header for a MIME message sent through smtplib's sendmail in Python ?
Thanks in advance.
A:
Return-Path is set by the SMTP protocol, it's not derived from the message itself. It'll be the Envelope From address is most setups.
The proper way to accomplish this is:
msg = email.message_from_string('\n'.join([
'To: michael@mydomain.com',
'From: michael@mydomain.com',
'Subject: test email',
'',
'Just testing'
]))
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail('something@something.com', 'michael@mydomain.com', msg.as_string())
| Setting Return-Path with Python sendmail for a MIME message | Hi would like to set the "Return-Path" header for a MIME message I send with Python.
Basically, I tried something like this :
message = MIMEMultipart()
message.add_header("Return-Path", "something@something.com")
#...
smtplib.SMTP().sendmail(from, to, message.as_string())
The message I receive have its "Return-Path" header set to the same content as the "From" one, even if I explicitly add "Return-Path" header.
How can I set "Return-Path" header for a MIME message sent through smtplib's sendmail in Python ?
Thanks in advance.
| [
"Return-Path is set by the SMTP protocol, it's not derived from the message itself. It'll be the Envelope From address is most setups.\nThe proper way to accomplish this is:\nmsg = email.message_from_string('\\n'.join([\n 'To: michael@mydomain.com',\n 'From: michael@mydomain.com',\n 'Subject: test email',\... | [
4
] | [] | [] | [
"header",
"mime",
"python",
"return_path",
"smtplib"
] | stackoverflow_0003337055_header_mime_python_return_path_smtplib.txt |
Q:
Pythonic way to write two if-statements
I have two variables that are the result of regex searches.
a = re.search('some regex', str)
b = re.search('different regex', str)
This should return a re object. If they are not None, I want to use the group() method to get the string that it matched. This is the code I am using right now to do this:
if a != None:
a = a.group()
if b != None:
b = b.group()
Is there a more clever way to write these two if-statements? Maybe combine them into one? I think taking up 4 lines to do this is too verbose.
Thanks.
A:
Don't shadow the built-in str, and say
if a:
instead of
if a != None
Not much else to improve imho.
A:
a = a.group() if a else None
A:
If you really must have a one-liner:
a, b = a.group() if a else None, b.group() if b else None
A:
As I commented, I prefer not to reuse a and b for both the Match object and the matched text. I'd go with a function to pull out the match, like this:
>>> def text_or_none(v): return v.group() if v is not None else None
>>> a = text_or_none(re.search("\d", "foo"))
None
>>> b = text_or_none(re.search("\w+", "foo"))
foo
A:
You can refactor little:
a, b = (var.group() if var is not None else None for var in (a,b) )
This keeps value of a if it is for example 0. This is the end of your request.
However after some time passed I came up with this suggestion considering context:
import re
target = """"Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera"
1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d
"""
print target
regs=(',(.*.tif)',',(left.*)',',(right.*)')
re_results=(result.group()
for result in ((re.search(reg, target)
for reg in regs)
)
if result is not None)
print list(re_results)
| Pythonic way to write two if-statements | I have two variables that are the result of regex searches.
a = re.search('some regex', str)
b = re.search('different regex', str)
This should return a re object. If they are not None, I want to use the group() method to get the string that it matched. This is the code I am using right now to do this:
if a != None:
a = a.group()
if b != None:
b = b.group()
Is there a more clever way to write these two if-statements? Maybe combine them into one? I think taking up 4 lines to do this is too verbose.
Thanks.
| [
"Don't shadow the built-in str, and say\nif a:\n\ninstead of\nif a != None\n\nNot much else to improve imho.\n",
"a = a.group() if a else None\n",
"If you really must have a one-liner:\na, b = a.group() if a else None, b.group() if b else None\n\n",
"As I commented, I prefer not to reuse a and b for both the ... | [
5,
4,
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003337128_python_regex.txt |
Q:
Why is django.test.client.Client not keeping me logged in
I'm using django.test.client.Client to test whether some text shows up when a user is logged in. However, I the Client object doesn't seem to be keeping me logged in.
This test passes if done manually with Firefox but not when done with the Client object.
class Test(TestCase):
def test_view(self):
user.set_password(password)
user.save()
client = self.client
# I thought a more manual way would work, but no luck
# client.post('/login', {'username':user.username, 'password':password})
login_successful = client.login(username=user.username, password=password)
# this assert passes
self.assertTrue(login_successful)
response = client.get("/path", follow=True)
#whether follow=True or not doesn't seem to work
self.assertContains(response, "needle" )
When I print response it returns the login form that is hidden by:
{% if not request.user.is_authenticated %}
... form ...
{% endif %}
This is confirmed when I run ipython manage.py shell.
The problem seems to be that the Client object is not keeping the session authenticated.
A:
Just happened to me when retesting an app that has been working and forgotten for some months.
The solution (apart from updating to Django 1.2) is Patch #11821. In short, Python 2.6.5 has some bugfix in the Cookie module, triggering an edge case bug in the test client.
A:
I use RequestContext to get the logged in user into the template context.
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
@login_required
def index(request):
return render_to_response('page.html',
{},
context_instance=RequestContext(request))
and in the template
{% if user.is_authenticated %} ... {{ user.username }} .. {% endif %}
This works as expected (I don't get to this page without logging in, and when I get there, the username is present in response.content) when driven through the test client.
A:
FWIW, an update to Django 1.2 (I was running 1.1.1 before) fixed it. I have no idea what was broken there, considering when I last ran that test suite about 2 weeks ago, it worked great.
| Why is django.test.client.Client not keeping me logged in | I'm using django.test.client.Client to test whether some text shows up when a user is logged in. However, I the Client object doesn't seem to be keeping me logged in.
This test passes if done manually with Firefox but not when done with the Client object.
class Test(TestCase):
def test_view(self):
user.set_password(password)
user.save()
client = self.client
# I thought a more manual way would work, but no luck
# client.post('/login', {'username':user.username, 'password':password})
login_successful = client.login(username=user.username, password=password)
# this assert passes
self.assertTrue(login_successful)
response = client.get("/path", follow=True)
#whether follow=True or not doesn't seem to work
self.assertContains(response, "needle" )
When I print response it returns the login form that is hidden by:
{% if not request.user.is_authenticated %}
... form ...
{% endif %}
This is confirmed when I run ipython manage.py shell.
The problem seems to be that the Client object is not keeping the session authenticated.
| [
"Just happened to me when retesting an app that has been working and forgotten for some months.\nThe solution (apart from updating to Django 1.2) is Patch #11821. In short, Python 2.6.5 has some bugfix in the Cookie module, triggering an edge case bug in the test client.\n",
"I use RequestContext to get the logg... | [
1,
0,
0
] | [] | [] | [
"automated_tests",
"django",
"python",
"testing",
"unit_testing"
] | stackoverflow_0002878602_automated_tests_django_python_testing_unit_testing.txt |
Q:
Personal archive tool, looking for suggestions on improving the code
i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
A:
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.
| Personal archive tool, looking for suggestions on improving the code | i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
| [
"In the else, you call the main function again recursively. Instead, I'd do something like choice == \"0\", which will just cause the while loop to request another entry. This avoids a pointless recursion.\n"
] | [
1
] | [] | [] | [
"archive",
"code_snippets",
"python"
] | stackoverflow_0003338088_archive_code_snippets_python.txt |
Q:
Python - Using os.popen() to parse Unix "ls" - Problems with Killing Child Process
From my understanding, os.popen() opens a pipe within Python and initiates a new sub process. I have a problem when I run a for loop in conjunction with os.popen(). I can't seem to CTRL+C out of the loop. Here is my code:
for FILE in os.popen("ls $MY_DIR/"):
os.system("./processFile " + FILE)
Whenever I try to CTRL+C, Python will stop the ./processFile program but NOT the python program itself!
I have Google'd around and couldn't seem to find the correct answer. Some people recommend using SIGNALS (I tried... it didn't work). Another tried to use PIDs and killing child PIDs but I couldn't seem to get it.
Can someone lead me to a better example so I can stop the programming when I use CTRL+C (SIGINT) ?
A:
I see some answer correctly recommended subprocess.check_call and the OP in a comment said
I'm getting this error:
AttributeError: 'module' object has no
attribute 'check_call'
Per the docs I just linked to, check_call is marked as:
New in version 2.5.
so it looks like the OP is using some ancient version of Python -- 2.4 or earlier -- without mentioning the fact (the current production-ready version is 2.7, and 2.4 is many years old).
The best one can recommend, therefore, is to upgrade! If 2.7 is "too new" for your tastes (as it might be considered in a conservative "shop"), 2.6's latest microrelease should at least be fine -- and it won't just give you subprocess.check_call, but also many additional feautures, bug fixes, and optimizations!-)
A:
The behavior is correct. Ctrl+C stops the foreground process and not its parent process. Calling the shell and using ls is inappropriate here, your code should better be written as follows (untested):
import os
import subprocess
for fname in os.listdir(directory):
path = os.path.join(directory, fname)
subprocess.check_call(["./processFile", path])
| Python - Using os.popen() to parse Unix "ls" - Problems with Killing Child Process | From my understanding, os.popen() opens a pipe within Python and initiates a new sub process. I have a problem when I run a for loop in conjunction with os.popen(). I can't seem to CTRL+C out of the loop. Here is my code:
for FILE in os.popen("ls $MY_DIR/"):
os.system("./processFile " + FILE)
Whenever I try to CTRL+C, Python will stop the ./processFile program but NOT the python program itself!
I have Google'd around and couldn't seem to find the correct answer. Some people recommend using SIGNALS (I tried... it didn't work). Another tried to use PIDs and killing child PIDs but I couldn't seem to get it.
Can someone lead me to a better example so I can stop the programming when I use CTRL+C (SIGINT) ?
| [
"I see some answer correctly recommended subprocess.check_call and the OP in a comment said\n\nI'm getting this error:\n AttributeError: 'module' object has no\n attribute 'check_call'\n\nPer the docs I just linked to, check_call is marked as:\n\nNew in version 2.5.\n\nso it looks like the OP is using some ancien... | [
3,
2
] | [] | [] | [
"c",
"centos",
"ctrl",
"linux",
"python"
] | stackoverflow_0003338033_c_centos_ctrl_linux_python.txt |
Q:
Various queries - MongoDB
This is my table:
unicorns = {'name':'George',
'actions':[{'action':'jump', 'time':123123},
{'action':'run', 'time':345345},
...]}
How can I perform the following queries?
Grab the time of all actions of all unicorns where action=='jump' ?
Grab all actions of all unicorns where time is equal?
e.g. {'action':'jump', 'time':123} and {'action':'stomp', 'time':123}
Help would be amazing =)
A:
Use dot-separated notation:
db.unicorns.find({'actions.action' : 'jump'})
Similarly for times:
db.unicorns.find({'actions.time' : 123})
Edit: if you want to group the results by time, you'll have to use MapReduce.
A:
For the second query, you need to use MapReduce, which can get a big hairy. This will work:
map = function() {
for (var i = 0, j = this.actions.length; i < j; i++) {
emit(this.actions[i].time, this.actions[i].action);
}
}
reduce = function(key, value_array) {
var array = [];
for (var i = 0, j = value_array.length; i < j; i++) {
if (value_array[i]['actions']) {
array = array.concat(value_array[i]['actions']);
} else {
array.push(value_array[i]);
}
}
return ({ actions: array });
}
res = db.test.mapReduce(map, reduce)
db[res.result].find()
This would return something like this, where the _id keys are your timestamps:
{ "_id" : 123, "value" : { "actions" : [ "jump" ] } }
{ "_id" : 125, "value" : { "actions" : [ "neigh", "canter" ] } }
{ "_id" : 127, "value" : { "actions" : [ "whinny" ] } }
Unfortunately, mongo doesn't currently support returning an array from a reduce function, thus necessitating the silly {actions: [...]} syntax.
| Various queries - MongoDB | This is my table:
unicorns = {'name':'George',
'actions':[{'action':'jump', 'time':123123},
{'action':'run', 'time':345345},
...]}
How can I perform the following queries?
Grab the time of all actions of all unicorns where action=='jump' ?
Grab all actions of all unicorns where time is equal?
e.g. {'action':'jump', 'time':123} and {'action':'stomp', 'time':123}
Help would be amazing =)
| [
"Use dot-separated notation:\ndb.unicorns.find({'actions.action' : 'jump'})\n\nSimilarly for times:\ndb.unicorns.find({'actions.time' : 123})\n\nEdit: if you want to group the results by time, you'll have to use MapReduce.\n",
"For the second query, you need to use MapReduce, which can get a big hairy. This will ... | [
2,
2
] | [] | [] | [
"django",
"mongodb",
"nosql",
"pymongo",
"python"
] | stackoverflow_0003330637_django_mongodb_nosql_pymongo_python.txt |
Q:
Does nesting affect efficiency?
Consider languages like Python or JavaScript that allow functions to be nested like this:
print(vector(a * b),(a * c),(b * c)))
or flat like this:
i = (a * b)
j = (a * c)
k = (b * c)
V = vector(i,j,k)
print(V)
How much does the different format affect performance? Can valid generalizations be made, or does it vary a lot by language?
I expect that an optimizing compiler would do inlining and output approximately the same machine code for both. So perhaps this would be just an issue for interpreted languages?
A:
Any function call adds a small number of machine instructions, including more for more parameters, compared to the same code being present inline, or the compile treating the function as inline.
However, it is a VERY small number of machine instructions. So, in most cases you can easily make that back by for any non-trivial sized input by choosing and implementing a more efficient algorithm.
If you are really on the BLAZING EDGE of performance, (chances are you are not, unless you're working on device drivers) then you can start inlining functions or switching to assembly.
But in any case, write the clearest code possible first, then measure before you start worrying about performance. By doing so you'll have fewer bugs and thus more time to optimize your correctly working code.
Edit: if you're referring to such things as anonymous functions, they cause a performance hit, but, as always, measure first, optimize second.
A:
In the Pascal implementations I've seen, where a nested function is allowed access variables in the outer function's scope, the compiler has to maintain an extra frame pointer for each level of nesting, and dereference it any time the nested function accesses something from the outer scope. The only time I would expect this would be an issue would be if a nested function used an outer function's variable within a tight loop. In that case, performance might be impaired by the extra dereferencing operation; copying the variable to the inner scope outside the loop would avoid that extra overhead.
| Does nesting affect efficiency? | Consider languages like Python or JavaScript that allow functions to be nested like this:
print(vector(a * b),(a * c),(b * c)))
or flat like this:
i = (a * b)
j = (a * c)
k = (b * c)
V = vector(i,j,k)
print(V)
How much does the different format affect performance? Can valid generalizations be made, or does it vary a lot by language?
I expect that an optimizing compiler would do inlining and output approximately the same machine code for both. So perhaps this would be just an issue for interpreted languages?
| [
"Any function call adds a small number of machine instructions, including more for more parameters, compared to the same code being present inline, or the compile treating the function as inline.\nHowever, it is a VERY small number of machine instructions. So, in most cases you can easily make that back by for any ... | [
3,
2
] | [] | [] | [
"coding_style",
"javascript",
"nested",
"performance",
"python"
] | stackoverflow_0003337861_coding_style_javascript_nested_performance_python.txt |
Q:
Decrypting a gpg file with gnupg
I'm trying to decrypt some data from gpg files that I've downloaded. Downloading the files to a directory is no problem, but I'm having trouble actually decrypting them. Here's what I'm doing right now:
def extractGPGs(gpglist,path,gpgPath="\"C:\\Program Files\\GNU\\GnuPG\\gpg.exe\""):
os.chdir(path)
if not os.path.isdir("GPGFiles"):
os.mkdir("GPGFiles")
if not os.path.isdir("OtherFiles"):
os.mkdir("OtherFiles")
if gpglist == None:
print "No GPG files found"
return
try:
gpg = gnupg.GPG(gpgbinary=gpgPath)
except:
raise "Path to gpg.exe is bad"
print "Extracting GPG Files..."
for filename in gpglist:
print "Extracting %s..." % filename
stream = open(filename,"rb")
decrypted_data = gpg.decrypt_file(stream,output=".\\OtherFiles")
stream.close()
print "Finished Extracting GPG Files"
And here is the error that I'm getting:
Traceback (most recent call last):
File "C:\Documents and Settings\nlesniewski\Desktop\downloadData.py", line 281, in <module>
main(vendor,category)
File "C:\Documents and Settings\nlesniewski\Desktop\downloadData.py", line 273, in main
extractAndParse.main(info['LocalFolder'])
File "C:\Documents and Settings\nlesniewski\Desktop\extractAndParse.py", line 147, in main
extractGPGs(getGPGs(getAllArchives(path)),path)
File "C:\Documents and Settings\nlesniewski\Desktop\extractAndParse.py", line 133, in extractGPGs
decrypted_data = gpg.decrypt_file(stream,output=".\\OtherFiles")
File "C:\Python25\Lib\site-packages\gnupg.py", line 574, in decrypt_file
os.remove(output) # to avoid overwrite confirmation message
WindowsError: [Error 5] Access is denied: '.\\OtherFiles'
Why am I getting this error, and, more importantly, how can I decrypt the gpg's?
A:
Maybe you need the output to be a file name instead of a directory.
| Decrypting a gpg file with gnupg | I'm trying to decrypt some data from gpg files that I've downloaded. Downloading the files to a directory is no problem, but I'm having trouble actually decrypting them. Here's what I'm doing right now:
def extractGPGs(gpglist,path,gpgPath="\"C:\\Program Files\\GNU\\GnuPG\\gpg.exe\""):
os.chdir(path)
if not os.path.isdir("GPGFiles"):
os.mkdir("GPGFiles")
if not os.path.isdir("OtherFiles"):
os.mkdir("OtherFiles")
if gpglist == None:
print "No GPG files found"
return
try:
gpg = gnupg.GPG(gpgbinary=gpgPath)
except:
raise "Path to gpg.exe is bad"
print "Extracting GPG Files..."
for filename in gpglist:
print "Extracting %s..." % filename
stream = open(filename,"rb")
decrypted_data = gpg.decrypt_file(stream,output=".\\OtherFiles")
stream.close()
print "Finished Extracting GPG Files"
And here is the error that I'm getting:
Traceback (most recent call last):
File "C:\Documents and Settings\nlesniewski\Desktop\downloadData.py", line 281, in <module>
main(vendor,category)
File "C:\Documents and Settings\nlesniewski\Desktop\downloadData.py", line 273, in main
extractAndParse.main(info['LocalFolder'])
File "C:\Documents and Settings\nlesniewski\Desktop\extractAndParse.py", line 147, in main
extractGPGs(getGPGs(getAllArchives(path)),path)
File "C:\Documents and Settings\nlesniewski\Desktop\extractAndParse.py", line 133, in extractGPGs
decrypted_data = gpg.decrypt_file(stream,output=".\\OtherFiles")
File "C:\Python25\Lib\site-packages\gnupg.py", line 574, in decrypt_file
os.remove(output) # to avoid overwrite confirmation message
WindowsError: [Error 5] Access is denied: '.\\OtherFiles'
Why am I getting this error, and, more importantly, how can I decrypt the gpg's?
| [
"Maybe you need the output to be a file name instead of a directory.\n"
] | [
2
] | [] | [] | [
"encryption",
"gnupg",
"python"
] | stackoverflow_0003338485_encryption_gnupg_python.txt |
Q:
Python Permutation code
Started to learn programming 2 months ago, in one of my little projects i encountered the need to generate permutations of list of objects.
I knew that i'll find how to do this if i'll just searched for it, but i wanted to make one of my own, so i worked up and made my own permutation generator code:
def perm(lst, c = [], x = 0):
i = -1
g = len(lst) - 1
if x == g:
while i < g:
i += 1
if lst[i] in c:
continue
c.append(lst[i])
print(c)
del c[-1]
i = g
else:
while i < g:
if x == 0:
del c[:]
elif g == x:
del c[-1]
elif len(c) > x:
del c[-1]
continue
i += 1
if lst[i] in c:
continue
c.append(lst[i])
x + 1
perm(lst, c, x + 1)
This is what it gives if i run it:
perm(range(2))
[0, 1]
[1, 0]
perm([1, 4, 5])
[1, 4, 5]
[1, 5, 4]
[4, 1, 5]
[4, 5, 1]
[5, 1, 4]
[5, 4, 1]
It works as i expected, but when i use bigger lists it take some time for it to generate all the permutations of the list.
So all i want is hints on how to improve my code, only hints.
Or if you can tell me what should i learn to be able to make a better generator?
Thanks in advance for all the helpers.
A:
>>> from itertools import permutations
>>> list(permutations(range(2)))
[(0, 1), (1, 0)]
>>> list(permutations([1, 4, 5]))
[(1, 4, 5), (1, 5, 4), (4, 1, 5), (4, 5, 1), (5, 1, 4), (5, 4, 1)]
In the docs there is Python code available for legacy versions.
A note re your code, x + 1 doesn't do anything as you're not assigning result of that expression to anyting.
A:
Generating permutations is often done recursively. Given a list of 5 items, the permutations can be created by picking each of the 5 elements in turn as the first element of the answer, then for each of them permuting the remaining 4 elements, and appending them together.
A:
The best way to understand what is making your code slow is to actually measure it. When you attempt to guess at what will make something fast, it's often wrong. You've got the right idea in that you're noticing that your code is slower and it's time for some improvement.
Since this is a fairly small piece of code, the timeit module will probably be useful. Break the code up into sections, and time them. A good rule of thumb is that it's better to look at an inner loop for improvements, since this will be executed the most times. In your example, this would be the loop inside the perm function.
It is also worth noting that while loops are generally slower than for loops in python, and that list comprehensions are faster than both of these.
Once you start writing longer scripts, you'll want to be aware of the ability to profile in python, which will help you identify where your code is slow. Hopefully this has given you a few places to look.
A:
OK, for large lists, a recursive solution will take more and more time & space, and eventually reach the recursion limit and die. So, on the theoretical side, you could work on ways to save time and space.
Hint: tail-recursive functions (such as the one you've written) can be rewritten as loops
On a more practical side, you may consider the use cases of your function. Maybe there's somebody who doesn't want the whole list of permutations at once, but a single one each time - there's a good opportunity to learn about yield and generators.
Also, for something generally not directly applicable to your question: k-combinations and multisets are closely related to permutations. Perhaps you can extend your function (or write a new one) which will produce the k-combinations and/or multiset the user asks for.
A:
The first thing I notice is that the code is hard to understand. The variable names are completely meaningless, replace them with meaningful names. It also seems like you're using i as a loop index, which is almost always bad style in python, because you can do for item in list:.
A:
This is not really performance related, but there is a glaring bug in the code. Using a list as a default parameter does not do what you think it does - it will create one list object that will be shared by every call to perm(), so the second time you call perm you will have the value in c of whatever it contained when the last call finished. This is a common beginner's error.
You also say "when I use bigger lists it takes some time to generate all the permutations of the list". What did you expect? The number of permutations is equal to the factorial of the length of the list, and that grows big fast! For example a list of length 20 will have 2432902008176640000 permutations. Even the most efficient algorithm in the world is "going to take some time" for a list this size, even if it did not run out of memory first. If our hypothetical algorithm generated a billion permutations a second it would still take 77 years to run. Can you be more specific about the length of lists you are using and how long it is taking?
| Python Permutation code | Started to learn programming 2 months ago, in one of my little projects i encountered the need to generate permutations of list of objects.
I knew that i'll find how to do this if i'll just searched for it, but i wanted to make one of my own, so i worked up and made my own permutation generator code:
def perm(lst, c = [], x = 0):
i = -1
g = len(lst) - 1
if x == g:
while i < g:
i += 1
if lst[i] in c:
continue
c.append(lst[i])
print(c)
del c[-1]
i = g
else:
while i < g:
if x == 0:
del c[:]
elif g == x:
del c[-1]
elif len(c) > x:
del c[-1]
continue
i += 1
if lst[i] in c:
continue
c.append(lst[i])
x + 1
perm(lst, c, x + 1)
This is what it gives if i run it:
perm(range(2))
[0, 1]
[1, 0]
perm([1, 4, 5])
[1, 4, 5]
[1, 5, 4]
[4, 1, 5]
[4, 5, 1]
[5, 1, 4]
[5, 4, 1]
It works as i expected, but when i use bigger lists it take some time for it to generate all the permutations of the list.
So all i want is hints on how to improve my code, only hints.
Or if you can tell me what should i learn to be able to make a better generator?
Thanks in advance for all the helpers.
| [
">>> from itertools import permutations\n>>> list(permutations(range(2)))\n[(0, 1), (1, 0)]\n>>> list(permutations([1, 4, 5]))\n[(1, 4, 5), (1, 5, 4), (4, 1, 5), (4, 5, 1), (5, 1, 4), (5, 4, 1)]\n\nIn the docs there is Python code available for legacy versions.\nA note re your code, x + 1 doesn't do anything as you... | [
3,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003336862_python.txt |
Q:
How do I use pylons (paste) webtest with multiple checkboxes with the same name?
Suppose I have a form like this:
<form id='myform'>
Favorite colors?
<input type='checkbox' name='color' value='Green'>Green
<input type='checkbox' name='color' value='Blue'>Blue
<input type='checkbox' name='color' value='Red'>Red
<input type='submit' value='Submit'>
</form>
How do I use webtest's form library to test submitting multiple values?
A:
Not sure about the form library, but you could use a MultiDict (you might have to use UnicodeMultiDict in some cases, I'm not sure).
from webob.multidict import MultiDict
class TestSomeController(TestController):
def test_something(self):
params = MultiDict()
params.add('some_param', '1')
params.add('color', 'Green')
params.add('color', 'Blue')
response = self.app.post(url('something'), params=params)
assert 'something' in response
I never used WebTest to submit actual forms, but, looking at the source of the Form class, you can set the index of the field you want to set to disambiguate. I've not tested it, but something like that would probably work:
form = response.form
form.set('color', True, 0)
form.set('color', True, 2)
| How do I use pylons (paste) webtest with multiple checkboxes with the same name? | Suppose I have a form like this:
<form id='myform'>
Favorite colors?
<input type='checkbox' name='color' value='Green'>Green
<input type='checkbox' name='color' value='Blue'>Blue
<input type='checkbox' name='color' value='Red'>Red
<input type='submit' value='Submit'>
</form>
How do I use webtest's form library to test submitting multiple values?
| [
"Not sure about the form library, but you could use a MultiDict (you might have to use UnicodeMultiDict in some cases, I'm not sure).\nfrom webob.multidict import MultiDict\n\nclass TestSomeController(TestController):\n\n def test_something(self):\n params = MultiDict()\n params.add('some_param', '... | [
4
] | [] | [] | [
"paste",
"pylons",
"python",
"webob",
"webtest"
] | stackoverflow_0003337736_paste_pylons_python_webob_webtest.txt |
Q:
Python: get currently logged user and his/her special folders
Does this code win32api.GetUserName() works fine on all win system from win 2000 to win 7 ?
What about if user is not local user but domain user, does it still work ?
When i use this function shell.SHGetFolderPath(0, shellcon.CSIDL_someDirectory, 0, 0), do I get wanted folder for currently logged user ?
Any help appreciated.
A:
There is a module called getpass which has a getpass.getuser() function.
This should work on all windows versions. It did on all the versions I've tried anyway. The user I've used wasn't local either.
| Python: get currently logged user and his/her special folders | Does this code win32api.GetUserName() works fine on all win system from win 2000 to win 7 ?
What about if user is not local user but domain user, does it still work ?
When i use this function shell.SHGetFolderPath(0, shellcon.CSIDL_someDirectory, 0, 0), do I get wanted folder for currently logged user ?
Any help appreciated.
| [
"There is a module called getpass which has a getpass.getuser() function. \nThis should work on all windows versions. It did on all the versions I've tried anyway. The user I've used wasn't local either.\n"
] | [
2
] | [] | [] | [
"python",
"pywin32",
"windows"
] | stackoverflow_0003339191_python_pywin32_windows.txt |
Q:
getting started with processing data with python
i have an excel spreadsheet of about 3 million cells. i asked the following question and i liked the answer about saving the spreadsheet as CSV and then processing it with python:
solution to perform lots of calculations on 3 million data points and make charts
is there a library that i can use that will read the csv into a matrix or should i write one myself?
does python speak with VBA at all?
after i am done processing the data, is it simple to put it back in the form of a CSV so that i can open it in excel for viewing?
A:
I like NumPy's loadtxt for this sort of thing. Very configurable for reading CSVs. And savetxt for putting it back after manipulation. Or you could check out the built in csv module if you'd rather not install anything new.
A:
is there a library that i can use that will read the csv into a matrix or should i write one myself?
The csv module handles just about everything you could want.
does python speak with VBA at all?
Iron Python might.
after i am done processing the data, is it simple to put it back in the form of a CSV so that i can open it in excel for viewing?
The csv module handles just about everything you could want.
Suggestion: Read this: http://docs.python.org/library/csv.html
A:
If we speak pythonish, why not to use http://www.python-excel.org/ ?
Example of read file:
import xlrd
rb = xlrd.open_workbook('file.xls',formatting_info=True)
sheet = rb.sheet_by_index(0)
for rownum in range(sheet.nrows):
row = sheet.row_values(rownum)
for c_el in row:
print c_el
Writing the new file:
import xlwt
from datetime import datetime
font0 = xlwt.Font()
font0.name = 'Times New Roman'
font0.colour_index = 2
font0.bold = True
style0 = xlwt.XFStyle()
style0.font = font0
style1 = xlwt.XFStyle()
style1.num_format_str = 'D-MMM-YY'
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
ws.write(0, 0, 'Test', style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
There are other examples on the page.
A:
If you don't want to deal with changing back and forth from CSV you can use win32com, which can be downloaded here. http://python.net/crew/mhammond/win32/Downloads.html
| getting started with processing data with python | i have an excel spreadsheet of about 3 million cells. i asked the following question and i liked the answer about saving the spreadsheet as CSV and then processing it with python:
solution to perform lots of calculations on 3 million data points and make charts
is there a library that i can use that will read the csv into a matrix or should i write one myself?
does python speak with VBA at all?
after i am done processing the data, is it simple to put it back in the form of a CSV so that i can open it in excel for viewing?
| [
"I like NumPy's loadtxt for this sort of thing. Very configurable for reading CSVs. And savetxt for putting it back after manipulation. Or you could check out the built in csv module if you'd rather not install anything new.\n",
"\nis there a library that i can use that will read the csv into a matrix or shoul... | [
3,
3,
1,
1
] | [] | [] | [
"excel",
"python",
"vba"
] | stackoverflow_0003338567_excel_python_vba.txt |
Q:
Can this image processing code be optimised to use less memory?
I have a python function that takes a string s-expression like "(add (sub 10 5) 5)", where "add" and "sub" are actually image processing functions, and evaluates and creates the image represented in the string. The image processing functions take constants, variables, or other images (represented as lists of vectors), and return images represented the same way. PIL is used to convert the image represented as a list of vectors into an image file.
To evaluate the prefix notation s-expressions, I convert the s-expr to a list, reverse it, and iterate the tokens until a function is found, at which point the image processing function is performed and the resulting image replaces the function and its arguments in the list. This is done until only one element is left in the list, which is the final image.
The image processing functions are simple- most perform some mathematical operation to each of the (r,g,b) values in the image(s).
The problem is my computer comes to a standstill if I want to make decent sized images for more complex expressions. Can this be optimised to use less memory?
def createImage(self, sexpr, filename, (picWidth, picHeight)):
"""Use the image processing functions in ImgProcessing
to create an image from the procedural information
contained in the s-expression."""
img = Image.new("RGB",(picWidth,picHeight),(255,255,255))
ip = ImgProcessing(picWidth,picHeight)
# Split s-expression into list of tokens and reverse
sList = sexpr.replace("(","").replace(")","").split()
sList.reverse()
while len(sList) > 1:
for index,token in enumerate(sList):
# If token is an image processing function
if type(token) == str and self.FuncSet.has_key(token):
# If this function takes one argument
if self.FuncSet[token] == 1:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + ")")
sList = sList[:index-1] + [rawImage] + sList[index+1:]
break
# If this function takes two arguments
elif self.FuncSet[token] == 2:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + "," + "\"" + str(sList[index-2]) + "\"" +
")")
sList = sList[:index-2] + [rawImage] + sList[index+1:]
break
img.putdata(sList[0])
img.save(filename)
A:
Profiling can tell you where the program is spending most of its time.
Second, is str(sList[index-1]) converting an Image into a string? Does ip.token(...) return an Image? If so, you are converting between string and Image a number of times. That might be very slow.
It might help to change
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + ")")
to something like
getattr(ip,token)(sList[index-1])
but of course this depends on what type of argument ip.token expects. I couldn't find any information on ImgProcessing from Googling. Is this a custom class? If so, it might help to explain more about how it works.
If ip.token can be changed from taking strings to taking Images, that might be a big improvement.
A:
In my experience, anything that you do in pure Python or PIL pixel-by-pixel on a large image is going to be slow as molasses in January. Consider moving the low-level stuff into a Python extension written in C. I have used OpenCV, but it takes some learning.
| Can this image processing code be optimised to use less memory? | I have a python function that takes a string s-expression like "(add (sub 10 5) 5)", where "add" and "sub" are actually image processing functions, and evaluates and creates the image represented in the string. The image processing functions take constants, variables, or other images (represented as lists of vectors), and return images represented the same way. PIL is used to convert the image represented as a list of vectors into an image file.
To evaluate the prefix notation s-expressions, I convert the s-expr to a list, reverse it, and iterate the tokens until a function is found, at which point the image processing function is performed and the resulting image replaces the function and its arguments in the list. This is done until only one element is left in the list, which is the final image.
The image processing functions are simple- most perform some mathematical operation to each of the (r,g,b) values in the image(s).
The problem is my computer comes to a standstill if I want to make decent sized images for more complex expressions. Can this be optimised to use less memory?
def createImage(self, sexpr, filename, (picWidth, picHeight)):
"""Use the image processing functions in ImgProcessing
to create an image from the procedural information
contained in the s-expression."""
img = Image.new("RGB",(picWidth,picHeight),(255,255,255))
ip = ImgProcessing(picWidth,picHeight)
# Split s-expression into list of tokens and reverse
sList = sexpr.replace("(","").replace(")","").split()
sList.reverse()
while len(sList) > 1:
for index,token in enumerate(sList):
# If token is an image processing function
if type(token) == str and self.FuncSet.has_key(token):
# If this function takes one argument
if self.FuncSet[token] == 1:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + ")")
sList = sList[:index-1] + [rawImage] + sList[index+1:]
break
# If this function takes two arguments
elif self.FuncSet[token] == 2:
rawImage = eval("ip." + token + "(" + "\"" + str(sList[index-1]) +
"\"" + "," + "\"" + str(sList[index-2]) + "\"" +
")")
sList = sList[:index-2] + [rawImage] + sList[index+1:]
break
img.putdata(sList[0])
img.save(filename)
| [
"Profiling can tell you where the program is spending most of its time.\nSecond, is str(sList[index-1]) converting an Image into a string? Does ip.token(...) return an Image? If so, you are converting between string and Image a number of times. That might be very slow.\nIt might help to change\nrawImage = eval(\"ip... | [
2,
0
] | [] | [] | [
"image_processing",
"memory_management",
"python",
"python_imaging_library",
"s_expression"
] | stackoverflow_0003339728_image_processing_memory_management_python_python_imaging_library_s_expression.txt |
Q:
error: ambiguous overload for 'operator/'
I am new to c, and the following is giving me some grief:
int i,j,ll,k;
double ddim,ddip,ddjm,ddjp,ddlm,ddlp;
for(i=1; i<(mx-1); i++){
for(j=1; j<(my-1); j++){
for(ll=1; ll<(mz-1); ll++){
ddim=0.5*k
ddip=0.5*k
ddjm=0.5*k
ddjp=0.5*k
ddlm=0.5*k
ddlp=0.5*k
Wijl(i,j,ll) = ((1.0/h_x)*(ddip) \
((1.0/h_x)*(ddim)) \
((1.0/h_y)*(ddjp)) \
((1.0/h_y)*(ddjm)) \
((1.0/h_z)*(ddlp)) \
((1.0/h_z)*(ddlm)) ;
}
}
}
I then compile this with gcc using python and scipy, passing it everything that is not initialized, but I know the problem is in the 1.0/h_x part of the code. If I compile basic c statements using python/gcc it works, so I am not having a python/gcc issue.
The error I am getting is: "error: ambiguous overload for 'operator/' in '1.0e+0 / h_x'
It seems like it is trying to do assignment overloading, and all I want to do is division!
Any help would be greatly appreciated! :)
Thanks,
Tyler
A:
I think it's trying to say that it's not clear what type h_x is, so it doesn't know which of the overloaded / operators to use (double/int, double/double, etc). You could try casting it (h_x) to int or double to tell it what version to use.
A:
If h_x is float then dividing 1.0 (by default double) by it leaves C wondering whether to do the operation in float or double math.
If you want to do it in floats, change 1.0 to 1.0f; if double, either declare or cast your h_x to double.
If h_x is int (that's what I'm afraid of) you'd probably do well to assign your h_?'s to three corresponding float or double temp variables outside the loop, to save the compiler from (possibly) doing lots of unnecessary int-to-float conversions. As a side effect, this will make your type ambiguity go away.
You could also simplify the code a bit by getting rid of those 1.0's: Instead of multiplying by the reciprocal, you could simply divide those expressions by h_whatever. Especially as the right half of each of those lines is already doing something similar.
A:
I strongly suggest that you carefully peal off all of the utterly redundant parentheses and examine carefully what is left.
For example, this snippet:
((1.0/h_x)*(ddim)*((q(i,j,ll) - q(i-1,j,ll)))/h_x)
boils down to:
ddim * (q(i,j,ll) - q(i-1,j,ll)) / h_x / h_x
Note that the original separation of the two occurrences of / h_x makes one wonder what the original intention was.
| error: ambiguous overload for 'operator/' | I am new to c, and the following is giving me some grief:
int i,j,ll,k;
double ddim,ddip,ddjm,ddjp,ddlm,ddlp;
for(i=1; i<(mx-1); i++){
for(j=1; j<(my-1); j++){
for(ll=1; ll<(mz-1); ll++){
ddim=0.5*k
ddip=0.5*k
ddjm=0.5*k
ddjp=0.5*k
ddlm=0.5*k
ddlp=0.5*k
Wijl(i,j,ll) = ((1.0/h_x)*(ddip) \
((1.0/h_x)*(ddim)) \
((1.0/h_y)*(ddjp)) \
((1.0/h_y)*(ddjm)) \
((1.0/h_z)*(ddlp)) \
((1.0/h_z)*(ddlm)) ;
}
}
}
I then compile this with gcc using python and scipy, passing it everything that is not initialized, but I know the problem is in the 1.0/h_x part of the code. If I compile basic c statements using python/gcc it works, so I am not having a python/gcc issue.
The error I am getting is: "error: ambiguous overload for 'operator/' in '1.0e+0 / h_x'
It seems like it is trying to do assignment overloading, and all I want to do is division!
Any help would be greatly appreciated! :)
Thanks,
Tyler
| [
"I think it's trying to say that it's not clear what type h_x is, so it doesn't know which of the overloaded / operators to use (double/int, double/double, etc). You could try casting it (h_x) to int or double to tell it what version to use.\n",
"If h_x is float then dividing 1.0 (by default double) by it leaves ... | [
1,
0,
0
] | [] | [] | [
"c",
"math",
"numpy",
"overloading",
"python"
] | stackoverflow_0003338125_c_math_numpy_overloading_python.txt |
Q:
Architecting from scratch in Python: what to use?
I'm lucky enough to have full control over the architecture of my company's app, and I've decided to scrap our prototype written in Ruby/Rails and start afresh in Python. This is for a few reasons: I want to learn Python, I prefer the syntax and I've basically said "F**k it, let's do it."
So, baring in mind this is going to be a pretty intensive app, I'd like to hear your opinions on the following:
Generic web frameworks
ORM/Database Layer (perhaps to work with MongoDB)
RESTful API w/ oAuth/xAuth authentication
Testing/BDD support
Message queue (I'd like to keep this in Python if possible)
The API is going to need to interface with a Clojure app to handle some internal data stuff, and interface with the message queue, so if it's not Python it'd be great to have some libraries to it.
TDD/BDD is very important to me, so the more tested, the better!
It'll be really interesting to read your thoughts on this. Much appreciated.
My best,
Jamie
A:
Frameworks
OK, so I'm a little biased here as I currently make extensive use of Django and organise the Django User Group in London so bear that in mind when reading the following.
Start with Django because it's a great gateway drug. Lots of documentation and literature, a very active community of people to talk to and lots of example code around the web.
That's a completely non-technical reason. Pylons is probably purer in terms of Python philosophy (being much more a collection of discrete bits and pieces) but lots of the technical stuff is personal preference, at least until you get into Python more. Compare the very active Django tag on Stack Overflow with that of pylons or turbogears though and I'd argue getting started is simply easier with Django irrespective of anything to do with code.
Personally I default to Django, but find that an increasing amount of time I actually opt for writing using simpler micro frameworks (think Sinatra rather than Rails). Lots of things to choose from (good list here, http://fewagainstmany.com/blog/python-micro-frameworks-are-all-the-rage). I tend to use MNML (because I wrote parts of it and it's tiny) but others are actively developed. I tend to do this for small, stupid web services which are then strung together with a Django project in the middle serving people.
Worth noting here is appengine. You have to work within it's limitations and it's not designed for everything but it's a great way to just play with Python and get something up and working quickly. It makes a great testbed for learning and experimentation.
Mongo/ORM
On the MongoDB front you'll likely want to look at the basic python mongo library ( http://api.mongodb.org/python/ ) first to see if it has everything you need. If you really do want something a little more ORM like then mongoengine (http://hmarr.com/mongoengine/) might be what you're looking for. A bunch of folks are also working on making Django specifically integrate more seamlessly with nosql backends. Some of that is for future Django releases, but django-norel ( http://www.allbuttonspressed.com/projects/django-nonrel) has code now.
For relational data SQLAlchemy ( http://www.sqlalchemy.org/) is good if you want something standalone. Django's ORM is also excellent if you're using Django.
API
The most official Oauth library is python-oauth2 ( http://github.com/simplegeo/python-oauth2), which handily has a Django example as part of it's docs.
Piston ( http://bitbucket.org/jespern/django-piston/wiki/Home) is a Django app which provides lots of tools for building APIs. It has the advantage of being pretty active and well maintained and in production all over the place. Other projects exist too, including Dagny ( http://zacharyvoase.github.com/dagny/) which is an early attempt to create something akin to RESTful resources in Rails.
In reality any Python framework (or even just raw WSGI code) should be reasonably good for this sort of task.
Testing
Python has unittest as part of it's standard library, and unittest2 is in python 2.7 (but backported to previous versions too http://pypi.python.org/pypi/unittest2/0.1.4). Some people also like Nose ( http://code.google.com/p/python-nose/), which is an alternative test runner with some additional features. Twill ( http://twill.idyll.org/) is also nice, it's a "a simple scripting language for Web browsing", so handy for some functional testing. Freshen ( http://github.com/rlisagor/freshen) is a port of cucumber to Python. I haven't yet gotten round to using this in anger, but a quick look now suggests it's much better than when I last looked.
I actually also use Ruby for high level testing of Python apps and apis because I love the combination of celerity and cucumber. But I'm weird and get funny looks from other Python people for this.
Message Queues
For a message queue, whatever language I'm using, I now always use RabbitMQ. I've had some success with stompserver in the past but Rabbit is awesome. Don't worry that it's not itself written in Python, neither is PostgresSQL, Nginx or MongoDB - all for good reason. What you care about are the libraries available. What you're looking for here is py-amqplib ( http://barryp.org/software/py-amqplib/) which is a low level library for talking amqp (the protocol for talking to rabbit as well as other message queues). I've also used Carrot ( http://github.com/ask/carrot/), which is easier to get started with and provides a nicer API. Think bunny in Ruby if you're familiar with that.
Environment
Whatever bits and pieces you decide to use from the Python ecosystem I'd recommend getting to who pip and virtualenv ( http://clemesha.org/blog/2009/jul/05/modern-python-hacker-tools-virtualenv-fabric-pip/ - note that fabric is also cool, but not essential and these docs are out of date on that tool). Think about using Ruby without gem, bundler or rvm and you'll be in the right direction.
A:
Ok, you might be making a mistake, the same one I made when I started with python.
Before you decide on a thing like django, which is an excellent, yet atypical python web framework, spend an night cuddled up with:
This, is a good start. Make sure you do A little Werkzeug watching , Then check out
some classic WebOb. Maybe, if you feel the fire in the blood, and you might, wsgi is a bit flawed, but only to the gods, check out Flask
I'm not saying use it, Django is beautiful too, but if you don't know python, and you go through django, you run the risk of learning a framework.
WSGI is super straightforward. You'll find out about Paste, and Pastescript, and Pylons.
Then, make your decision. It'll be much easier learning stuff doing bare bones wsgi or Flask, stuff like variable assignment, using the interpreter, style concerns, testing, on 3 files for a couple of nights, instead of django. Take 2 nights. Then you'll see the great similarity between python web frameworks, instead of the differences. Hell, you might even roll with Flask.
Just some advice, I did the same thing with ruby, going in through Rails, and... well, strong words were said.
Language, then basic wsgi and testing, then pick your framework and roll
A:
I'm new to python myself, and plan to get more in depth with it this year. I've had a few false starts at this, but always professional needs bring me back to PHP. The few times I've done some development, I've had really good experiences with web2py as a python framework. It's quite well done, and complete in features, while still being extremely lightweight. The database layer seems to be very flexible and mature.
As for TDD/BDD and the rest of your questions, I don't have any experience with python options, but would be interested to hear what others say.
A:
I am using Twisted Framework based Nevow library for python based web app.
All your criteria fit into this single framework.
| Architecting from scratch in Python: what to use? | I'm lucky enough to have full control over the architecture of my company's app, and I've decided to scrap our prototype written in Ruby/Rails and start afresh in Python. This is for a few reasons: I want to learn Python, I prefer the syntax and I've basically said "F**k it, let's do it."
So, baring in mind this is going to be a pretty intensive app, I'd like to hear your opinions on the following:
Generic web frameworks
ORM/Database Layer (perhaps to work with MongoDB)
RESTful API w/ oAuth/xAuth authentication
Testing/BDD support
Message queue (I'd like to keep this in Python if possible)
The API is going to need to interface with a Clojure app to handle some internal data stuff, and interface with the message queue, so if it's not Python it'd be great to have some libraries to it.
TDD/BDD is very important to me, so the more tested, the better!
It'll be really interesting to read your thoughts on this. Much appreciated.
My best,
Jamie
| [
"Frameworks\nOK, so I'm a little biased here as I currently make extensive use of Django and organise the Django User Group in London so bear that in mind when reading the following.\nStart with Django because it's a great gateway drug. Lots of documentation and literature, a very active community of people to talk... | [
29,
14,
4,
0
] | [] | [] | [
"frameworks",
"orm",
"python",
"rest"
] | stackoverflow_0003143115_frameworks_orm_python_rest.txt |
Q:
When download an image, does urllib have a return code if it's successful or not?
I want to download an image file from potentially 5 sites.
Meaning that if the image wasn't found in site#1, try site#2, etc.
How can I test if the file was downloaded?
A:
You can call getcode() on the object you get back from urlopen().
getcode() gives you the HTTP status response from the server, so you can test to see if you got an HTTP 200 response, which would mean the download was successful.
| When download an image, does urllib have a return code if it's successful or not? | I want to download an image file from potentially 5 sites.
Meaning that if the image wasn't found in site#1, try site#2, etc.
How can I test if the file was downloaded?
| [
"You can call getcode() on the object you get back from urlopen().\ngetcode() gives you the HTTP status response from the server, so you can test to see if you got an HTTP 200 response, which would mean the download was successful.\n"
] | [
3
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0003340152_python_urllib.txt |
Q:
post to page to login using beautiful soup
I'm using python and beautifulsoup (new to both!), and I want to login to a suppliers website.
So their form looks like (simplified):
<form name=loginform action=/index.html method="post">
<input name=user>
<input name=pass">
</form>
Is there a way to keep track for cookies?
A:
Do some more reading.
Read about urllib2 That's what you use to do a POST to login. If you know the <input> names, you don't need Beautiful Soup. http://docs.python.org/library/urllib2.html
Beautiful Soup is what you use to parse a page of results. After you login. After you post the real request.
A:
Use mechanize -- that's just the best (3rd party) Python library for interacting with web forms, keeping track of cookies &c.
| post to page to login using beautiful soup | I'm using python and beautifulsoup (new to both!), and I want to login to a suppliers website.
So their form looks like (simplified):
<form name=loginform action=/index.html method="post">
<input name=user>
<input name=pass">
</form>
Is there a way to keep track for cookies?
| [
"Do some more reading. \nRead about urllib2 That's what you use to do a POST to login. If you know the <input> names, you don't need Beautiful Soup. http://docs.python.org/library/urllib2.html\nBeautiful Soup is what you use to parse a page of results. After you login. After you post the real request.\n",
"U... | [
9,
8
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003340190_beautifulsoup_python.txt |
Q:
python csv: getting subset
here is a snapshot of my csv:
alex 123f 1
harry fwef 2
alex sef 3
alex gsdf 4
alex wf35 6
harry sdfsdf 3
i would like to get the subset of this data where the occurrence of anything in the first column (harry, alex) is at least 4. so i want the resulting data set to be:
alex 123f 1
alex sef 3
alex gsdf 4
alex wf35 6
A:
Clearly, you cannot decide which rows are interesting until you've seen all rows (since the very last row might be the one turning some count from three to four and thereby making some previously seen rows interesting, for example;-). So, unless your CSV file is horribly huge, suck it all into memory, first, as a list...:
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
then, do the counting -- Python 2.7 has a better way, but assuming you're still on 2.6 like most of us...:
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
and finally do the selection loop...:
for row in data:
if counter[row[0]] >= 4:
print row
Of course, this prints each interesting row as a roughly-hewed list (with square brackets and quotes around the items), but it will be easy to format it in any way you might prefer.
A:
if Python is not a must
$ gawk '{b[$1]++;c[++d,$1]=$0}END{for(i in b){if(b[i]>=4){for(j=1;j<=d;j++){print c[j,i]}}}}' file
And yes, 70MB file is fine.
| python csv: getting subset | here is a snapshot of my csv:
alex 123f 1
harry fwef 2
alex sef 3
alex gsdf 4
alex wf35 6
harry sdfsdf 3
i would like to get the subset of this data where the occurrence of anything in the first column (harry, alex) is at least 4. so i want the resulting data set to be:
alex 123f 1
alex sef 3
alex gsdf 4
alex wf35 6
| [
"Clearly, you cannot decide which rows are interesting until you've seen all rows (since the very last row might be the one turning some count from three to four and thereby making some previously seen rows interesting, for example;-). So, unless your CSV file is horribly huge, suck it all into memory, first, as a... | [
5,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003339694_csv_python.txt |
Q:
with beautifulsoup, how to reference the first table after a given form
I want to drill down into my html, specifically I want to get the first html table that is AFTER a form that looks like:
<form method="POST" action="/parts.html">
..
<table ...>
...
</table>
..
</form>
So this table has <tr> for each product.
My utlimate goal here is to loop through each tablerow, and then I need to extract the product name, price, image url, etc.
What should my strategy be, and what methods in beautiful soup should I be focusing on?
A:
Keep reading.
http://www.crummy.com/software/BeautifulSoup/documentation.html#Iterating%20over%20a%20Tag
http://www.crummy.com/software/BeautifulSoup/documentation.html#nextSibling%20and%20previousSibling
| with beautifulsoup, how to reference the first table after a given form | I want to drill down into my html, specifically I want to get the first html table that is AFTER a form that looks like:
<form method="POST" action="/parts.html">
..
<table ...>
...
</table>
..
</form>
So this table has <tr> for each product.
My utlimate goal here is to loop through each tablerow, and then I need to extract the product name, price, image url, etc.
What should my strategy be, and what methods in beautiful soup should I be focusing on?
| [
"Keep reading. \nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#Iterating%20over%20a%20Tag\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#nextSibling%20and%20previousSibling\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003340329_beautifulsoup_python.txt |
Q:
Is it possible to have python open a terminal and write to it?
For example, if I have this code:
subprocess.call(['gnome-terminal'])
Is it possible to have python output strings to that specific terminal that was just opened? Thanks!
A:
Possibly, but it is easier to have a custom process running in the subordinate terminal. For example, given sserv.py from the example server in the documentation the command:
gnome-terminal -e "python ./sserv.py"
will happily chat on port 9999 with you. Given a more complex sserv.py it could do anything you want (anything terminalish, that is).
A:
I think that PExpect might do this for you:
Pexpect is basically a pattern
matching system. It runs programs and
watches output. When output matches a
given pattern Pexpect can respond as
if a human were typing responses.
Pexpect can be used for automation,
testing, and screen scraping. Pexpect
can be used for automating interactive
console applications such as ssh, ftp,
passwd, telnet, etc. It can also be
used to control web applications via
lynx, w3m, or some other
text-based web browser. Pexpect is
pure Python. Unlike other Expect-like
modules for Python Pexpect does not
require TCL or Expect nor does it
require C extensions to be compiled.
It should work on any platform that
supports the standard Python pty
module.
| Is it possible to have python open a terminal and write to it? | For example, if I have this code:
subprocess.call(['gnome-terminal'])
Is it possible to have python output strings to that specific terminal that was just opened? Thanks!
| [
"Possibly, but it is easier to have a custom process running in the subordinate terminal. For example, given sserv.py from the example server in the documentation the command:\n gnome-terminal -e \"python ./sserv.py\"\n\nwill happily chat on port 9999 with you. Given a more complex sserv.py it could do anything you... | [
3,
2
] | [] | [] | [
"gnome_terminal",
"linux",
"python"
] | stackoverflow_0003340341_gnome_terminal_linux_python.txt |
Q:
Python3.0 TypeError
Usually one comes across this problem in python3.0 while attempting a split() method on a bytes type object.
TypeError: Type str does'nt support the buffer API
This issue can be resolved by using the split method after decoding the bytes type object.
However, I find the error message rather ambiguous. Am I missing some underlying concept or do you think the message is ambiguous too?(If more people think so, maybe we could ask for a fix)
A:
Just forget the existence of totally-obsolete, zero-reasons-to-keep-it-around 3.0, upgrade to 3.1 instead, and splitting bytes is just fine:
>>> x = bytes(b'ciao bella')
>>> x.split()
[b'ciao', b'bella']
| Python3.0 TypeError | Usually one comes across this problem in python3.0 while attempting a split() method on a bytes type object.
TypeError: Type str does'nt support the buffer API
This issue can be resolved by using the split method after decoding the bytes type object.
However, I find the error message rather ambiguous. Am I missing some underlying concept or do you think the message is ambiguous too?(If more people think so, maybe we could ask for a fix)
| [
"Just forget the existence of totally-obsolete, zero-reasons-to-keep-it-around 3.0, upgrade to 3.1 instead, and splitting bytes is just fine:\n>>> x = bytes(b'ciao bella')\n>>> x.split()\n[b'ciao', b'bella']\n\n"
] | [
9
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003340712_python_python_3.x.txt |
Q:
GUI's Over Running Programs in python
Just wondering if there is any kind of framework or method of making a Gui that will override (Stay on top of) all other windows in python. Including Games or other programs that seem to "Take over" the computers Graphical processes. Any point in the right direction would be much appreciated...
PS. The OS in question is Windows 7, but a cross platform solution would be appreciated.
A:
You need the SetWindowPos function from the Win32 API. Something like the following should work (see the API link for more details):
import win32gui, win32con
hwnd = get_my_window_handle()
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
A:
For a cross-platform solution, you could use wxPython with a wxSTAY_ON_TOP style bit in a main window. I believe that this will give you the behavior you desire on Mac and Unix GUIs as well as Microsoft Windows ones.
| GUI's Over Running Programs in python | Just wondering if there is any kind of framework or method of making a Gui that will override (Stay on top of) all other windows in python. Including Games or other programs that seem to "Take over" the computers Graphical processes. Any point in the right direction would be much appreciated...
PS. The OS in question is Windows 7, but a cross platform solution would be appreciated.
| [
"You need the SetWindowPos function from the Win32 API. Something like the following should work (see the API link for more details):\nimport win32gui, win32con\n\nhwnd = get_my_window_handle()\nwin32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)\n\n",
"For a... | [
0,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003340639_python_user_interface.txt |
Q:
saving data and calling data python
say i want to ask the many users to give me their ID number and their name, than save it.
and than i can call any ID and get the name. can someone tell me how i can do that by making a class and using the _ _ init _ _ method?
A:
The "asking" part, as @Zonda's answer says, could use raw_input (or Python 3's input) at a terminal ("command window" in Windows); but it could also use a web application, or a GUI application -- you don't really tell us enough about where the users will be (on the same machine you're using to run your code, or at a browser while your code runs on a server?) and whether GUI or textual interfaces are preferred, so it's impossible to give more precise advice.
For storing and retrieving the data, a SQL engine as mentioned in @aaron's answer is a possibility (though some might consider it overkill if this is all you want to save), but his suggested alternative of using pickle directly makes little sense -- I would instead recommend the shelf module, which offers (just about) the equivalent of a dictionary persisted to disk. (Keys, however, can only be strings -- but even if your IDs are integers instead, that's no problem, just use str(someid) as the key both to store and to retrieve).
In a truly weird comment I see you ask...:
is there any way to do it by making a
class? and using the __init__
method?
Of course there is a way to do "in a class, using the __init__ method" most anything you can do in a function -- at worst, you write all the code that would (in a sensible program) be in the function, in the __init__ method instead (in lieu of return, you stash the result in self.result and then get the .result attribute of the weirdly useless instance you have thus created).
But it makes any sense to use a class only when you need special methods, or want to associate state and behavior, and you don't at all explain why either condition should apply here, which is why I call your request "weird" -- you provide absolutely no context to explain why you would at all want that in lieu of functions.
If you can clarify your motivations (ideally by editing your question, or, even better, asking a separate one, but not by extending your question in sundry comments!-) maybe it's possible to help you further.
A:
To get data from a user, use this code (python 3).
ID = input("Enter your id: ")
In python 2, replace input with raw_input.
The same should can be done to get the users name.
This will save it to a variable, which can be used later in the program. If you want to save it to a file, use the following code:
w = open('\path\to\file.txt', 'w')
w.write(ID, age)
w.close()
A:
if you're not concerned with security, you can use the pickle module to pickle a dictionary.
import pickle
data = {}
# whatever you do to collect the data
data[id] = name
pickle.dump(data, filename)
new_data = pickle.load(filename)
new_name = new_data[id]
#new_name == name
otherwise use the sqlite3 module
import sqlite3
conn = sqlite3.connect(filename)
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS names (id INTEGER, name TEXT)')
#do whatever you do to get the data
cur.execute('INSERT INTO names VALUES (?,?)', (id, name))
#to get the name later by id you would do...
cur.execute('SELECT name FROM names WHERE id = ?', (id, ))
name = cur.fetchone()[0]
| saving data and calling data python | say i want to ask the many users to give me their ID number and their name, than save it.
and than i can call any ID and get the name. can someone tell me how i can do that by making a class and using the _ _ init _ _ method?
| [
"The \"asking\" part, as @Zonda's answer says, could use raw_input (or Python 3's input) at a terminal (\"command window\" in Windows); but it could also use a web application, or a GUI application -- you don't really tell us enough about where the users will be (on the same machine you're using to run your code, o... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003340803_python.txt |
Q:
How can I upgrade the sqlite3 package in Python 2.6?
I was using Python 2.6.5 to build my application, which came with sqlite3 3.5.9. Apparently though, as I found out in another question of mine, foreign key support wasn't introduced in sqlite3 until version 3.6.19. However, Python 2.7 comes with sqlite3 3.6.21, so this work -- I decided I wanted to use foreign keys in my application, so I tried upgrading to python 2.7.
I'm using twisted, and I couldn't for the life of me get it to build. Twisted relies on zope.interface and I can't find zope.interface for python 2.7 -- I thought it might just "work" anyway, but I'd have to just copy all the files over myself, and get everything working myself, rather than just using the self-installing packages.
So I thought it might be wiser to just re-build python 2.6 and link it against a new version of sqlite3. But I don't know how--
How would I do this?
I have Visual Studio 2008 installed as a compiler, I read that that is the only one that is really supported for Windows, and I am running a 64 bit operating system
A:
download the latest version of sqlite3.dll from sqlite website and replace the the sqlite3.dll in the python dir.
A:
sqlite3 is not a built-in module; it's an extension module (the binary is C:\Python26\DLLs_sqlite3.pyd (on my machine)). A pyd is a DLL with a different filename extension and only 1 entry point. There's also a sqlite3.dll, which contains the SQLite code. python.exe is not linked against either of those, and thus rebuilding python.exe has no point.
The next idea is to go to the pysqlite2 download site, and get the latest Windows installer for Python 2.6. Unfortunately there's no docs about which version of SQLite it contains; one needs to install it and then muck about:
>>> import sqlite3 as standard
>>> from pysqlite2 import dbapi2 as latest
>>> for m in (standard, latest):
... print m.sqlite_version
...
3.5.9
3.6.2
>>>
So, it contains only SQLite version 3.6.2, which doesn't have the real foreign key support that you want.
I suggest that you check the mailing list to see if your question is answered there, and if not ask about the possibility of a Python 2.6 installer containing a later SQLite (e.g. the one included with Python 2.7).
A:
I decided I'd just give this a shot when I realized that every library I've ever installed in python 2.6 resided in my site-packages folder. I just... copied site-packages to my 2.7 installation, and it works so far. This is by far the easiest route for me if this works -- I'll look further into it but at least I can continue to develop now.
I won't accept this answer, because it doesn't even answer my question, but it does solve my problem, as far as I can tell so far.
| How can I upgrade the sqlite3 package in Python 2.6? | I was using Python 2.6.5 to build my application, which came with sqlite3 3.5.9. Apparently though, as I found out in another question of mine, foreign key support wasn't introduced in sqlite3 until version 3.6.19. However, Python 2.7 comes with sqlite3 3.6.21, so this work -- I decided I wanted to use foreign keys in my application, so I tried upgrading to python 2.7.
I'm using twisted, and I couldn't for the life of me get it to build. Twisted relies on zope.interface and I can't find zope.interface for python 2.7 -- I thought it might just "work" anyway, but I'd have to just copy all the files over myself, and get everything working myself, rather than just using the self-installing packages.
So I thought it might be wiser to just re-build python 2.6 and link it against a new version of sqlite3. But I don't know how--
How would I do this?
I have Visual Studio 2008 installed as a compiler, I read that that is the only one that is really supported for Windows, and I am running a 64 bit operating system
| [
"download the latest version of sqlite3.dll from sqlite website and replace the the sqlite3.dll in the python dir.\n",
"sqlite3 is not a built-in module; it's an extension module (the binary is C:\\Python26\\DLLs_sqlite3.pyd (on my machine)). A pyd is a DLL with a different filename extension and only 1 entry poi... | [
6,
3,
1
] | [] | [] | [
"build",
"linker",
"python",
"sqlite"
] | stackoverflow_0003333095_build_linker_python_sqlite.txt |
Q:
Filtering in Python/Django based on date, ignoring time
I'd like to filter objects to the day with datetime, but can't find examples on how to do this anywhere.
This, for example, works perfectly in pulling together all following events:
@login_required
def invoice_picker(request):
"""Grab a date from the URL and show all the invoicable deliveries for that day."""
query = request.GET.get('q' , '2/9/1984')
date = datetime
date = datetime.strptime('7/14/2010', '%m/%d/%Y')
date = date.strptime(query, '%m/%d/%Y')
results = []
if query:
results = LaundryDelivery.objects.filter(end__gte=date)
return render_to_response('invoicer.html', {
'results' : results,
'date' : date,
'user' : request.user,
})
But when I remove __gte, it returns nothing because the dates are along the lines of 2010-06-22 04:04:00 instead of 2010-06-22 00:00:00. I also tried:
results = LaundryDelivery.objects.filter(end.date=date)
but unfortunately I get the error "keyword can't be an expression". Any ideas?
A:
I don't think there's a good way to compare datetimes with dates. One way is the following:
filter(end__year=date.year, end__month=date.month, end__day=date.day)
The other is to use the range lookup with the min time and max time for the day.
| Filtering in Python/Django based on date, ignoring time | I'd like to filter objects to the day with datetime, but can't find examples on how to do this anywhere.
This, for example, works perfectly in pulling together all following events:
@login_required
def invoice_picker(request):
"""Grab a date from the URL and show all the invoicable deliveries for that day."""
query = request.GET.get('q' , '2/9/1984')
date = datetime
date = datetime.strptime('7/14/2010', '%m/%d/%Y')
date = date.strptime(query, '%m/%d/%Y')
results = []
if query:
results = LaundryDelivery.objects.filter(end__gte=date)
return render_to_response('invoicer.html', {
'results' : results,
'date' : date,
'user' : request.user,
})
But when I remove __gte, it returns nothing because the dates are along the lines of 2010-06-22 04:04:00 instead of 2010-06-22 00:00:00. I also tried:
results = LaundryDelivery.objects.filter(end.date=date)
but unfortunately I get the error "keyword can't be an expression". Any ideas?
| [
"I don't think there's a good way to compare datetimes with dates. One way is the following:\nfilter(end__year=date.year, end__month=date.month, end__day=date.day)\n\nThe other is to use the range lookup with the min time and max time for the day.\n"
] | [
8
] | [] | [] | [
"datetime_format",
"django",
"python"
] | stackoverflow_0003341120_datetime_format_django_python.txt |
Q:
Is there Python Clang wrapper in the vein of pygccxml which wraps GCC-XML?
For a long time now I've been using pygccxml to parse and introspect my C++ source code: it helps me to do some clever code-generation during our build process.
Recently I've read a lot about the benefits of the LLVM stack, and especially the benefits that the LLVM Clang parser brings to C++ compilation. I am now wondering if there is any Python interface to Clang such that I could use it as the basis for some of my existing code generation tasks?
A:
After further digging I found that in the LLVM 2.7 release there could be the beginings of something useful:
In the LLVM 2.7 time-frame, the Clang team has made many improvements....
CIndex API and Python bindings: Clang now includes a C API as part of the CIndex library. Although we make make some changes to the API in the future, it is intended to be stable and has been designed for use by external projects. See the Clang doxygen CIndex documentation for more details. The CIndex API also includings an preliminary set of Python bindings.
I'm not sure how useful this is in practice, certainly it looks like it could be the foundation for building a pygccxml equivalent based on LLVM but it is not in itself such a library.
| Is there Python Clang wrapper in the vein of pygccxml which wraps GCC-XML? | For a long time now I've been using pygccxml to parse and introspect my C++ source code: it helps me to do some clever code-generation during our build process.
Recently I've read a lot about the benefits of the LLVM stack, and especially the benefits that the LLVM Clang parser brings to C++ compilation. I am now wondering if there is any Python interface to Clang such that I could use it as the basis for some of my existing code generation tasks?
| [
"After further digging I found that in the LLVM 2.7 release there could be the beginings of something useful:\n\nIn the LLVM 2.7 time-frame, the Clang team has made many improvements....\nCIndex API and Python bindings: Clang now includes a C API as part of the CIndex library. Although we make make some changes to ... | [
5
] | [] | [] | [
"c++",
"clang",
"code_generation",
"llvm",
"python"
] | stackoverflow_0003334170_c++_clang_code_generation_llvm_python.txt |
Q:
Python OpenGL module - can't render basic triangle
I'm trying to use the OpenGL module with Python.
Here is my source:
pygame.init()
screen = pygame.display.set_mode((800, 600), HWSURFACE|OPENGL|DOUBLEBUF)
def init():
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_FLAT)
glClearColor(1.0, 1.0, 1.0, 0.0)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0))
def draw():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glColor3fv((25, 123, 180))
glBegin(GL_TRIANGLES)
glVertex3f( 0.0, 10.0, 0.0)
glVertex3f(-10.0,-10.0, 0.0)
glVertex3f( 10.0,-10.0, 0.0)
glEnd()
def run():
init()
while True:
draw()
pygame.display.flip()
run()
Can anyone see what is wrong? I'm just trying to draw a simple 3 pointed vertex, yet nothing shows up on the screen. Occasionally I get a bright pink screen. I'm confident it's a basic error.
A:
You need to setup view and projection matrices.
http://www.opengl.org/resources/faq/technical/transformations.htm#tran0090
| Python OpenGL module - can't render basic triangle | I'm trying to use the OpenGL module with Python.
Here is my source:
pygame.init()
screen = pygame.display.set_mode((800, 600), HWSURFACE|OPENGL|DOUBLEBUF)
def init():
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_FLAT)
glClearColor(1.0, 1.0, 1.0, 0.0)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0))
def draw():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glColor3fv((25, 123, 180))
glBegin(GL_TRIANGLES)
glVertex3f( 0.0, 10.0, 0.0)
glVertex3f(-10.0,-10.0, 0.0)
glVertex3f( 10.0,-10.0, 0.0)
glEnd()
def run():
init()
while True:
draw()
pygame.display.flip()
run()
Can anyone see what is wrong? I'm just trying to draw a simple 3 pointed vertex, yet nothing shows up on the screen. Occasionally I get a bright pink screen. I'm confident it's a basic error.
| [
"You need to setup view and projection matrices.\nhttp://www.opengl.org/resources/faq/technical/transformations.htm#tran0090\n"
] | [
1
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0003340732_opengl_python.txt |
Q:
How to set fixed depth levels in DOT graphs
I'm creating a DOT graph visualization from a tree-like data structure but am having difficulties setting fixed level depths based upon data type. For example, if I had 4 nodes in a tree and A denotes a specific data type and B represents another it would like Graph_1:
ROOT
/ \
A[0] B[1]
/
B[0]
as opposed to Graph_2:
ROOT
/ \
A[0] \
/ \
B[0] B[1]
Graph_2 is what I would like to end up with.
The fixed levels are what I'm looking for. How can I achieve this? I can easily identify what data type I'm adding to the graph, but am having trouble on how to tag nodes to achieve this. Can this be done using subgraphs?
FYI, this is my first time playing with DOT.
A:
Yes, subgraphs will work.
digraph {
subgraph { rank = same; A0 };
subgraph { rank = same; B0; B1 };
root -> A0;
A0 -> B0;
root -> B1;
}
results in
(source: brool.com)
| How to set fixed depth levels in DOT graphs | I'm creating a DOT graph visualization from a tree-like data structure but am having difficulties setting fixed level depths based upon data type. For example, if I had 4 nodes in a tree and A denotes a specific data type and B represents another it would like Graph_1:
ROOT
/ \
A[0] B[1]
/
B[0]
as opposed to Graph_2:
ROOT
/ \
A[0] \
/ \
B[0] B[1]
Graph_2 is what I would like to end up with.
The fixed levels are what I'm looking for. How can I achieve this? I can easily identify what data type I'm adding to the graph, but am having trouble on how to tag nodes to achieve this. Can this be done using subgraphs?
FYI, this is my first time playing with DOT.
| [
"Yes, subgraphs will work.\ndigraph {\n subgraph { rank = same; A0 };\n subgraph { rank = same; B0; B1 };\n root -> A0;\n A0 -> B0;\n root -> B1;\n}\n\nresults in\n\n(source: brool.com) \n"
] | [
4
] | [] | [] | [
"dot",
"graphviz",
"macos",
"python"
] | stackoverflow_0003322827_dot_graphviz_macos_python.txt |
Q:
CPython vs. Jython vs. IronPython for cross-platform GUI development
I'm thinking of making some kind of experimental IDE for digital hardware design. So I can't decide witch platform to choose.
I'm going to have text-editor with syntax highlighting, some vector graphics and lots of tabbed windows.
My goals:
1. to make GUI using as less custom components as possible.
2. to make it as cross-platform as possible
(I know already that CPython and Jython are cross-platform-friendly, but what about IronPython+Mono?)
So - the question is about GUI - what should I choose?
A:
IronPython with Mono is cross platform - to whatever platforms supported by Mono, and for the feature set supported by Mono (which pretty much means Windows Forms is supported fairly well). Other options for GUI toolkits are available, however, which may provide better "cross platform" capabilities, or at least a better feel on non-Windows platforms.
CPython will depend on the GUI suite you choose. Personally, I've found CPython with PyQt to be the most usable, cross platform GUI option from Python. It's very powerful, feature-rich, and works quite well.
Jython will work, but I personally don't like the GUI options as much (this is a 100% personal preference, however).
A:
I'd say that if cross-platform is a goal, forget IronPython. A lot of people hate the dependency hell it causes so it'll be too much work to get it up in running in some OSes/distributions. Jython will suffer this also, albeit to a lesser degree.
A:
Well, Mono does not come with the base of most Linux distributions. It's not a terribly lightweight dependency either, and I think Java is considerably more likely for people to already have. Would you plan on using "Winforms" with Mono? If so, and you don't have experience with Winforms, read about what others have to say :-) The other .NET GUI toolkit is WPF, which unfortunately Mono has no plans to implement.
Jython would be better too, because you can use SWT, which renders native widgets and provides lots of layout possibilities easily. Or you can use Jython with Swing, or whatever else -- even AWT if you love ugliness.
I really like wxPython (which you can use with CPython, which is on most distros by default), because it renders good-looking native widgets in OSX, Windows and Linux (I've only seen the Gnome widgets in person). wxPython is by far the easiest to use GUI toolkit I've used -- even programatically (i.e. layout without Glade or similar). I've also used SWT, which I found quite nice, and Swing, which I personally don't really like the looks of, and Winforms, which was a nightmare to try to do even simple layouts with.
Here's a quick comparison of the existence of the interpreter/language runtime by OS
CPython
Windows - Probably not installed, and you'd have to make a non-python installer install it with your software :-P
Linux - Probably installed (Ubuntu, Gentoo and RedHat all have system tools that are written in Python and run on CPython)
Mac - Preinstalled on OSX
Jython
Windows - Probably installed at some point in my experience, though it doesn't come with
Linux - Probably installed, but more importantly nobody would hate you for depending on it like Mono
Mac - Preinstalled on OSX ("Mac OS X Leopard comes with J2SE 5.0 preinstalled, based on JDK 1.5.0_13_b05" -- Apple's site)
IronPython
Windows - Will probably run fine because I bet most people have at the very least .NET 2.0 if they have a recent version of Windows
Linux - Probably not installed -- the only application with which I've used Mono on Linux was Rasterbator, which worked well but I felt weird putting .NET on Linux
Mac - See above
I would choose a GUI toolkit first, since that will very much impact the user experience and overall difficulty (I would choose wxPython but SWT would be a close second) then consider the above as well maybe as a tiebreaker.
A:
I faced this same question roughly a year ago. After looking at all the alternatives, I ended up with CPython and PyQt. IMO, Qt/PyQt is by far the best choice amongst all of the Python GUI toolkits. After hitting many bugs in wxPython I switched to PyQt and never looked back. Qt/PyQt are much more solid than the wx toolkits in my experience.
I use the exact same code base and build stand alone executables with PyInstaller for Windows and Py2App for the Mac (PyInstaller can be used for Linux as well). Because these builders embed the Python interpreter and all of the dependencies, it takes a lot of the hassle away. The only rub is that you'll need both a Windows and Mac to do the builds. Getting all of the configurations correct can be a pain too, but it's possible and time worth investing.
A:
Take a look at comparable GUI's written in python/jython/ironpython. Look for programs that you like and find out what they use. I guess most if not all will be written in cpython + gtk or cpython + qt. I think all gui toolkits in python are cross platform.
A:
Java is the most portable platform. Jython is written in 100% pure Java. 'Nuff said.
BTW I just switched a CPython/GTK project to Jython (trying to remove as much unmanaged code as possible), the only problem is that Jython is at 2.5 still, which kind of sucks when you're used to 2.6/2.7/3 :)
A:
There are plenty of answers already, but I'd like to add one important thing - regardless of which library you learn, most of the principles will be the same when you move to another library.
I don't know about Qt, but for most graphics programs (in PyGTK or Tkinter) the best thing to do, as far as editing goes, is to use a PIL image (or something similar) to draw on and then draw that image on your canvas widget, otherwise you can lose pixel data if your window gets covered.
A:
You may use Python 2.7 or 3.1 (CPython) with ttk (in Standart Library in 2.7, 3.1), ttk support themes (looks nice and very simple coding)
(1-st screen is text-editor with tabs and syntax highlighting) ttk screenshots
| CPython vs. Jython vs. IronPython for cross-platform GUI development | I'm thinking of making some kind of experimental IDE for digital hardware design. So I can't decide witch platform to choose.
I'm going to have text-editor with syntax highlighting, some vector graphics and lots of tabbed windows.
My goals:
1. to make GUI using as less custom components as possible.
2. to make it as cross-platform as possible
(I know already that CPython and Jython are cross-platform-friendly, but what about IronPython+Mono?)
So - the question is about GUI - what should I choose?
| [
"IronPython with Mono is cross platform - to whatever platforms supported by Mono, and for the feature set supported by Mono (which pretty much means Windows Forms is supported fairly well). Other options for GUI toolkits are available, however, which may provide better \"cross platform\" capabilities, or at least... | [
9,
5,
5,
3,
2,
2,
1,
1
] | [] | [] | [
"cpython",
"ironpython",
"jython",
"python",
"user_interface"
] | stackoverflow_0003337725_cpython_ironpython_jython_python_user_interface.txt |
Q:
Python/Web: What's the best way to run Python on a web server?
I am leasing a dedicated web server.
I have a Python web-application.
Which configuration option (CGI, FCGI, mod_python, Passenger, etc) would result in Python being served the fastest on my web server and how do I set it up that way?
UPDATE:
Note, I'm not using a Python framework such as Django or Pylons.
A:
I usually go the Apache + mod_wsgi route. It is pretty easy to set up.
To answer your question about speed, I pulled this from the provided link:
The mod_wsgi module is written in C code directly against the internal Apache and Python application programming interfaces. As such, for hosting WSGI applications in conjunction with Apache it has a lower memory overhead and performs better than existing WSGI adapters for mod_python or alternative FASTCGI/SCGI/CGI or proxy based solutions.
A:
Don't get carried away with trying to work out what is the fastest web server. All you will do in doing that is waste your time. This is because the web server is nearly never the bottleneck if you set them up properly. The real bottleneck is your web application, database access etc.
As such, choose whatever web hosting system you think meets your general requirements and which you find easy to setup and manage. Using something you understand and which doesn't require lots of time devoted to it, means you can then focus your valuable time on making your application perform better, thus reducing the real bottleneck.
A:
You may use pure python wsgi server (see benchmark) with microframework (like Bottle, Flask)
A:
Use Apache + mod_python. It's usually the easiest way and it performs very well.
Edit: additionally, as it turns out, it is also considered a dead project. So that might factor into your decision. That said, mod_wsgi is the preferred alternative.
A:
Tornado is an impressive high performance Python web server. It has it's own framework, but the speed/page load statistics are all the buzz right now.
Apache2 and WSGI is my other suggestion.
| Python/Web: What's the best way to run Python on a web server? | I am leasing a dedicated web server.
I have a Python web-application.
Which configuration option (CGI, FCGI, mod_python, Passenger, etc) would result in Python being served the fastest on my web server and how do I set it up that way?
UPDATE:
Note, I'm not using a Python framework such as Django or Pylons.
| [
"I usually go the Apache + mod_wsgi route. It is pretty easy to set up.\nTo answer your question about speed, I pulled this from the provided link:\n\nThe mod_wsgi module is written in C code directly against the internal Apache and Python application programming interfaces. As such, for hosting WSGI applications i... | [
8,
4,
1,
0,
0
] | [
"You don't usually just serve Python, you serve a specific web server or framework based on Python. eg. Zope, TurboGears, Django, Pylons, etc. Although they tend to be able to operate on different web server back-ends (and some provide an internal web server themselves), the best solution will depend on which one y... | [
-1
] | [
"mod_wsgi",
"python",
"webserver"
] | stackoverflow_0003336787_mod_wsgi_python_webserver.txt |
Q:
How to call a static methods on a django model class during a south migration
I'm writing a data migration in south to fix some denormalized data I screwed up in earlier code. The way to figure out the right value for the incorrect field is to call a static method on the django model class. The code looks like this:
class Account(models.Model):
name = models.CharField()
@staticmethod
def lookup_by_name(name):
# There's actually more to it than this
return Account.objects.get(name=name)
class Record(models.Model):
account_name = models.CharField()
acct = models.ForeignKey('Account')
...
class Migration(DataMigration):
def forwards(self, orm):
# Fixing Records with the wrong FK to Account
for record in orm.Record.objects.all():
record.acct = orm.Account.lookup_by_name(record.account_name)
record.save()
But this fails with
AttributeError: type object 'Account' has no attribute 'lookup_by_name'
I'm guessing south just doesn't support @staticmethods on model classes?
Trying to import Account directly fails, unless I also import Record directly and completely ignore the ORM object. Is that a safe option, since it's a data migration and the schema isn't changing? Or should I just run this fix by hand rather than in the context of a south migration.
A:
You can't use methods from models.py in south migrations. The reason is that in the future models.py will evolve and sooner or later you will delete those methods, then migration will be broken.
You should put all code needed by migration in migration file itself.
A:
Here's the pertinent section of the South docs explaining why your methods don't work:
Rationale behind the serialisation
A:
Aren't you using different names lookup_by_name and lookup_name?
| How to call a static methods on a django model class during a south migration | I'm writing a data migration in south to fix some denormalized data I screwed up in earlier code. The way to figure out the right value for the incorrect field is to call a static method on the django model class. The code looks like this:
class Account(models.Model):
name = models.CharField()
@staticmethod
def lookup_by_name(name):
# There's actually more to it than this
return Account.objects.get(name=name)
class Record(models.Model):
account_name = models.CharField()
acct = models.ForeignKey('Account')
...
class Migration(DataMigration):
def forwards(self, orm):
# Fixing Records with the wrong FK to Account
for record in orm.Record.objects.all():
record.acct = orm.Account.lookup_by_name(record.account_name)
record.save()
But this fails with
AttributeError: type object 'Account' has no attribute 'lookup_by_name'
I'm guessing south just doesn't support @staticmethods on model classes?
Trying to import Account directly fails, unless I also import Record directly and completely ignore the ORM object. Is that a safe option, since it's a data migration and the schema isn't changing? Or should I just run this fix by hand rather than in the context of a south migration.
| [
"You can't use methods from models.py in south migrations. The reason is that in the future models.py will evolve and sooner or later you will delete those methods, then migration will be broken.\nYou should put all code needed by migration in migration file itself.\n",
"Here's the pertinent section of the South ... | [
43,
7,
1
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0003314173_django_django_south_python.txt |
Q:
python FLV checker
i need a simple python lib that check the uploaded files to my webserver are flash media (FLV), by reading the flv header (metadata) and not the mimetype extension.
A:
Kaa is simple to use and quite powerful as well.
Right away:
>>> import kaa.metadata
>>> info = kaa.metadata.parse('tlib_allie_jordan-sd169.wmv')
>>> print info
| type: asf format
| media: MEDIA_AV
| mime: video/x-ms-asf
| length: 1871.166
+-- Video Track #1
| | media: MEDIA_VIDEO
| | codec: Windows Media Video V8
| | width: 768
| | height: 432
| | fourcc: WMV2
| | id: 1
+-- Audio Track #1
| | media: MEDIA_AUDIO
| | channels: 2
| | samplerate: 48000
| | codec: Windows Media Audio V7 / V8 / V9
| | samplebits: 16
| | bitrate: 64000
| | fourcc: 0x161
| | id: 2
See what Kaa can support. Support includes FLV.
| python FLV checker | i need a simple python lib that check the uploaded files to my webserver are flash media (FLV), by reading the flv header (metadata) and not the mimetype extension.
| [
"Kaa is simple to use and quite powerful as well.\nRight away:\n>>> import kaa.metadata\n>>> info = kaa.metadata.parse('tlib_allie_jordan-sd169.wmv')\n>>> print info\n| type: asf format\n| media: MEDIA_AV\n| mime: video/x-ms-asf\n| length: 1871.166\n+-- Video Track #1\n| | media: MEDIA_... | [
5
] | [] | [] | [
"flash",
"flv",
"metadata",
"python"
] | stackoverflow_0003341461_flash_flv_metadata_python.txt |
Q:
Extract a specific portion of connection string
Any way to extract what's after the @(if any) and before the next . (if any)?
Examples:
host
host.domain.com
user@host
first.last@host
first.last@host.domain.com
first@host.domain.com
I need to get host in a variable.
Suggestions in Python? Any method is welcomed.
Thanks,
EDIT: I fixed my question. Need to match host and host.blah.blah too.
A:
You can use a couple of string.split calls, the first using '@' as a separator, the second using '.'
A:
do a split by '@', and then substring.
A:
>>> x = "first.last@host.domain.com"
>>> x.split("@")[1].split(".")[0]
'host'
>>> y = "first.last@host"
>>> y.split("@")[1].split(".")[0]
'host'
>>>
There will be an IndexError Exception thrown if there is no @ in the string.
A:
'first.last@host.domain.com'.split('@')[1].split('.')[0]
A:
host = re.search(r"@(\w+)(\.|$)", s).group(1)
A:
Here is one more solution:
re.search("^.*@([^.]*).*", str).group(1)
edit:
Much better solution thanks to the comment:
re.search("@([^.]*)[.]?", str).group(1)
A:
>>> s="first.last@host.domain.com"
>>> s[s.index("@")+1:]
'host.domain.com'
>>> s[s.index("@")+1:].split(".")[0]
'host'
A:
import re
hosts = """
user@host1
first.last@host2
first.last@host3.domain.com
first@host4.domain.com
"""
print re.findall(r"@(\w+)", hosts)
returns:
['host1', 'host2', 'host3', 'host4']
| Extract a specific portion of connection string | Any way to extract what's after the @(if any) and before the next . (if any)?
Examples:
host
host.domain.com
user@host
first.last@host
first.last@host.domain.com
first@host.domain.com
I need to get host in a variable.
Suggestions in Python? Any method is welcomed.
Thanks,
EDIT: I fixed my question. Need to match host and host.blah.blah too.
| [
"You can use a couple of string.split calls, the first using '@' as a separator, the second using '.'\n",
"do a split by '@', and then substring.\n",
">>> x = \"first.last@host.domain.com\"\n>>> x.split(\"@\")[1].split(\".\")[0]\n'host'\n>>> y = \"first.last@host\"\n>>> y.split(\"@\")[1].split(\".\")[0]\n'host'... | [
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"connection_string",
"python",
"regex",
"string"
] | stackoverflow_0003341557_connection_string_python_regex_string.txt |
Q:
Python SESSION (like php) class
is there any class to handle a SESSION (like php) in Python? not in django, but I want to use it with PyQt
thank you
A:
The short answer is that there is no $SESSION variable in Python.
Python tends not to put things in global scope like PHP. Therefore, if you are accessing a user's session id, it will probably be accessed via dot notation module_name.ClassName.session. If you would like to create a PyQt app that acts as a webserver, you could probably adapt a web framework's implementation.
Others' responses to similar queries suggest implementing sessions via a simple database[1]. You could try assigning unique ids with uuid, and storing them with tools like sqlite3 or pickle.
[1] http://ubuntuforums.org/showthread.php?t=859645
A:
Theres a session class with mod_python for apache, that can be a good starting point for making our own class. The class is not very dependent on apache to work.
http://www.modpython.org/
| Python SESSION (like php) class | is there any class to handle a SESSION (like php) in Python? not in django, but I want to use it with PyQt
thank you
| [
"The short answer is that there is no $SESSION variable in Python.\nPython tends not to put things in global scope like PHP. Therefore, if you are accessing a user's session id, it will probably be accessed via dot notation module_name.ClassName.session. If you would like to create a PyQt app that acts as a webserv... | [
2,
0
] | [] | [] | [
"class",
"pyqt",
"python",
"session"
] | stackoverflow_0003341298_class_pyqt_python_session.txt |
Q:
how to upload python application with google apps?
I developed one application and upload on example.appspot.com
now i want to upload it on www.example.com
what to do???
pls reply fast..
A:
Actually, your application has to be hosted by GAE, but you can set a domain for it.
| how to upload python application with google apps? | I developed one application and upload on example.appspot.com
now i want to upload it on www.example.com
what to do???
pls reply fast..
| [
"Actually, your application has to be hosted by GAE, but you can set a domain for it.\n"
] | [
3
] | [] | [] | [
"dns",
"google_app_engine",
"python",
"upload",
"web"
] | stackoverflow_0003341899_dns_google_app_engine_python_upload_web.txt |
Q:
Installing PIL on Snow Leopard -- NOTHING WORKS
I'm trying to install PIL on Snow Leopard, using Python 2.6.1, GCC 4.2.1, PIL 1.1.7, and have tried with both libjpeg6b and libjpeg7 -- nothing works. I've cleared out every trace of libjpeg/pil/zlib from fink, tried various compiler options, etc. and used http://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/ and http:// www.brambraakman.com/blog/comments/installing_pil_in_snow_leopard_jpeg_resync_to_restart_error/ (not a link because StOv only lets me post one...)
4 bits of potentially useful information:
OTOOL does not show libjpeg as a dependency
otool -L /Library/Python/2.6/site-packages/PIL/_imaging.so
/Library/Python/2.6/site-packages/PIL/_imaging.so:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
I get these weird compiler messages
i686-apple-darwin10-gcc-4.2.1: -framework: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: Tcl: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: -framework: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: Tk: linker input file unused because linking not done
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe -I/System/Library/Frameworks/Tcl.framework/Headers -I/System/Library/Frameworks/Tk.framework/Headers -IlibImaging -I/sw/include/freetype2 -I/sw/include -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c Tk/tkImaging.c -o build/temp.macosx-10.6-universal-2.6/Tk/tkImaging.o -framework Tcl -framework Tk
In file included from /System/Library/Frameworks/Tk.framework/Headers/tk.h:78,
from Tk/tkImaging.c:51:
selftest.py fails because of _imagingmath (after I used the second link given above, before it too failed due to _imaging)
Themistocles:Imaging-1.1.7 me$ python selftest.py
Traceback (most recent call last):
File "selftest.py", line 11, in <module>
from PIL import ImageMath
File "./PIL/ImageMath.py", line 19, in <module>
import _imagingmath
ImportError: No module named _imagingmath
Anything but selftest.py fails because of _imaging
>>> import _imaging
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.6/site-packages/PIL/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart
Referenced from: /Library/Python/2.6/site-packages/PIL/_imaging.so
Expected in: flat namespace
in /Library/Python/2.6/site-packages/PIL/_imaging.so
Please, please help! This is getting ridiculous. I'd even be happy to be able to compile PIL sans jpeg support at this point!
A:
I recently wrote an article on how to get PIL, django, libjpeg to work nicely alongside Snow Leopard
http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/
I'll copy it in here for you too.
If you don’t have this download it first.
http://www.ijg.org/files/jpegsrc.v7.tar.gz
go into your shell environment and untar by running the following
tar -zxvf jpegsrc.v7.tar.gz
cd jpeg-7
then run
sudo make clean
sudo CC="gcc -arch i386”"./configure --enable-shared --enable-static
sudo make
sudo make install
Next get PIL and untar it
http://effbot.org/downloads/Imaging-1.1.6.tar.gz
tar -zxvf Imaging-1.1.6.tar.gz
cd Imaging-1.1.6
If you already have PIL I would recommend running
sudo rm -Rf build
to clean any existing builds, this has caused me loads of errors and gray hairs!
in your settings.py file run find JPEG_ROOT
amend it so it looks as follows
JPEG_ROOT = libinclude(“/usr/local”)
Next move onto the build
sudo python setup.py build
if libjpeg is successfully installed you should be able to run python selftest.py without any errors relating to “jpeg”
sudo python setup.py install
if all has worked successfully you should be able to enter your python interpreter by executing python in your command line and also do the following:
import PIL
import Image
import _imaging
without any errors.
Just to triple check I have a simple jpeg on my desktop.
image = Image.open(“/Users/MyName/Desktop/myimage.jpeg”)
image.save(“/Users/MyName/Desktop/test.jpeg”)
should work without errors
A:
Download macport:
http://www.macports.org/install.php
Then use it for pil:
http://trac.macports.org/browser/trunk/dports/python/py-pil/Portfile
I also had a lot of trouble with this, but port managed.
A:
I've always gotten several screens worth of gcc errors when trying to install PIL. At some point I got something working (perhaps via MacPorts), so now my solution is to copy it to the appropriate site-packages (e.g. inside a new virtualenv).
I just posted it here: http://blogmaker.com/PIL-1.1.6-for-MacOSX-10.5-Leopard.zip
Works for me; I have no idea whether it will work for anyone else! Feel free to contact me with suggestions. And, let me know if there's a better place I should post it. PIL is both very cool and a royal hassle; it would be nice to have a definitive place for support. There are other PIL-related issues that I never solved.
| Installing PIL on Snow Leopard -- NOTHING WORKS | I'm trying to install PIL on Snow Leopard, using Python 2.6.1, GCC 4.2.1, PIL 1.1.7, and have tried with both libjpeg6b and libjpeg7 -- nothing works. I've cleared out every trace of libjpeg/pil/zlib from fink, tried various compiler options, etc. and used http://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/ and http:// www.brambraakman.com/blog/comments/installing_pil_in_snow_leopard_jpeg_resync_to_restart_error/ (not a link because StOv only lets me post one...)
4 bits of potentially useful information:
OTOOL does not show libjpeg as a dependency
otool -L /Library/Python/2.6/site-packages/PIL/_imaging.so
/Library/Python/2.6/site-packages/PIL/_imaging.so:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
I get these weird compiler messages
i686-apple-darwin10-gcc-4.2.1: -framework: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: Tcl: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: -framework: linker input file unused because linking not done
i686-apple-darwin10-gcc-4.2.1: Tk: linker input file unused because linking not done
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe -I/System/Library/Frameworks/Tcl.framework/Headers -I/System/Library/Frameworks/Tk.framework/Headers -IlibImaging -I/sw/include/freetype2 -I/sw/include -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c Tk/tkImaging.c -o build/temp.macosx-10.6-universal-2.6/Tk/tkImaging.o -framework Tcl -framework Tk
In file included from /System/Library/Frameworks/Tk.framework/Headers/tk.h:78,
from Tk/tkImaging.c:51:
selftest.py fails because of _imagingmath (after I used the second link given above, before it too failed due to _imaging)
Themistocles:Imaging-1.1.7 me$ python selftest.py
Traceback (most recent call last):
File "selftest.py", line 11, in <module>
from PIL import ImageMath
File "./PIL/ImageMath.py", line 19, in <module>
import _imagingmath
ImportError: No module named _imagingmath
Anything but selftest.py fails because of _imaging
>>> import _imaging
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.6/site-packages/PIL/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart
Referenced from: /Library/Python/2.6/site-packages/PIL/_imaging.so
Expected in: flat namespace
in /Library/Python/2.6/site-packages/PIL/_imaging.so
Please, please help! This is getting ridiculous. I'd even be happy to be able to compile PIL sans jpeg support at this point!
| [
"I recently wrote an article on how to get PIL, django, libjpeg to work nicely alongside Snow Leopard\nhttp://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/\nI'll copy it in here for you too.\nIf you don’t have this download it first.\n\nhttp://www.ijg.org/files/jpegsrc.v7.ta... | [
5,
1,
0
] | [] | [] | [
"gcc",
"libjpeg",
"osx_snow_leopard",
"python",
"python_imaging_library"
] | stackoverflow_0003224628_gcc_libjpeg_osx_snow_leopard_python_python_imaging_library.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.