content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
sequence | answers_scores
sequence | non_answers
sequence | non_answers_scores
sequence | tags
sequence | name
stringlengths 35
137
|
---|---|---|---|---|---|---|---|---|
Q:
Which is the most useful Mercurial hook for programming in a loosely connected team?
I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier.
notify-extension: https://www.mercurial-scm.org/wiki/NotifyExtension
Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team?
Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it.
A:
I really enjoy what I did with my custom hook. I have it post a message to my campfire account (campfire is a group based app). It worked out really well. Because I had my clients in there and it could show him my progress.
A:
Take a look at the hgweb stuff. You can set up RSS feeds and see all the revisions, et cetera.
A:
I've written a small set of minor hooks which might be interesting: http://fellowiki.org/hg/support/quecksilber/file/
Anyway, these are the hooks most useful to me ;-)
| Which is the most useful Mercurial hook for programming in a loosely connected team? | I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier.
notify-extension: https://www.mercurial-scm.org/wiki/NotifyExtension
Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team?
Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it.
| [
"I really enjoy what I did with my custom hook. I have it post a message to my campfire account (campfire is a group based app). It worked out really well. Because I had my clients in there and it could show him my progress.\n",
"Take a look at the hgweb stuff. You can set up RSS feeds and see all the revisions, et cetera.\n",
"I've written a small set of minor hooks which might be interesting: http://fellowiki.org/hg/support/quecksilber/file/\nAnyway, these are the hooks most useful to me ;-)\n"
] | [
2,
1,
1
] | [] | [] | [
"hook",
"mercurial",
"python"
] | stackoverflow_0000063488_hook_mercurial_python.txt |
Q:
jython date conversion
Given a string as below, I need to convert:
1 Dec 2008 06:43:00 +0100
to
MM/DD/YYYY HH:MM:SSAM
using jython what is the best way to do this?
A:
I don't have jython handy, but I'd expect something like this to work:
import java
sdf = java.text.SimpleDateFormat
fmt_in = sdf('d MMM yyyy HH:mm:ss Z')
fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')
fmt_out.format(fmt_in.parse(time_str))
A:
Jython 2.5b0 (beta) has an implementation of the time module that includes
strptime(string[, format]).
Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
(strptime is missing in Jython2.2.1).
A python version of the conversion formats will look like (not sure of the zone component):
import time
mytime = time.strptime("1 Dec 2008 06:43:00 +0100", "%d %b %Y %H:%M:%S %Z")
new_time_string = time.strftime("%m/%d/%Y %I:%M:%S%p", mytime)
| jython date conversion | Given a string as below, I need to convert:
1 Dec 2008 06:43:00 +0100
to
MM/DD/YYYY HH:MM:SSAM
using jython what is the best way to do this?
| [
"I don't have jython handy, but I'd expect something like this to work:\nimport java\nsdf = java.text.SimpleDateFormat\n\nfmt_in = sdf('d MMM yyyy HH:mm:ss Z')\nfmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')\n\nfmt_out.format(fmt_in.parse(time_str))\n\n",
"Jython 2.5b0 (beta) has an implementation of the time module that includes\n\nstrptime(string[, format]).\nParse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().\n\n(strptime is missing in Jython2.2.1).\nA python version of the conversion formats will look like (not sure of the zone component):\nimport time\nmytime = time.strptime(\"1 Dec 2008 06:43:00 +0100\", \"%d %b %Y %H:%M:%S %Z\")\nnew_time_string = time.strftime(\"%m/%d/%Y %I:%M:%S%p\", mytime)\n\n"
] | [
2,
1
] | [] | [] | [
"date_conversion",
"jython",
"python"
] | stackoverflow_0000330383_date_conversion_jython_python.txt |
Q:
CherryPy for a webhosting control panel application
For quite a long time I've wanted to start a pet project that will aim in
time to become a web hosting control panel, but mainly focused on Python hosting --
meaning I would like to make a way for users to generate/start Django/
other frameworks projects right from the panel. I seemed to have
found the perfect tool to build my app with it: CherryPy.
This would allow me to do it the way I want, building the app with its own HTTP/
HTTPS server and also all in my favorite programming language.
But now a new question arises: As CherryPy is a threaded server, will
it be the right for this kind of task?
There will be lots of time consuming tasks so if one of the
tasks blocks, the rest of the users trying to access other pages will
be left waiting and eventually get timed out.
I imagine that this kind of problem wouldn't happen on a fork based server.
What would you advise?
A:
"Threaded" and "Fork based" servers are equivalent. A "threaded" server has multiple threads of execution, and if one blocks then the others will continue. A "Fork based" server has multiple processes executing, and if one blocks then the others will continue. The only difference is that threaded servers by default will share memory between the threads, "fork based" ones by default will not share memory.
One other point - the "subprocess" module is not thread safe, so if you try to use it from CherryPy you will get wierd errors. (This is Python Bug 1731717)
| CherryPy for a webhosting control panel application | For quite a long time I've wanted to start a pet project that will aim in
time to become a web hosting control panel, but mainly focused on Python hosting --
meaning I would like to make a way for users to generate/start Django/
other frameworks projects right from the panel. I seemed to have
found the perfect tool to build my app with it: CherryPy.
This would allow me to do it the way I want, building the app with its own HTTP/
HTTPS server and also all in my favorite programming language.
But now a new question arises: As CherryPy is a threaded server, will
it be the right for this kind of task?
There will be lots of time consuming tasks so if one of the
tasks blocks, the rest of the users trying to access other pages will
be left waiting and eventually get timed out.
I imagine that this kind of problem wouldn't happen on a fork based server.
What would you advise?
| [
"\"Threaded\" and \"Fork based\" servers are equivalent. A \"threaded\" server has multiple threads of execution, and if one blocks then the others will continue. A \"Fork based\" server has multiple processes executing, and if one blocks then the others will continue. The only difference is that threaded servers by default will share memory between the threads, \"fork based\" ones by default will not share memory.\nOne other point - the \"subprocess\" module is not thread safe, so if you try to use it from CherryPy you will get wierd errors. (This is Python Bug 1731717)\n"
] | [
1
] | [] | [] | [
"cherrypy",
"fork",
"multithreading",
"python"
] | stackoverflow_0000330573_cherrypy_fork_multithreading_python.txt |
Q:
Pure Python rational numbers module for 2.5
Has anybody seen such a thing? Small self-sufficient modules are preferred.
A:
The fractions module from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules.
You can get the single files from here (2.6 branch, 2.7 does not work):
http://hg.python.org/cpython/branches
A:
SymPy is a symbolic maths library written entirely in Python and has full support for rational numbers. From the tutorial:
>>> from sympy import *
>>> a = Rational(1,2)
>>> a
1/2
>>> a*2
1
>>> Rational(2)**50/Rational(10)**50
1/88817841970012523233890533447265625
There is also GMP for Python (GMPY) which, while not pure Python, is probably more efficient.
A:
One more thing to try is Rat.py from demo folder in Python 2.5 maintenance branch. If i understand correctly, it is the daddy of 2.6 fractions. It's a single module without dependencies.
>>> from Rat import rat
>>> rat(1) / rat(3)
Rat(1,3)
>>> rat(1, 3) ** 2
Rat(1,9)
UPDATE: Nah, fractions.py is about 2.5 times faster for my task.
| Pure Python rational numbers module for 2.5 | Has anybody seen such a thing? Small self-sufficient modules are preferred.
| [
"The fractions module from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules. \nYou can get the single files from here (2.6 branch, 2.7 does not work): \nhttp://hg.python.org/cpython/branches\n",
"SymPy is a symbolic maths library written entirely in Python and has full support for rational numbers. From the tutorial:\n>>> from sympy import *\n>>> a = Rational(1,2)\n\n>>> a\n1/2\n\n>>> a*2\n1\n\n>>> Rational(2)**50/Rational(10)**50\n1/88817841970012523233890533447265625\n\nThere is also GMP for Python (GMPY) which, while not pure Python, is probably more efficient.\n",
"One more thing to try is Rat.py from demo folder in Python 2.5 maintenance branch. If i understand correctly, it is the daddy of 2.6 fractions. It's a single module without dependencies.\n>>> from Rat import rat\n>>> rat(1) / rat(3)\nRat(1,3)\n>>> rat(1, 3) ** 2\nRat(1,9)\n\nUPDATE: Nah, fractions.py is about 2.5 times faster for my task.\n"
] | [
10,
9,
3
] | [] | [] | [
"python",
"rational_numbers"
] | stackoverflow_0000329333_python_rational_numbers.txt |
Q:
How to quickly parse a list of strings
If I want to split a list of words separated by a delimiter character, I can use
>>> 'abc,foo,bar'.split(',')
['abc', 'foo', 'bar']
But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?
In: 'abc,"a string, with a comma","another, one"'
Out: ['abc', 'a string, with a comma', 'another, one']
Related question: How can i parse a comma delimited string into a list (caveat)?
A:
import csv
input = ['abc,"a string, with a comma","another, one"']
parser = csv.reader(input)
for fields in parser:
for i,f in enumerate(fields):
print i,f # in Python 3 and up, print is a function; use: print(i,f)
Result:
0 abc
1 a string, with a comma
2 another, one
A:
The CSV module should be able to do that for you
| How to quickly parse a list of strings | If I want to split a list of words separated by a delimiter character, I can use
>>> 'abc,foo,bar'.split(',')
['abc', 'foo', 'bar']
But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?
In: 'abc,"a string, with a comma","another, one"'
Out: ['abc', 'a string, with a comma', 'another, one']
Related question: How can i parse a comma delimited string into a list (caveat)?
| [
"import csv\n\ninput = ['abc,\"a string, with a comma\",\"another, one\"']\nparser = csv.reader(input)\n\nfor fields in parser:\n for i,f in enumerate(fields):\n print i,f # in Python 3 and up, print is a function; use: print(i,f)\n\nResult:\n\n0 abc\n1 a string, with a comma\n2 another, one\n\n",
"The CSV module should be able to do that for you\n"
] | [
42,
8
] | [] | [] | [
"python"
] | stackoverflow_0000330900_python.txt |
Q:
Parsing a string for nested patterns
What would be the best way to do this.
The input string is
<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust.</135_3></133_3>
the expected output is
{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \
using either camera now they are just sitting and collecting dust.':[133, 135],
'The other system worked for about 1 month': [116],
'on it then it started doing the same thing as the first one':[137]
}
that seems like a recursive regexp search but I can't figure out how exactly.
I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.
Related question: Can regular expressions be used to match nested patterns?
A:
Take an XML parser, make it generate a DOM (Document Object Model) and then build a recursive algorithm that traverses all the nodes, calls "text()" in each node (that should give you the text in the current node and all children) and puts that as a key in the dictionary.
A:
Use expat or another XML parser; it's more explicit than anything else, considering you're dealing with XML data anyway.
However, note that XML element names can't start with a number as your example has them.
Here's a parser that will do what you need, although you'll need to tweak it to combine duplicate elements into one dict key:
from xml.parsers.expat import ParserCreate
open_elements = {}
result_dict = {}
def start_element(name, attrs):
open_elements[name] = True
def end_element(name):
del open_elements[name]
def char_data(data):
for element in open_elements:
cur = result_dict.setdefault(element, '')
result_dict[element] = cur + data
if __name__ == '__main__':
p = ParserCreate()
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
p.Parse(u'<_133_3><_135_3><_116_2>The other system worked for about 1 month</_116_2> got some good images <_137_3>on it then it started doing the same thing as the first one</_137_3> so then I quit using either camera now they are just sitting and collecting dust.</_135_3></_133_3>', 1)
print result_dict
A:
from cStringIO import StringIO
from collections import defaultdict
####from xml.etree import cElementTree as etree
from lxml import etree
xml = "<e133_3><e135_3><e116_2>The other system worked for about 1 month</e116_2> got some good images <e137_3>on it then it started doing the same thing as the first one</e137_3> so then I quit using either camera now they are just sitting and collecting dust. </e135_3></e133_3>"
d = defaultdict(list)
for event, elem in etree.iterparse(StringIO(xml)):
d[''.join(elem.itertext())].append(int(elem.tag[1:-2]))
print(dict(d.items()))
Output:
{'on it then it started doing the same thing as the first one': [137],
'The other system worked for about 1 month': [116],
'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \
either camera now they are just sitting and collecting dust. ': [133, 135]}
A:
I think a grammar would be the best option here. I found a link with some information:
http://www.onlamp.com/pub/a/python/2006/01/26/pyparsing.html
A:
Note that you can't actually solve this by a regular expression, since they don't have the expressive power to enforce proper nesting.
Take the following mini-language:
A certain number of "(" followed by the same number of ")", no matter what the number.
You could make a regular expression very easily to represent a super-language of this mini-language (where you don't enforce the equality of the number of starts parentheses and end parentheses). You could also make a regular expression very easilty to represent any finite sub-language (where you limit yourself to some max depth of nesting). But you can never represent this exact language in a regular expression.
So you'd have to use a grammar, yes.
A:
Here's an unreliable inefficient recursive regexp solution:
import re
re_tag = re.compile(r'<(?P<tag>[^>]+)>(?P<content>.*?)</(?P=tag)>', re.S)
def iterparse(text, tag=None):
if tag is not None: yield tag, text
for m in re_tag.finditer(text):
for tag, text in iterparse(m.group('content'), m.group('tag')):
yield tag, text
def strip_tags(content):
nested = lambda m: re_tag.sub(nested, m.group('content'))
return re_tag.sub(nested, content)
txt = "<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust. </135_3></133_3>"
d = {}
for tag, text in iterparse(txt):
d.setdefault(strip_tags(text), []).append(int(tag[:-2]))
print(d)
Output:
{'on it then it started doing the same thing as the first one': [137],
'The other system worked for about 1 month': [116],
'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \
either camera now they are just sitting and collecting dust. ': [133, 135]}
| Parsing a string for nested patterns | What would be the best way to do this.
The input string is
<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust.</135_3></133_3>
the expected output is
{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \
using either camera now they are just sitting and collecting dust.':[133, 135],
'The other system worked for about 1 month': [116],
'on it then it started doing the same thing as the first one':[137]
}
that seems like a recursive regexp search but I can't figure out how exactly.
I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.
Related question: Can regular expressions be used to match nested patterns?
| [
"Take an XML parser, make it generate a DOM (Document Object Model) and then build a recursive algorithm that traverses all the nodes, calls \"text()\" in each node (that should give you the text in the current node and all children) and puts that as a key in the dictionary.\n",
"Use expat or another XML parser; it's more explicit than anything else, considering you're dealing with XML data anyway.\nHowever, note that XML element names can't start with a number as your example has them.\nHere's a parser that will do what you need, although you'll need to tweak it to combine duplicate elements into one dict key:\nfrom xml.parsers.expat import ParserCreate\n\nopen_elements = {}\nresult_dict = {}\n\ndef start_element(name, attrs):\n open_elements[name] = True\n\ndef end_element(name):\n del open_elements[name]\n\ndef char_data(data):\n for element in open_elements:\n cur = result_dict.setdefault(element, '')\n result_dict[element] = cur + data\n\nif __name__ == '__main__':\n p = ParserCreate()\n\n p.StartElementHandler = start_element\n p.EndElementHandler = end_element\n p.CharacterDataHandler = char_data\n\n p.Parse(u'<_133_3><_135_3><_116_2>The other system worked for about 1 month</_116_2> got some good images <_137_3>on it then it started doing the same thing as the first one</_137_3> so then I quit using either camera now they are just sitting and collecting dust.</_135_3></_133_3>', 1)\n\n print result_dict\n\n",
"from cStringIO import StringIO\nfrom collections import defaultdict\n####from xml.etree import cElementTree as etree\nfrom lxml import etree\n\nxml = \"<e133_3><e135_3><e116_2>The other system worked for about 1 month</e116_2> got some good images <e137_3>on it then it started doing the same thing as the first one</e137_3> so then I quit using either camera now they are just sitting and collecting dust. </e135_3></e133_3>\"\n\nd = defaultdict(list)\nfor event, elem in etree.iterparse(StringIO(xml)):\n d[''.join(elem.itertext())].append(int(elem.tag[1:-2]))\n\nprint(dict(d.items()))\n\nOutput:\n{'on it then it started doing the same thing as the first one': [137], \n'The other system worked for about 1 month': [116], \n'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \\\neither camera now they are just sitting and collecting dust. ': [133, 135]}\n\n",
"I think a grammar would be the best option here. I found a link with some information:\nhttp://www.onlamp.com/pub/a/python/2006/01/26/pyparsing.html\n",
"Note that you can't actually solve this by a regular expression, since they don't have the expressive power to enforce proper nesting.\nTake the following mini-language:\n\nA certain number of \"(\" followed by the same number of \")\", no matter what the number.\n\nYou could make a regular expression very easily to represent a super-language of this mini-language (where you don't enforce the equality of the number of starts parentheses and end parentheses). You could also make a regular expression very easilty to represent any finite sub-language (where you limit yourself to some max depth of nesting). But you can never represent this exact language in a regular expression.\nSo you'd have to use a grammar, yes.\n",
"Here's an unreliable inefficient recursive regexp solution:\nimport re\n\nre_tag = re.compile(r'<(?P<tag>[^>]+)>(?P<content>.*?)</(?P=tag)>', re.S)\n\ndef iterparse(text, tag=None):\n if tag is not None: yield tag, text\n for m in re_tag.finditer(text):\n for tag, text in iterparse(m.group('content'), m.group('tag')):\n yield tag, text\n\ndef strip_tags(content):\n nested = lambda m: re_tag.sub(nested, m.group('content'))\n return re_tag.sub(nested, content)\n\n\ntxt = \"<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust. </135_3></133_3>\"\nd = {}\nfor tag, text in iterparse(txt):\n d.setdefault(strip_tags(text), []).append(int(tag[:-2]))\n\nprint(d)\n\nOutput:\n{'on it then it started doing the same thing as the first one': [137], \n 'The other system worked for about 1 month': [116], \n 'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \\\n either camera now they are just sitting and collecting dust. ': [133, 135]}\n\n"
] | [
4,
4,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000330334_python_regex.txt |
Q:
Memory Efficient Alternatives to Python Dictionaries
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDict[word1][word2][word3] returns the number of times these words appear in the text, topDict[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.
This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.
My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.
From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.
So, does anyone have any suggestions for me?
Edited to add:
Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (i.e. I want something like the result of topDict[word1, word2].keys()).
The current dataset I am playing around with is the most recent version of Wikipedia For Schools. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.
A:
Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record:
295760 S. Lott's answer
237984 S. Lott's with keys interned before passing in
203172 [*] d[(a,b,c)] = int(freq)
203156 d[a][b][c] = int(freq)
189132 keys.append((a,b,c)); freqs.append(int(freq))
146132 d[intern(a),intern(b)][intern(c)] = int(freq)
145408 d[intern(a)][intern(b)][intern(c)] = int(freq)
83888 [*] d[a+' '+b+' '+c] = int(freq)
82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq)
68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq))
60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq))
50556 pair array
48320 squeezed pair array
33024 squeezed single array
The entries marked [*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.)
'Pair array' is the scheme below in my original answer ("I'd start with the array with keys
being the first two words..."), where the value table for each pair is
represented as a single string. 'Squeezed pair array' is the same,
leaving out the frequency values that are equal to 1 (the most common
case). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code:
import collections
def build(file):
pairs = collections.defaultdict(list)
for line in file: # N.B. file assumed to be already sorted
a, b, c, freq = line.split()
key = ' '.join((a, b))
pairs[key].append(c + ':' + freq if freq != '1' else c)
out = open('squeezedsinglearrayfile', 'w')
for key in sorted(pairs.keys()):
out.write('%s|%s\n' % (key, ' '.join(pairs[key])))
def load():
return open('squeezedsinglearrayfile').readlines()
if __name__ == '__main__':
build(open('freqs'))
I haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below.
Original answer: A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using zlib? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options.
Also, binary tree structures are not recommended for memory efficiency here. E.g., this paper tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure.
I should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.)
A:
Use tuples.
Tuples can be keys to dictionaries, so you don't need to nest dictionaries.
d = {}
d[ word1, word2, word3 ] = 1
Also as a plus, you could use defaultdict
so that elements that don't have entries always return 0
and so that u can say d[w1,w2,w3] += 1 without checking if the key already exists or not
example:
from collections import defaultdict
d = defaultdict(int)
d["first","word","tuple"] += 1
If you need to find all words "word3" that are tupled with (word1,word2) then search for it in dictionary.keys() using list comprehension
if you have a tuple, t, you can get the first two items using slices:
>>> a = (1,2,3)
>>> a[:2]
(1, 2)
a small example for searching tuples with list comprehensions:
>>> b = [(1,2,3),(1,2,5),(3,4,6)]
>>> search = (1,2)
>>> [a[2] for a in b if a[:2] == search]
[3, 5]
You see here, we got a list of all items that appear as the third item in the tuples that start with (1,2)
A:
In this case, ZODB¹ BTrees might be helpful, since they are much less memory-hungry. Use a BTrees.OOBtree (Object keys to Object values) or BTrees.OIBTree (Object keys to Integer values), and use 3-word tuples as your key.
Something like:
from BTrees.OOBTree import OOBTree as BTree
The interface is, more or less, dict-like, with the added bonus (for you) that .keys, .items, .iterkeys and .iteritems have two min, max optional arguments:
>>> t=BTree()
>>> t['a', 'b', 'c']= 10
>>> t['a', 'b', 'z']= 11
>>> t['a', 'a', 'z']= 12
>>> t['a', 'd', 'z']= 13
>>> print list(t.keys(('a', 'b'), ('a', 'c')))
[('a', 'b', 'c'), ('a', 'b', 'z')]
¹ Note that if you are on Windows and work with Python >2.4, I know there are packages for more recent python versions, but I can't recollect where.
PS They exist in the CheeseShop ☺
A:
A couple attempts:
I figure you're doing something similar to this:
from __future__ import with_statement
import time
from collections import deque, defaultdict
# Just used to generate some triples of words
def triplegen(words="/usr/share/dict/words"):
d=deque()
with open(words) as f:
for i in range(3):
d.append(f.readline().strip())
while d[-1] != '':
yield tuple(d)
d.popleft()
d.append(f.readline().strip())
if __name__ == '__main__':
class D(dict):
def __missing__(self, key):
self[key] = D()
return self[key]
h=D()
for a, b, c in triplegen():
h[a][b][c] = 1
time.sleep(60)
That gives me ~88MB.
Changing the storage to
h[a, b, c] = 1
takes ~25MB
interning a, b, and c makes it take about 31MB. My case is a bit special because my words never repeat on the input. You might try some variations yourself and see if one of these helps you.
A:
Are you implementing Markovian text generation?
If your chains map 2 words to the probabilities of the third I'd use a dictionary mapping K-tuples to the 3rd-word histogram. A trivial (but memory-hungry) way to implement the histogram would be to use a list with repeats, and then random.choice gives you a word with the proper probability.
Here's an implementation with the K-tuple as a parameter:
import random
# can change these functions to use a dict-based histogram
# instead of a list with repeats
def default_histogram(): return []
def add_to_histogram(item, hist): hist.append(item)
def choose_from_histogram(hist): return random.choice(hist)
K=2 # look 2 words back
words = ...
d = {}
# build histograms
for i in xrange(len(words)-K-1):
key = words[i:i+K]
word = words[i+K]
d.setdefault(key, default_histogram())
add_to_histogram(word, d[key])
# generate text
start = random.randrange(len(words)-K-1)
key = words[start:start+K]
for i in NUM_WORDS_TO_GENERATE:
word = choose_from_histogram(d[key])
print word,
key = key[1:] + (word,)
A:
You could try to use same dictionary, only one level deep.
topDictionary[word1+delimiter+word2+delimiter+word3]
delimiter could be plain " ". (or use (word1,word2,word3))
This would be easiest to implement.
I believe you will see a little improvement, if it is not enough...
...i'll think of something...
A:
Ok, so you are basically trying to store a sparse 3D space. The kind of access patterns you want to this space is crucial for the choice of algorithm and data structure. Considering your data source, do you want to feed this to a grid? If you don't need O(1) access:
In order to get memory efficiency you want to subdivide that space into subspaces with a similar number of entries. (like a BTree). So a data structure with :
firstWordRange
secondWordRange
thirdWordRange
numberOfEntries
a sorted block of entries.
next and previous blocks in all 3 dimensions
A:
Scipy has sparse matrices, so if you can make the first two words a tuple, you can do something like this:
import numpy as N
from scipy import sparse
word_index = {}
count = sparse.lil_matrix((word_count*word_count, word_count), dtype=N.int)
for word1, word2, word3 in triple_list:
w1 = word_index.setdefault(word1, len(word_index))
w2 = word_index.setdefault(word2, len(word_index))
w3 = word_index.setdefault(word3, len(word_index))
w1_w2 = w1 * word_count + w2
count[w1_w2,w3] += 1
A:
If memory is simply not big enough, pybsddb can help store a disk-persistent map.
A:
You could use a numpy multidimensional array. You'll need to use numbers rather than strings to index into the array, but that can be solved by using a single dict to map words to numbers.
import numpy
w = {'word1':1, 'word2':2, 'word3':3, 'word4':4}
a = numpy.zeros( (4,4,4) )
Then to index into your array, you'd do something like:
a[w[word1], w[word2], w[word3]] += 1
That syntax is not beautiful, but numpy arrays are about as efficient as anything you're likely to find. Note also that I haven't tried this code out, so I may be off in some of the details. Just going from memory here.
A:
Here's a tree structure that uses the bisect library to maintain a sorted list of words. Each lookup in O(log2(n)).
import bisect
class WordList( object ):
"""Leaf-level is list of words and counts."""
def __init__( self ):
self.words= [ ('\xff-None-',0) ]
def count( self, wordTuple ):
assert len(wordTuple)==1
word= wordTuple[0]
loc= bisect.bisect_left( self.words, word )
if self.words[loc][0] != word:
self.words.insert( loc, (word,0) )
self.words[loc]= ( word, self.words[loc][1]+1 )
def getWords( self ):
return self.words[:-1]
class WordTree( object ):
"""Above non-leaf nodes are words and either trees or lists."""
def __init__( self ):
self.words= [ ('\xff-None-',None) ]
def count( self, wordTuple ):
head, tail = wordTuple[0], wordTuple[1:]
loc= bisect.bisect_left( self.words, head )
if self.words[loc][0] != head:
if len(tail) == 1:
newList= WordList()
else:
newList= WordTree()
self.words.insert( loc, (head,newList) )
self.words[loc][1].count( tail )
def getWords( self ):
return self.words[:-1]
t = WordTree()
for a in ( ('the','quick','brown'), ('the','quick','fox') ):
t.count(a)
for w1,wt1 in t.getWords():
print w1
for w2,wt2 in wt1.getWords():
print " ", w2
for w3 in wt2.getWords():
print " ", w3
For simplicity, this uses a dummy value in each tree and list. This saves endless if-statements to determine if the list was actually empty before we make a comparison. It's only empty once, so the if-statements are wasted for all n-1 other words.
| Memory Efficient Alternatives to Python Dictionaries | In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDict[word1][word2][word3] returns the number of times these words appear in the text, topDict[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.
This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.
My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.
From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.
So, does anyone have any suggestions for me?
Edited to add:
Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (i.e. I want something like the result of topDict[word1, word2].keys()).
The current dataset I am playing around with is the most recent version of Wikipedia For Schools. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.
| [
"Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record:\n295760 S. Lott's answer\n237984 S. Lott's with keys interned before passing in\n203172 [*] d[(a,b,c)] = int(freq)\n203156 d[a][b][c] = int(freq)\n189132 keys.append((a,b,c)); freqs.append(int(freq))\n146132 d[intern(a),intern(b)][intern(c)] = int(freq)\n145408 d[intern(a)][intern(b)][intern(c)] = int(freq)\n 83888 [*] d[a+' '+b+' '+c] = int(freq)\n 82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq)\n 68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq))\n 60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq))\n 50556 pair array\n 48320 squeezed pair array\n 33024 squeezed single array\n\nThe entries marked [*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.)\n'Pair array' is the scheme below in my original answer (\"I'd start with the array with keys\nbeing the first two words...\"), where the value table for each pair is\nrepresented as a single string. 'Squeezed pair array' is the same,\nleaving out the frequency values that are equal to 1 (the most common\ncase). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code:\nimport collections\n\ndef build(file):\n pairs = collections.defaultdict(list)\n for line in file: # N.B. file assumed to be already sorted\n a, b, c, freq = line.split()\n key = ' '.join((a, b))\n pairs[key].append(c + ':' + freq if freq != '1' else c)\n out = open('squeezedsinglearrayfile', 'w')\n for key in sorted(pairs.keys()):\n out.write('%s|%s\\n' % (key, ' '.join(pairs[key])))\n\ndef load():\n return open('squeezedsinglearrayfile').readlines()\n\nif __name__ == '__main__':\n build(open('freqs'))\n\nI haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below.\nOriginal answer: A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using zlib? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options.\nAlso, binary tree structures are not recommended for memory efficiency here. E.g., this paper tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure.\nI should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.)\n",
"Use tuples.\nTuples can be keys to dictionaries, so you don't need to nest dictionaries.\nd = {}\nd[ word1, word2, word3 ] = 1\n\nAlso as a plus, you could use defaultdict \n\nso that elements that don't have entries always return 0\nand so that u can say d[w1,w2,w3] += 1 without checking if the key already exists or not\n\nexample:\nfrom collections import defaultdict\nd = defaultdict(int)\nd[\"first\",\"word\",\"tuple\"] += 1\n\nIf you need to find all words \"word3\" that are tupled with (word1,word2) then search for it in dictionary.keys() using list comprehension\nif you have a tuple, t, you can get the first two items using slices:\n>>> a = (1,2,3)\n>>> a[:2]\n(1, 2)\n\na small example for searching tuples with list comprehensions:\n>>> b = [(1,2,3),(1,2,5),(3,4,6)]\n>>> search = (1,2)\n>>> [a[2] for a in b if a[:2] == search]\n[3, 5]\n\nYou see here, we got a list of all items that appear as the third item in the tuples that start with (1,2)\n",
"In this case, ZODB¹ BTrees might be helpful, since they are much less memory-hungry. Use a BTrees.OOBtree (Object keys to Object values) or BTrees.OIBTree (Object keys to Integer values), and use 3-word tuples as your key.\nSomething like:\nfrom BTrees.OOBTree import OOBTree as BTree\n\nThe interface is, more or less, dict-like, with the added bonus (for you) that .keys, .items, .iterkeys and .iteritems have two min, max optional arguments:\n>>> t=BTree()\n>>> t['a', 'b', 'c']= 10\n>>> t['a', 'b', 'z']= 11\n>>> t['a', 'a', 'z']= 12\n>>> t['a', 'd', 'z']= 13\n>>> print list(t.keys(('a', 'b'), ('a', 'c')))\n[('a', 'b', 'c'), ('a', 'b', 'z')]\n\n¹ Note that if you are on Windows and work with Python >2.4, I know there are packages for more recent python versions, but I can't recollect where.\nPS They exist in the CheeseShop ☺\n",
"A couple attempts:\nI figure you're doing something similar to this:\nfrom __future__ import with_statement\n\nimport time\nfrom collections import deque, defaultdict\n\n# Just used to generate some triples of words\ndef triplegen(words=\"/usr/share/dict/words\"):\n d=deque()\n with open(words) as f:\n for i in range(3):\n d.append(f.readline().strip())\n\n while d[-1] != '':\n yield tuple(d)\n d.popleft()\n d.append(f.readline().strip())\n\nif __name__ == '__main__':\n class D(dict):\n def __missing__(self, key):\n self[key] = D()\n return self[key]\n h=D()\n for a, b, c in triplegen():\n h[a][b][c] = 1\n time.sleep(60)\n\nThat gives me ~88MB.\nChanging the storage to\nh[a, b, c] = 1\n\ntakes ~25MB\ninterning a, b, and c makes it take about 31MB. My case is a bit special because my words never repeat on the input. You might try some variations yourself and see if one of these helps you.\n",
"Are you implementing Markovian text generation?\nIf your chains map 2 words to the probabilities of the third I'd use a dictionary mapping K-tuples to the 3rd-word histogram. A trivial (but memory-hungry) way to implement the histogram would be to use a list with repeats, and then random.choice gives you a word with the proper probability.\nHere's an implementation with the K-tuple as a parameter:\nimport random\n\n# can change these functions to use a dict-based histogram\n# instead of a list with repeats\ndef default_histogram(): return []\ndef add_to_histogram(item, hist): hist.append(item)\ndef choose_from_histogram(hist): return random.choice(hist)\n\nK=2 # look 2 words back\nwords = ...\nd = {}\n\n# build histograms\nfor i in xrange(len(words)-K-1):\n key = words[i:i+K]\n word = words[i+K]\n\n d.setdefault(key, default_histogram())\n add_to_histogram(word, d[key])\n\n# generate text\nstart = random.randrange(len(words)-K-1)\nkey = words[start:start+K]\nfor i in NUM_WORDS_TO_GENERATE:\n word = choose_from_histogram(d[key])\n print word,\n key = key[1:] + (word,)\n\n",
"You could try to use same dictionary, only one level deep.\ntopDictionary[word1+delimiter+word2+delimiter+word3]\n\ndelimiter could be plain \" \". (or use (word1,word2,word3))\nThis would be easiest to implement.\nI believe you will see a little improvement, if it is not enough...\n...i'll think of something...\n",
"Ok, so you are basically trying to store a sparse 3D space. The kind of access patterns you want to this space is crucial for the choice of algorithm and data structure. Considering your data source, do you want to feed this to a grid? If you don't need O(1) access:\nIn order to get memory efficiency you want to subdivide that space into subspaces with a similar number of entries. (like a BTree). So a data structure with :\n\nfirstWordRange\nsecondWordRange\nthirdWordRange\nnumberOfEntries\na sorted block of entries.\nnext and previous blocks in all 3 dimensions\n\n",
"Scipy has sparse matrices, so if you can make the first two words a tuple, you can do something like this:\nimport numpy as N\nfrom scipy import sparse\n\nword_index = {}\ncount = sparse.lil_matrix((word_count*word_count, word_count), dtype=N.int)\n\nfor word1, word2, word3 in triple_list:\n w1 = word_index.setdefault(word1, len(word_index))\n w2 = word_index.setdefault(word2, len(word_index))\n w3 = word_index.setdefault(word3, len(word_index))\n w1_w2 = w1 * word_count + w2\n count[w1_w2,w3] += 1\n\n",
"If memory is simply not big enough, pybsddb can help store a disk-persistent map.\n",
"You could use a numpy multidimensional array. You'll need to use numbers rather than strings to index into the array, but that can be solved by using a single dict to map words to numbers.\nimport numpy\nw = {'word1':1, 'word2':2, 'word3':3, 'word4':4}\na = numpy.zeros( (4,4,4) )\n\nThen to index into your array, you'd do something like:\na[w[word1], w[word2], w[word3]] += 1\n\nThat syntax is not beautiful, but numpy arrays are about as efficient as anything you're likely to find. Note also that I haven't tried this code out, so I may be off in some of the details. Just going from memory here.\n",
"Here's a tree structure that uses the bisect library to maintain a sorted list of words. Each lookup in O(log2(n)).\nimport bisect\n\nclass WordList( object ):\n \"\"\"Leaf-level is list of words and counts.\"\"\"\n def __init__( self ):\n self.words= [ ('\\xff-None-',0) ]\n def count( self, wordTuple ):\n assert len(wordTuple)==1\n word= wordTuple[0]\n loc= bisect.bisect_left( self.words, word )\n if self.words[loc][0] != word:\n self.words.insert( loc, (word,0) ) \n self.words[loc]= ( word, self.words[loc][1]+1 )\n def getWords( self ):\n return self.words[:-1]\n\nclass WordTree( object ):\n \"\"\"Above non-leaf nodes are words and either trees or lists.\"\"\"\n def __init__( self ):\n self.words= [ ('\\xff-None-',None) ]\n def count( self, wordTuple ):\n head, tail = wordTuple[0], wordTuple[1:]\n loc= bisect.bisect_left( self.words, head )\n if self.words[loc][0] != head:\n if len(tail) == 1:\n newList= WordList()\n else:\n newList= WordTree()\n self.words.insert( loc, (head,newList) )\n self.words[loc][1].count( tail )\n def getWords( self ):\n return self.words[:-1]\n\nt = WordTree()\nfor a in ( ('the','quick','brown'), ('the','quick','fox') ):\n t.count(a)\n\nfor w1,wt1 in t.getWords():\n print w1\n for w2,wt2 in wt1.getWords():\n print \" \", w2\n for w3 in wt2.getWords():\n print \" \", w3\n\nFor simplicity, this uses a dummy value in each tree and list. This saves endless if-statements to determine if the list was actually empty before we make a comparison. It's only empty once, so the if-statements are wasted for all n-1 other words.\n"
] | [
33,
9,
4,
3,
2,
1,
1,
1,
0,
0,
0
] | [
"You could put all words in a dictionary.\nkey would be word, and value is number (index).\nThen you use it like this:\nWord1=indexDict[word1]\nWord2=indexDict[word2]\nWord3=indexDict[word3]\n\ntopDictionary[Word1][Word2][Word3]\n\nInsert in indexDict with:\nif word not in indexDict:\n indexDict[word]=len(indexDict)\n\n"
] | [
-1
] | [
"data_structures",
"memory",
"python"
] | stackoverflow_0000327223_data_structures_memory_python.txt |
Q:
Python UPnP/IGD Client Implementation?
I am searching for an open-source implementation of an UPnP client in Python, and more specifically of its Internet Gateway Device (IGD) part.
For now, I have only been able to find UPnP Media Server implementations, in projects such as PyMediaServer, PyMedS, BRisa or Coherence.
I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity.
So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as MiniUPnP, but I would much prefer a pure Python implementation.
Update: an interesting, kind of related discussion of SSDP and UPnP is available on StackOverflow.
A:
MiniUPnP source code contains a Python sample code using the C library as an extension module (see testupnpigd.py), which I consider as a proper solution to my problem.
Rationale: this is not the pure Python solution I was looking for, but:
significant effort has already been invested in this library,
it is lightweight (it does not address Media Server issues),
IGD is typically only used at connection setup, so not integrating it tighter with the Python code does not seem like an issue,
as a bonus, it also provides a NAT-PNP implementation (the Apple concurrent of IGD, part of Bonjour).
A:
I think you should really consider BRisa. It recently became a pure python UPnP Framework, not focused only on Media Server.
It provides lots of utilitary modules and functions for you to build and deploy your UPnP device.
The project also is lacking feedback :-). I suggest you to use the latest svn code, if you're willing to try BRisa.
You can also contact the developers on #brisa at irc.freenode.org, we're either online or idling.
| Python UPnP/IGD Client Implementation? | I am searching for an open-source implementation of an UPnP client in Python, and more specifically of its Internet Gateway Device (IGD) part.
For now, I have only been able to find UPnP Media Server implementations, in projects such as PyMediaServer, PyMedS, BRisa or Coherence.
I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity.
So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as MiniUPnP, but I would much prefer a pure Python implementation.
Update: an interesting, kind of related discussion of SSDP and UPnP is available on StackOverflow.
| [
"MiniUPnP source code contains a Python sample code using the C library as an extension module (see testupnpigd.py), which I consider as a proper solution to my problem.\nRationale: this is not the pure Python solution I was looking for, but:\n\nsignificant effort has already been invested in this library,\nit is lightweight (it does not address Media Server issues),\nIGD is typically only used at connection setup, so not integrating it tighter with the Python code does not seem like an issue,\nas a bonus, it also provides a NAT-PNP implementation (the Apple concurrent of IGD, part of Bonjour).\n\n",
"I think you should really consider BRisa. It recently became a pure python UPnP Framework, not focused only on Media Server.\nIt provides lots of utilitary modules and functions for you to build and deploy your UPnP device.\nThe project also is lacking feedback :-). I suggest you to use the latest svn code, if you're willing to try BRisa.\nYou can also contact the developers on #brisa at irc.freenode.org, we're either online or idling.\n"
] | [
7,
2
] | [] | [] | [
"nat",
"networking",
"python",
"upnp"
] | stackoverflow_0000294504_nat_networking_python_upnp.txt |
Q:
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.
L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.
A:
You could try freeze.py, see http://wiki.python.org/moin/Freeze for more details.
A:
Try py2exe.
A:
But if you make a deb with the correct dependencies listed the installer will download them for the user. That's the best way, as it's non redundant.
Maybe you could make a tar or zip with your deb and all the third-party deb's and an install script that just install all the debs in the correct order. This way, if the user already has some package it wouldn't be installed again.
A:
You can have your users run the system from a startup script, and that script can fix the pythonpath ahead of time to put your versions first. For example if you put CherryPy, SQLAlchemy, etc. in an "external" subdirectory, you could try:
# startproj.sh
script_path=`dirname $0`
export PYTHONPATH=${script_path}/external;${PYTHONPATH}
exec ${script_path}/projstartup.py
| How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible | How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.
L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.
| [
"You could try freeze.py, see http://wiki.python.org/moin/Freeze for more details.\n",
"Try py2exe.\n",
"But if you make a deb with the correct dependencies listed the installer will download them for the user. That's the best way, as it's non redundant. \nMaybe you could make a tar or zip with your deb and all the third-party deb's and an install script that just install all the debs in the correct order. This way, if the user already has some package it wouldn't be installed again.\n",
"You can have your users run the system from a startup script, and that script can fix the pythonpath ahead of time to put your versions first. For example if you put CherryPy, SQLAlchemy, etc. in an \"external\" subdirectory, you could try:\n# startproj.sh\nscript_path=`dirname $0`\nexport PYTHONPATH=${script_path}/external;${PYTHONPATH}\nexec ${script_path}/projstartup.py\n\n"
] | [
4,
3,
2,
2
] | [] | [] | [
"deployment",
"linux",
"python"
] | stackoverflow_0000331377_deployment_linux_python.txt |
Q:
How to determine if a page is being redirected
I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python?
Thanks!
A:
If you specifically want to avoid downloading the content, you'll need to use the HEAD request method. I believe the urllib and urllib2 libraries do not support HEAD requests, so you'll have to use the lower-level httplib library:
import httplib
h = httplib.HTTPConnection('www.example.com')
h.request('HEAD', '/')
response = h.getresponse()
// Check for 30x status code
if 300 <= response.status < 400:
// It's a redirect
location = response.getheader('Location')
A:
When you open the URL with urllib2, and you're redirected, you get a status 30x for redirection. Check the info to see the location to which you're redirected. You don't need to read the page to read the info() that's part of the response.
| How to determine if a page is being redirected | I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python?
Thanks!
| [
"If you specifically want to avoid downloading the content, you'll need to use the HEAD request method. I believe the urllib and urllib2 libraries do not support HEAD requests, so you'll have to use the lower-level httplib library:\nimport httplib\n\nh = httplib.HTTPConnection('www.example.com')\nh.request('HEAD', '/')\nresponse = h.getresponse()\n\n// Check for 30x status code\nif 300 <= response.status < 400:\n // It's a redirect\n location = response.getheader('Location')\n\n",
"When you open the URL with urllib2, and you're redirected, you get a status 30x for redirection. Check the info to see the location to which you're redirected. You don't need to read the page to read the info() that's part of the response.\n"
] | [
9,
1
] | [] | [] | [
"http",
"http_headers",
"python"
] | stackoverflow_0000331855_http_http_headers_python.txt |
Q:
What is a good Python format style
I've created a small python script to toggle between two files I'm using for testing.
My question is, what is a good Python format style for the following code:
import filecmp
import shutil
local = "local.txt"
remote = "remote.txt"
config_file = "C:\some\path\file.txt"
shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file )
Or
shutil.copyfile( remote
if( filecmp.cmp(local, config_file ) )
else local,
config_file )
Or
tocopy = remote if( filecmp.cmp( local, config_file ) ) else local
shutil.copyfile( tocopy, config_file )
Or what?
Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"
A:
For the conditional statement, I would probably go with:
if filecmp.cmp(local, config_file):
shutil.copyfile(remote, config_file)
else:
shutil.copyfile(local, config_file)
There's little need to use the inline y if x else z in this case, since the surrounding code is simple enough.
A:
The most common naming I've seen is underscode separated words, to_copy.
As for the format style, I've seen no such agreement. I find
source = remote if filecmp.cmp(local, config_file) else local
shutil.copyfile(source, config_file)
to be the clearest among your options.
And seeing that everyone prefers to split the if I'd, at the very least, encapsulate the copyfile call in case you someday wish to change it:
def copy_to(source, destination):
shutil.copyfile(source,destination)
if filecmp.cmp(local, config_file):
copy_to(remote, config_file)
else:
copy_to(local, config_file)
A:
From the Python Style Guide:
With regard to listing out a compound expression:
Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
Or for the code you supplied, Greg's example is a good one:
if filecmp.cmp(local, config_file):
shutil.copyfile(remote, config_file)
else:
shutil.copyfile(local, config_file)
Rather not:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
Method Names and Instance Variables
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
Update: Per Oscar's request, also listed how his code would look in this fashion.
A:
The third option looks the most natural to me, although your use of spaces in side parentheses and superfluous parentheses contradict the Python style guide.
That guide also answers the to_copy question, but I would probably use clearer names altogether.
I would write it as:
import filecmp
import shutil
local = "local.txt"
remote = "remote.txt"
destination = r"C:\some\path\file.txt"
source = remote if filecmp.cmp(local, destination) else local
shutil.copyfile(source, destination)
A:
What about:
import filecmp
import shutil
local = "local.txt"
remote = "remote.txt"
config_file = "C:\some\path\file.txt"
if filecmp.cmp( local, config_file):
to_copy = remote
else:
to_copy = local
shutil.copyfile( to_copy, config_file )
yikes, this open id screen name looks terrible.
| What is a good Python format style | I've created a small python script to toggle between two files I'm using for testing.
My question is, what is a good Python format style for the following code:
import filecmp
import shutil
local = "local.txt"
remote = "remote.txt"
config_file = "C:\some\path\file.txt"
shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file )
Or
shutil.copyfile( remote
if( filecmp.cmp(local, config_file ) )
else local,
config_file )
Or
tocopy = remote if( filecmp.cmp( local, config_file ) ) else local
shutil.copyfile( tocopy, config_file )
Or what?
Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"
| [
"For the conditional statement, I would probably go with:\nif filecmp.cmp(local, config_file):\n shutil.copyfile(remote, config_file)\nelse:\n shutil.copyfile(local, config_file)\n\nThere's little need to use the inline y if x else z in this case, since the surrounding code is simple enough.\n",
"The most common naming I've seen is underscode separated words, to_copy.\nAs for the format style, I've seen no such agreement. I find \nsource = remote if filecmp.cmp(local, config_file) else local\n\nshutil.copyfile(source, config_file)\n\nto be the clearest among your options.\nAnd seeing that everyone prefers to split the if I'd, at the very least, encapsulate the copyfile call in case you someday wish to change it:\ndef copy_to(source, destination):\n shutil.copyfile(source,destination)\n\nif filecmp.cmp(local, config_file):\n copy_to(remote, config_file)\nelse:\n copy_to(local, config_file)\n\n",
"From the Python Style Guide:\nWith regard to listing out a compound expression:\nCompound statements (multiple statements on the same line) are generally discouraged.\nYes:\nif foo == 'blah':\n do_blah_thing()\ndo_one()\ndo_two()\ndo_three()\n\nOr for the code you supplied, Greg's example is a good one:\nif filecmp.cmp(local, config_file):\n shutil.copyfile(remote, config_file)\nelse:\n shutil.copyfile(local, config_file)\n\nRather not:\nif foo == 'blah': do_blah_thing()\ndo_one(); do_two(); do_three()\n\nMethod Names and Instance Variables\nUse the function naming rules: lowercase with words separated by underscores as necessary to improve readability.\nUpdate: Per Oscar's request, also listed how his code would look in this fashion.\n",
"The third option looks the most natural to me, although your use of spaces in side parentheses and superfluous parentheses contradict the Python style guide.\nThat guide also answers the to_copy question, but I would probably use clearer names altogether.\nI would write it as:\nimport filecmp\nimport shutil\n\nlocal = \"local.txt\"\nremote = \"remote.txt\"\n\ndestination = r\"C:\\some\\path\\file.txt\"\nsource = remote if filecmp.cmp(local, destination) else local\n\nshutil.copyfile(source, destination)\n\n",
"What about:\nimport filecmp\nimport shutil\n\nlocal = \"local.txt\"\nremote = \"remote.txt\"\nconfig_file = \"C:\\some\\path\\file.txt\"\n\n\nif filecmp.cmp( local, config_file):\n to_copy = remote\nelse:\n to_copy = local\n\n\nshutil.copyfile( to_copy, config_file )\n\nyikes, this open id screen name looks terrible.\n"
] | [
16,
5,
5,
5,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0000331767_coding_style_python.txt |
Q:
Storing and updating lists in Python dictionaries: why does this happen?
I have a list of data that looks like the following:
// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
... and I want to make this look like:
0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:
# where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
Now this causes IDLE to fail. However, if I do:
# code 2
d[t] = []
d[t].append(c)
... this works.
So the question is: why does code 2 work, but code 1 doesn't?
PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through.
A:
Let's look at
d[t].append(c)
What is the value of d[t]? Try it.
d = {}
t = 0
d[t]
What do you get? Oh. There's nothing in d that has a key of t.
Now try this.
d[t] = []
d[t]
Ahh. Now there's something in d with a key of t.
There are several things you can do.
Use example 2.
Use setdefault. d.setdefault(t,[]).append(c).
Use collections.defaultdict. You'd use a defaultdict(list) instead of a simple dictionary, {}.
Edit 1. Optimization
Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex
list of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived.
d= collections.defaultdict(list)
for ts, x, y in someFileOrListOrQueryOrWhatever:
d[ts].append( (x,y) )
Edit 2. Answer Question
"when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?"
I'm not sure what the question means. Since, all dictionaries are key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question.
Example 2.
Initialization
d= {}
Use
if t not in d:
d[t] = list()
d[t].append( c )
Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list.
Setdefault
Initialization
d= {}
Use
d.setdefault(t,list()).append( c )
In this case, we exploit the setdefault method to either fetch a value associated with a key or create a new value associated with a missing key.
default dict
Initialization
import collections
d = collections.defaultdict(list)
Use
d[t].append( c )
The defaultdict uses an initializer function for missing keys. In this case, we provide the list function so that a new, empty list is created for a missing key.
A:
I think you want to use setdefault. It's a bit weird to use but does exactly what you need.
d.setdefault(t, []).append(c)
The .setdefault method will return the element (in our case, a list) that's bound to the dict's key t if that key exists. If it doesn't, it will bind an empty list to the key t and return it. So either way, a list will be there that the .append method can then append the tuple c to.
A:
dict=[] //it's not a dict, it's a list, the dictionary is dict={}
elem=[1,2,3]
dict.append(elem)
you can access the single element in this way:
print dict[0] // 0 is the index
the output will be:
[1, 2, 3]
A:
In the case your data is not already sorted by desired criteria, here's the code that might help to group the data:
#!/usr/bin/env python
"""
$ cat data_shuffled.txt
0,2,7
1,4,7
0,4,7
1,9,0
1,2,5
0,6,7
1,6,8
0,9,5
"""
from itertools import groupby
from operator import itemgetter
# load the data and make sure it is sorted by the first column
sortby_key = itemgetter(0)
data = sorted((map(int, line.split(',')) for line in open('data_shuffled.txt')),
key=sortby_key)
# group by the first column
grouped_data = []
for key, group in groupby(data, key=sortby_key):
assert key == len(grouped_data) # assume the first column is 0,1, ...
grouped_data.append([trio[1:] for trio in group])
# print the data
for i, pairs in enumerate(grouped_data):
print i, pairs
Output:
0 [[2, 7], [4, 7], [6, 7], [9, 5]]
1 [[4, 7], [9, 0], [2, 5], [6, 8]]
| Storing and updating lists in Python dictionaries: why does this happen? | I have a list of data that looks like the following:
// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
... and I want to make this look like:
0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:
# where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
Now this causes IDLE to fail. However, if I do:
# code 2
d[t] = []
d[t].append(c)
... this works.
So the question is: why does code 2 work, but code 1 doesn't?
PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through.
| [
"Let's look at\nd[t].append(c)\n\nWhat is the value of d[t]? Try it.\nd = {}\nt = 0\nd[t]\n\nWhat do you get? Oh. There's nothing in d that has a key of t.\nNow try this.\nd[t] = []\nd[t]\n\nAhh. Now there's something in d with a key of t.\nThere are several things you can do. \n\nUse example 2.\nUse setdefault. d.setdefault(t,[]).append(c).\nUse collections.defaultdict. You'd use a defaultdict(list) instead of a simple dictionary, {}.\n\n\nEdit 1. Optimization\nGiven input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex\nlist of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived.\nd= collections.defaultdict(list)\nfor ts, x, y in someFileOrListOrQueryOrWhatever:\n d[ts].append( (x,y) )\n\n\nEdit 2. Answer Question\n\"when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?\"\nI'm not sure what the question means. Since, all dictionaries are key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question.\nExample 2.\nInitialization\nd= {}\n\nUse\nif t not in d:\n d[t] = list()\nd[t].append( c )\n\nEach dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list.\nSetdefault\nInitialization\nd= {}\n\nUse\nd.setdefault(t,list()).append( c )\n\nIn this case, we exploit the setdefault method to either fetch a value associated with a key or create a new value associated with a missing key.\ndefault dict\nInitialization\nimport collections\nd = collections.defaultdict(list)\n\nUse\nd[t].append( c )\n\nThe defaultdict uses an initializer function for missing keys. In this case, we provide the list function so that a new, empty list is created for a missing key.\n",
"I think you want to use setdefault. It's a bit weird to use but does exactly what you need.\nd.setdefault(t, []).append(c)\n\nThe .setdefault method will return the element (in our case, a list) that's bound to the dict's key t if that key exists. If it doesn't, it will bind an empty list to the key t and return it. So either way, a list will be there that the .append method can then append the tuple c to.\n",
"dict=[] //it's not a dict, it's a list, the dictionary is dict={}\nelem=[1,2,3]\ndict.append(elem)\n\nyou can access the single element in this way:\nprint dict[0] // 0 is the index\n\nthe output will be:\n[1, 2, 3]\n\n",
"In the case your data is not already sorted by desired criteria, here's the code that might help to group the data:\n#!/usr/bin/env python\n\"\"\"\n$ cat data_shuffled.txt\n0,2,7\n1,4,7\n0,4,7\n1,9,0\n1,2,5\n0,6,7\n1,6,8\n0,9,5\n\"\"\"\nfrom itertools import groupby\nfrom operator import itemgetter\n\n# load the data and make sure it is sorted by the first column\nsortby_key = itemgetter(0)\ndata = sorted((map(int, line.split(',')) for line in open('data_shuffled.txt')),\n key=sortby_key)\n\n# group by the first column\ngrouped_data = []\nfor key, group in groupby(data, key=sortby_key):\n assert key == len(grouped_data) # assume the first column is 0,1, ...\n grouped_data.append([trio[1:] for trio in group])\n\n# print the data\nfor i, pairs in enumerate(grouped_data):\n print i, pairs\n\nOutput:\n0 [[2, 7], [4, 7], [6, 7], [9, 5]]\n1 [[4, 7], [9, 0], [2, 5], [6, 8]]\n\n"
] | [
73,
12,
1,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0000327534_dictionary_list_python.txt |
Q:
Integer (representing a sequence of bits) reinterpretation as Character Array in Python
I've written some C code that I would like to port to python, as I feel python is a better 'concept' language.
In my C code, I use memory reinterpretation to achieve my goals, for example:
sizeof(int) is 4 byte
sizeof(char) is 1 byte
char c[4]={0x01,0x30,0x00,0x80};
int* i=(int*)c;
*i has the value 0x80003001
similarly if i have:
int* j = (int*)malloc(sizeof(int));
char* c = (char*)j;
*j = 0x78FF00AA;
c is now {0xAA, 0x00, 0xFF, 0x78}
I would like to do a similar thing in python, I realise that I can use bit operations to accomplish this:
chararray=[]
num=1234567890
size=8
while len(chararray) < size:
char = chr( (num & 255 ) )
num = num >> 8
chararray.append(char)
However I was hoping there would be a faster way of accomplishing this.
Does python have anything similar to C's union?
A:
You can use the struct module:
import struct
# Pack a Python long as if it was a C unsigned integer, little endian
bytes = struct.pack("<I", 0x78FF00AA)
print [hex(ord(byte)) for byte in bytes]
['0xaa', '0x0', '0xff', '0x78']
Read the documentation page to find about datatypes, and pay attention to endianness.
| Integer (representing a sequence of bits) reinterpretation as Character Array in Python | I've written some C code that I would like to port to python, as I feel python is a better 'concept' language.
In my C code, I use memory reinterpretation to achieve my goals, for example:
sizeof(int) is 4 byte
sizeof(char) is 1 byte
char c[4]={0x01,0x30,0x00,0x80};
int* i=(int*)c;
*i has the value 0x80003001
similarly if i have:
int* j = (int*)malloc(sizeof(int));
char* c = (char*)j;
*j = 0x78FF00AA;
c is now {0xAA, 0x00, 0xFF, 0x78}
I would like to do a similar thing in python, I realise that I can use bit operations to accomplish this:
chararray=[]
num=1234567890
size=8
while len(chararray) < size:
char = chr( (num & 255 ) )
num = num >> 8
chararray.append(char)
However I was hoping there would be a faster way of accomplishing this.
Does python have anything similar to C's union?
| [
"You can use the struct module:\nimport struct\n\n# Pack a Python long as if it was a C unsigned integer, little endian\nbytes = struct.pack(\"<I\", 0x78FF00AA)\nprint [hex(ord(byte)) for byte in bytes]\n\n['0xaa', '0x0', '0xff', '0x78']\n\nRead the documentation page to find about datatypes, and pay attention to endianness.\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0000333097_python.txt |
Q:
Deploying a python application with shared package
I'm thinking how to arrange a deployed python application which will have a
Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in
A library installed to wherever the current site-packages directory is.
Now, currently, I have the following directory structure in my sources:
foo.py
foo/
__init__.py
...
which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.
So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...
Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?
A:
This article is pretty good, and shows you a good way to do it. The second item from the Do list answers your question.
shameless copy paste:
Filesystem structure of a Python project
by Jp Calderone
Do:
name the directory something related to your project. For example, if your
project is named "Twisted", name the
top-level directory for its source
files Twisted. When you do releases,
you should include a version number
suffix: Twisted-2.5.
create a directory Twisted/bin and put your executables there, if you
have any. Don't give them a .py
extension, even if they are Python
source files. Don't put any code in
them except an import of and call to a
main function defined somewhere else
in your projects.
If your project is expressable as a single Python source file, then put it
into the directory and name it
something related to your project. For
example, Twisted/twisted.py. If you
need multiple source files, create a
package instead (Twisted/twisted/,
with an empty
Twisted/twisted/__init__.py) and place
your source files in it. For example,
Twisted/twisted/internet.py.
put your unit tests in a sub-package of your package (note - this means
that the single Python source file
option above was a trick - you always
need at least one other file for your
unit tests). For example,
Twisted/twisted/test/. Of course, make
it a package with
Twisted/twisted/test/__init__.py.
Place tests in files like
Twisted/twisted/test/test_internet.py.
add Twisted/README and Twisted/setup.py to explain and
install your software, respectively,
if you're feeling nice.
Don't:
put your source in a directory called src or lib. This makes it hard
to run without installing.
put your tests outside of your Python package. This makes it hard to
run the tests against an installed
version.
create a package that only has a __init__.py and then put all your code into __init__.py. Just make a module
instead of a package, it's simpler.
try to come up with magical hacks to make Python able to import your module
or package without having the user add
the directory containing it to their
import path (either via PYTHONPATH or
some other mechanism). You will not
correctly handle all cases and users
will get angry at you when your
software doesn't work in their
environment.
A:
Distutils supports installing modules, packages, and scripts. If you create a distutils setup.py which refers to foo as a package and foo.py as a script, then foo.py should get installed to /usr/local/bin or whatever the appropriate script install path is on the target OS, and the foo package should get installed to the site_packages directory.
A:
You should call the executable just foo, not foo.py, then attempts to import foo will not use it.
As for naming it properly: this is difficult to answer in the abstract; we would need to know what specifically it does. For example, if it configures and controls, calling it -config or ctl might be appropriate. If it is a shell API for the library, it should have the same name as the library.
A:
Your CLI module is one thing, the package that supports it is another thing. Don't confuse the names withe module foo (in a file foo.py) and the package foo (in a directory foo with a file __init__.py).
You have two things named foo: a module and a package. What else do you want to name foo? A class? A function? A variable?
Pick a distinctive name for the foo module or the foo package. foolib, for example, is a popular package name.
| Deploying a python application with shared package | I'm thinking how to arrange a deployed python application which will have a
Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in
A library installed to wherever the current site-packages directory is.
Now, currently, I have the following directory structure in my sources:
foo.py
foo/
__init__.py
...
which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.
So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...
Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?
| [
"This article is pretty good, and shows you a good way to do it. The second item from the Do list answers your question.\nshameless copy paste:\n\nFilesystem structure of a Python project\nby Jp Calderone\nDo:\n\nname the directory something related to your project. For example, if your\n project is named \"Twisted\", name the\n top-level directory for its source\n files Twisted. When you do releases,\n you should include a version number\n suffix: Twisted-2.5.\ncreate a directory Twisted/bin and put your executables there, if you\n have any. Don't give them a .py\n extension, even if they are Python\n source files. Don't put any code in\n them except an import of and call to a\n main function defined somewhere else\n in your projects.\nIf your project is expressable as a single Python source file, then put it\n into the directory and name it\n something related to your project. For\n example, Twisted/twisted.py. If you\n need multiple source files, create a\n package instead (Twisted/twisted/,\n with an empty\n Twisted/twisted/__init__.py) and place\n your source files in it. For example,\n Twisted/twisted/internet.py.\nput your unit tests in a sub-package of your package (note - this means\n that the single Python source file\n option above was a trick - you always\n need at least one other file for your\n unit tests). For example,\n Twisted/twisted/test/. Of course, make\n it a package with\n Twisted/twisted/test/__init__.py.\n Place tests in files like\n Twisted/twisted/test/test_internet.py.\nadd Twisted/README and Twisted/setup.py to explain and\n install your software, respectively,\n if you're feeling nice.\n\nDon't:\n\nput your source in a directory called src or lib. This makes it hard\n to run without installing.\nput your tests outside of your Python package. This makes it hard to\n run the tests against an installed\n version.\ncreate a package that only has a __init__.py and then put all your code into __init__.py. Just make a module\n instead of a package, it's simpler.\ntry to come up with magical hacks to make Python able to import your module\n or package without having the user add\n the directory containing it to their\n import path (either via PYTHONPATH or\n some other mechanism). You will not\n correctly handle all cases and users\n will get angry at you when your\n software doesn't work in their\n environment.\n\n\n",
"Distutils supports installing modules, packages, and scripts. If you create a distutils setup.py which refers to foo as a package and foo.py as a script, then foo.py should get installed to /usr/local/bin or whatever the appropriate script install path is on the target OS, and the foo package should get installed to the site_packages directory.\n",
"You should call the executable just foo, not foo.py, then attempts to import foo will not use it.\nAs for naming it properly: this is difficult to answer in the abstract; we would need to know what specifically it does. For example, if it configures and controls, calling it -config or ctl might be appropriate. If it is a shell API for the library, it should have the same name as the library.\n",
"Your CLI module is one thing, the package that supports it is another thing. Don't confuse the names withe module foo (in a file foo.py) and the package foo (in a directory foo with a file __init__.py).\nYou have two things named foo: a module and a package. What else do you want to name foo? A class? A function? A variable?\nPick a distinctive name for the foo module or the foo package. foolib, for example, is a popular package name.\n"
] | [
5,
2,
0,
0
] | [] | [] | [
"conventions",
"deploying",
"naming",
"package",
"python"
] | stackoverflow_0000328568_conventions_deploying_naming_package_python.txt |
Q:
string.split(text) or text.split() : what's the difference?
There is one thing that I do not understand...
Imagine you have a text = "hello world" and you want to split it.
In some places I see people that want to split the text doing:
string.split(text)
In other places I see people just doing:
text.split()
What’s the difference? Why you do in one way or in the other way? Can you give me a theory explanation about that?
A:
Interestingly, the docstrings for the two are not completely the same in Python 2.5.1:
>>> import string
>>> help(string.split)
Help on function split in module string:
split(s, sep=None, maxsplit=-1)
split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
>>> help("".split)
Help on built-in function split:
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.
Digging deeper, you'll see that the two forms are completely equivalent, as string.split(s) actually calls s.split() (search for the split-functions).
A:
The string.split(stringobj) is a feature of the string module, which must be imported separately. Once upon a time, that was the only way to split a string. That's some old code you're looking at.
The stringobj.split() is a feature of a string object, stringobj, which is more recent than the string module. But pretty old, nonetheless. That's the current practice.
A:
An extra note: str is the string type, as S.Lott points out above. That means that these two forms:
'a b c'.split()
str.split('a b c')
# both return ['a', 'b', 'c']
...are equivalent, because str.split is the unbound method, while s.split is a bound method of a str object. In the second case, the string that gets passed in to str.split is used as self in the method.
This doesn't make much difference here, but it's an important feature of how Python's object system works.
More info about bound and unbound methods.
A:
Short answer: the string module was the only way to perform these operations before python 1.6 - they've since been added to strings as methods.
A:
Use whichever you like, but realize that str.split is the recommended way of doing it. :-)
string.split is a tad older method of doing the same thing.
str.split is a bit more efficient (since you don't have to import the string module or look up any names from it), but not enough to make a huge difference if you prefer string.split.
| string.split(text) or text.split() : what's the difference? | There is one thing that I do not understand...
Imagine you have a text = "hello world" and you want to split it.
In some places I see people that want to split the text doing:
string.split(text)
In other places I see people just doing:
text.split()
What’s the difference? Why you do in one way or in the other way? Can you give me a theory explanation about that?
| [
"Interestingly, the docstrings for the two are not completely the same in Python 2.5.1:\n>>> import string\n>>> help(string.split)\nHelp on function split in module string:\n\nsplit(s, sep=None, maxsplit=-1)\n split(s [,sep [,maxsplit]]) -> list of strings\n\n Return a list of the words in the string s, using sep as the\n delimiter string. If maxsplit is given, splits at no more than\n maxsplit places (resulting in at most maxsplit+1 words). If sep\n is not specified or is None, any whitespace string is a separator.\n\n (split and splitfields are synonymous)\n\n>>> help(\"\".split)\nHelp on built-in function split:\n\nsplit(...)\n S.split([sep [,maxsplit]]) -> list of strings\n\n Return a list of the words in the string S, using sep as the\n delimiter string. If maxsplit is given, at most maxsplit\n splits are done. If sep is not specified or is None, any\n whitespace string is a separator.\n\nDigging deeper, you'll see that the two forms are completely equivalent, as string.split(s) actually calls s.split() (search for the split-functions).\n",
"The string.split(stringobj) is a feature of the string module, which must be imported separately. Once upon a time, that was the only way to split a string. That's some old code you're looking at.\nThe stringobj.split() is a feature of a string object, stringobj, which is more recent than the string module. But pretty old, nonetheless. That's the current practice.\n",
"An extra note: str is the string type, as S.Lott points out above. That means that these two forms:\n'a b c'.split()\nstr.split('a b c')\n\n# both return ['a', 'b', 'c']\n\n...are equivalent, because str.split is the unbound method, while s.split is a bound method of a str object. In the second case, the string that gets passed in to str.split is used as self in the method.\nThis doesn't make much difference here, but it's an important feature of how Python's object system works.\nMore info about bound and unbound methods.\n",
"Short answer: the string module was the only way to perform these operations before python 1.6 - they've since been added to strings as methods.\n",
"Use whichever you like, but realize that str.split is the recommended way of doing it. :-)\nstring.split is a tad older method of doing the same thing.\nstr.split is a bit more efficient (since you don't have to import the string module or look up any names from it), but not enough to make a huge difference if you prefer string.split.\n"
] | [
21,
13,
5,
5,
1
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0000333706_python_split_string.txt |
Q:
getting redirect loop for admin_only decorator
I've made this decorator, which results in an infinite redirect loop.
The problem is this:
args[0].redirect(users.create_login_url(args[0].request.path))
It appears to be a perfectly valid URL. So why wouldn't it properly redirect?
def admin_only(handler, *args):
def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted to enter an authorized page')
return redirect_to_login
else:
return redirect_to_login
A:
It seems that you aren't defining your decorator properly.
A decorator is called only once every time you wrap a function with it; from then on the function that the decorator returned will be called. It seems that you (mistakenly) believe that the decorator function itself will be called every time.
Try something like this instead:
def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
def admin_only(handler):
def wrapped_handler(*args, **kwargs):
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted '
'to enter an authorized page')
return redirect_to_login(*args, **kwargs)
else:
return redirect_to_login(*args, **kwargs)
return wrapped_handler
Note that in the above code, the decorator just defines a new function and returns it, and this new function itself does the relevant checks.
A:
Are you sure proper status code is being sent, you can use live http headers add-on for firefox to check whether 301 or 303 is being sent or not.
A:
You should use firebug, or live http headers, or somesuch, to see what exactly is happening here. My guess: Your authorized() function is always returning false (even when a user is logged in), so it redirects to the login page, which (if the user is already logged in) immediately redirects the user back to your page, which redirects... you get the idea.
A:
The problem is actually when I use
return args[0].redirect(users.create_logout_url(args[0].request.uri))
This goes to the logout page, which then redirects to the current page. However, my logs show that the current page thinks I'm still logged in, even after the logging out is complete.
This is strange, since I haven't modified anything in the app engine users API.
| getting redirect loop for admin_only decorator | I've made this decorator, which results in an infinite redirect loop.
The problem is this:
args[0].redirect(users.create_login_url(args[0].request.path))
It appears to be a perfectly valid URL. So why wouldn't it properly redirect?
def admin_only(handler, *args):
def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted to enter an authorized page')
return redirect_to_login
else:
return redirect_to_login
| [
"It seems that you aren't defining your decorator properly.\nA decorator is called only once every time you wrap a function with it; from then on the function that the decorator returned will be called. It seems that you (mistakenly) believe that the decorator function itself will be called every time.\nTry something like this instead:\ndef redirect_to_login(*args, **kwargs):\n return args[0].redirect(users.create_login_url(args[0].request.path))\n\ndef admin_only(handler):\n def wrapped_handler(*args, **kwargs): \n user = users.get_current_user()\n if user:\n if authorized(user):\n return handler(args[0])\n else:\n logging.warning('An unauthorized user has attempted '\n 'to enter an authorized page')\n return redirect_to_login(*args, **kwargs)\n else:\n return redirect_to_login(*args, **kwargs)\n\n return wrapped_handler\n\nNote that in the above code, the decorator just defines a new function and returns it, and this new function itself does the relevant checks.\n",
"Are you sure proper status code is being sent, you can use live http headers add-on for firefox to check whether 301 or 303 is being sent or not.\n",
"You should use firebug, or live http headers, or somesuch, to see what exactly is happening here. My guess: Your authorized() function is always returning false (even when a user is logged in), so it redirects to the login page, which (if the user is already logged in) immediately redirects the user back to your page, which redirects... you get the idea.\n",
"The problem is actually when I use \nreturn args[0].redirect(users.create_logout_url(args[0].request.uri))\n\nThis goes to the logout page, which then redirects to the current page. However, my logs show that the current page thinks I'm still logged in, even after the logging out is complete.\nThis is strange, since I haven't modified anything in the app engine users API. \n"
] | [
2,
0,
0,
0
] | [] | [] | [
"decorator",
"google_app_engine",
"python",
"redirect"
] | stackoverflow_0000333487_decorator_google_app_engine_python_redirect.txt |
Q:
Now that Python 2.6 is out, what modules currently in the language should every programmer know about?
A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in Python 2.6), for instance, are found in the collections module.
The Library Documentation page will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it this way using Python!" unless the important features in the language are pointed out by the experienced developers.
I'm not specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.
A:
The most impressive new module is probably the multiprocessing module. First because it lets you execute functions in new processes just as easily and with roughly the same API as you would with the threading module. But more importantly because it introduces a lot of great classes for communicating between processes, such as a Queue class and a Lock class which are each used just like those objects would be in multithreaded code, as well as some other classes for sharing memory between processes.
You can find the documentation at http://docs.python.org/library/multiprocessing.html
A:
The new json module is a real boon to web programmers!! (It was known as simplejson before being merged into the standard library.)
It's ridiculously easy to use: json.dumps(obj) encodes a built-in-type Python object to a JSON string, while json.loads(string) decodes a JSON string into a Python object.
Really really handy.
A:
May be PEP 0631 and What's new in 2.6 can provide elements of answer. This last article explains the new features in Python 2.6, released on October 1 2008.
A:
Essential Libraries
The main challenge for an experienced programmer coming from another language to Python is figuring out how one language maps to another. Here are a few essential libraries and how they relate to Java equivalents.
os, os.path
Has functionality like in java.io.File, java.lang.Process, and others. But cleaner and more sophisticated, with a Unix flavor. Use os.path instead of os for higher-level functionality.
sys
Manipulate the sys.path (which is like the classpath), register exit handlers (like in java Runtime object), and access the standard I/O streams, as in java.lang.System.
unittest
Very similar (and based on) jUnit, with test fixtures and runnable harnesses.
logging
Functionality almost identical to log4j with loglevels and loggers. ( logging is also in the standard java.util.Logging library)
datetime
Allows parsing and formatting dates and times, like in java.text.DateFormat, java.util.Date and related.
ConfigParser
Allows persistant configuration as in a java Properties file (but also allows nesting). Use this when you don't want the complexity of XML or a database backend.
socket, urllib
Similar functionality to what is in java.net, for working with either sockets, or retrieving content via URLs/URIs.
Also, keep in mind that a lot of basic functionality, such as reading files, and working with collections, is in the core python language, whereas in Java it lives in packages.
| Now that Python 2.6 is out, what modules currently in the language should every programmer know about? | A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in Python 2.6), for instance, are found in the collections module.
The Library Documentation page will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it this way using Python!" unless the important features in the language are pointed out by the experienced developers.
I'm not specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.
| [
"The most impressive new module is probably the multiprocessing module. First because it lets you execute functions in new processes just as easily and with roughly the same API as you would with the threading module. But more importantly because it introduces a lot of great classes for communicating between processes, such as a Queue class and a Lock class which are each used just like those objects would be in multithreaded code, as well as some other classes for sharing memory between processes.\nYou can find the documentation at http://docs.python.org/library/multiprocessing.html\n",
"The new json module is a real boon to web programmers!! (It was known as simplejson before being merged into the standard library.)\nIt's ridiculously easy to use: json.dumps(obj) encodes a built-in-type Python object to a JSON string, while json.loads(string) decodes a JSON string into a Python object.\nReally really handy.\n",
"May be PEP 0631 and What's new in 2.6 can provide elements of answer. This last article explains the new features in Python 2.6, released on October 1 2008.\n",
"Essential Libraries\nThe main challenge for an experienced programmer coming from another language to Python is figuring out how one language maps to another. Here are a few essential libraries and how they relate to Java equivalents.\nos, os.path \n\nHas functionality like in java.io.File, java.lang.Process, and others. But cleaner and more sophisticated, with a Unix flavor. Use os.path instead of os for higher-level functionality.\nsys \n\nManipulate the sys.path (which is like the classpath), register exit handlers (like in java Runtime object), and access the standard I/O streams, as in java.lang.System. \nunittest \n\nVery similar (and based on) jUnit, with test fixtures and runnable harnesses.\nlogging \n\nFunctionality almost identical to log4j with loglevels and loggers. ( logging is also in the standard java.util.Logging library)\ndatetime \n\nAllows parsing and formatting dates and times, like in java.text.DateFormat, java.util.Date and related.\nConfigParser \n\nAllows persistant configuration as in a java Properties file (but also allows nesting). Use this when you don't want the complexity of XML or a database backend.\nsocket, urllib \n\nSimilar functionality to what is in java.net, for working with either sockets, or retrieving content via URLs/URIs.\nAlso, keep in mind that a lot of basic functionality, such as reading files, and working with collections, is in the core python language, whereas in Java it lives in packages. \n"
] | [
12,
6,
5,
3
] | [] | [] | [
"language_features",
"module",
"python"
] | stackoverflow_0000168727_language_features_module_python.txt |
Q:
How do I create trivial customized field types in Django models?
I'm trying to make some types in Django that map to standard Django types. The custom model field documentation goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.
For example, if I were storing playing cards, I want something like:
class Card(object):
""" A playing card. """
def as_number(self):
""" returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
return self.number + self.suit_rank() * 13
def __unicode(self): ...
def is_highest(self, other_cards, trump=None):...
def __init__(self, number, suit): ...
...
I want my models to have something like:
class my_game(models.Model):
ante = models.IntegerField()
bonus_card = Card() # Really stored as an models.IntegerField()
....
I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming init(). Does anyone have sample code or better documentation?
A:
I'd do this with a subclass of Django's PositiveIntegerField:
from django.db import models
class Card(object):
"""The ``Card`` class you described."""
...
class CardField(models.PositiveIntegerField):
__metaclass__ = models.SubfieldBase
def get_db_prep_value(self, value):
"""Return the ``int`` equivalent of ``value``."""
if value is None: return None
try:
int_value = value.as_number()
except AttributeError:
int_value = int(value)
return int_value
def to_python(self, value):
"""Return the ``Card`` equivalent of ``value``."""
if value is None or isinstance(value, Card):
return value
return Card(int(value))
The get_db_prep_value method is responsible for converting value into something suitable for interacting with the database, in this case either an int or None.
The to_python method does the reverse, converting value into a Card. Just like before, you'll need to handle the possibility of None as a value. Using the SubfieldBase ensures that to_python is called every time a value is assigned to the field.
A:
Why can't you do something like the following?
class Card(models.Model):
""" A playing card. """
self.suit = models.PositiveIntegerField()
self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES )
def as_number(self):
""" returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
return self.number + self.suit * 13
def __unicode__(self):
return ...
def is_highest(self, other_cards, trump=None):...
Certainly, this is quite simple, and fits comfortably with what Django does naturally.
A:
Don't be afraid to adapt the model classes in Django to your own needs. There's nothing magical about them. And I guess this is the Right Place for this code: In the model.
| How do I create trivial customized field types in Django models? | I'm trying to make some types in Django that map to standard Django types. The custom model field documentation goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.
For example, if I were storing playing cards, I want something like:
class Card(object):
""" A playing card. """
def as_number(self):
""" returns a number from 1 (Ace of Clubs) and 52 (King of Spades)."""
return self.number + self.suit_rank() * 13
def __unicode(self): ...
def is_highest(self, other_cards, trump=None):...
def __init__(self, number, suit): ...
...
I want my models to have something like:
class my_game(models.Model):
ante = models.IntegerField()
bonus_card = Card() # Really stored as an models.IntegerField()
....
I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming init(). Does anyone have sample code or better documentation?
| [
"I'd do this with a subclass of Django's PositiveIntegerField:\nfrom django.db import models\n\nclass Card(object):\n \"\"\"The ``Card`` class you described.\"\"\"\n ...\n\nclass CardField(models.PositiveIntegerField):\n __metaclass__ = models.SubfieldBase\n\n def get_db_prep_value(self, value):\n \"\"\"Return the ``int`` equivalent of ``value``.\"\"\"\n if value is None: return None\n try:\n int_value = value.as_number()\n except AttributeError:\n int_value = int(value)\n return int_value\n\n def to_python(self, value):\n \"\"\"Return the ``Card`` equivalent of ``value``.\"\"\"\n if value is None or isinstance(value, Card):\n return value\n return Card(int(value))\n\nThe get_db_prep_value method is responsible for converting value into something suitable for interacting with the database, in this case either an int or None.\nThe to_python method does the reverse, converting value into a Card. Just like before, you'll need to handle the possibility of None as a value. Using the SubfieldBase ensures that to_python is called every time a value is assigned to the field.\n",
"Why can't you do something like the following?\nclass Card(models.Model):\n \"\"\" A playing card. \"\"\"\n self.suit = models.PositiveIntegerField()\n self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES )\n def as_number(self):\n \"\"\" returns a number from 1 (Ace of Clubs) and 52 (King of Spades).\"\"\"\n return self.number + self.suit * 13\n def __unicode__(self):\n return ...\n def is_highest(self, other_cards, trump=None):...\n\nCertainly, this is quite simple, and fits comfortably with what Django does naturally.\n",
"Don't be afraid to adapt the model classes in Django to your own needs. There's nothing magical about them. And I guess this is the Right Place for this code: In the model.\n"
] | [
4,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000334992_django_django_models_python.txt |
Q:
How to generate a filmstrip image in python from a folder of images?
I would like to do the equivalent off this (ruby code) in python for a Django project I am working on. I want to make a filmstrip image of X number of images in a folder.
A:
Do you mnean something like this? Use PIL to make a "contact sheet" of images?
Perhaps there are others here that are closer to what you want: http://code.activestate.com/recipes/tags/graphics/
A:
Here is a function that wraps the contact sheet function S.Lott mentioned.
#!/usr/bin/env python
import os, os.path
from contactsheet import make_contact_sheet
def make_film_strip(fnames,
(photow,photoh),
(marl,mart,marr,marb),
padding):
return make_contact_sheet(fnames,
(1, len(fnames)),
(photow,photoh),
(marl,mart,marr,marb),
padding)
It is assuming the recipe is saved as contactsheet.py. Usage is:
fstrip = filmstrip.make_film_strip(filmstrip.fnames, (120, 120), (0,0,0,0), 0)
fstrip.save('/path/to/file.format')
Tested.
| How to generate a filmstrip image in python from a folder of images? | I would like to do the equivalent off this (ruby code) in python for a Django project I am working on. I want to make a filmstrip image of X number of images in a folder.
| [
"Do you mnean something like this? Use PIL to make a \"contact sheet\" of images?\nPerhaps there are others here that are closer to what you want: http://code.activestate.com/recipes/tags/graphics/\n",
"Here is a function that wraps the contact sheet function S.Lott mentioned.\n#!/usr/bin/env python\n\nimport os, os.path\nfrom contactsheet import make_contact_sheet\n\ndef make_film_strip(fnames,\n (photow,photoh),\n (marl,mart,marr,marb),\n padding):\n return make_contact_sheet(fnames,\n (1, len(fnames)),\n (photow,photoh),\n (marl,mart,marr,marb),\n padding)\n\nIt is assuming the recipe is saved as contactsheet.py. Usage is:\nfstrip = filmstrip.make_film_strip(filmstrip.fnames, (120, 120), (0,0,0,0), 0)\nfstrip.save('/path/to/file.format')\n\nTested.\n"
] | [
4,
1
] | [] | [] | [
"django",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0000334827_django_image_python_python_imaging_library.txt |
Q:
How to complete this python function to save in the same folder?
I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.
I have this code now, which should be pretty much ok, but propably needs some modification:
import os
import Image
def filmstripOfImages():
imgpath = '/path/here/'
files = glob.glob(imgpath + '*.jpg')
imgwidth = files[0].size[0]
imgheight = files[0].size[1]
totalheight = imgheight * len(files)
filename = 'filmstrip.jpg'
filmstrip_url = imgpath + filename
# Create the new image. The background doesn't have to be white
white = (255,255,255)
filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)
row = 0
for file in files:
img = Image.open(file)
left = 0
right = left + imgwidth
upper = row*imgheight
lower = upper + imgheight
box = (left,upper,right,lower)
row += 1
filmstripimage.paste(img, box)
try:
filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
except:
filmstripimage.save(miniature_filename, 'jpg', quality=90)")
How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?
Related question: How to generate a filmstrip image in python from a folder of images?
A:
It is not an answer to your question, but It might be helpful:
#!/usr/bin/env python
from PIL import Image
def makefilmstrip(images, mode='RGB', color='white'):
"""Return a combined (filmstripped, each on top of the other) image of the images.
"""
width = max(img.size[0] for img in images)
height = sum(img.size[1] for img in images)
image = Image.new(mode, (width, height), color)
left, upper = 0, 0
for img in images:
image.paste(img, (left, upper))
upper += img.size[1]
return image
if __name__=='__main__':
# Here's how it could be used:
from glob import glob
from optparse import OptionParser
# process command-line args
parser = OptionParser()
parser.add_option("-o", "--output", dest="file",
help="write combined image to OUTPUT")
options, filepatterns = parser.parse_args()
outfilename = options.file
filenames = []
for files in map(glob, filepatterns):
if files:
filenames += files
# construct image
images = map(Image.open, filenames)
img = makefilmstrip(images)
img.save(outfilename)
Example:
$ python filmstrip.py -o output.jpg *.jpg
A:
I think if you change your try section to this:
filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)
A:
In the case you are not joking there are several problems with your script e.g. glob.glob() returns list of filenames (string objects, not Image objects) therefore files[0].size[0] will not work.
A:
as J. F. Sebastian mentioned, glob does not return image objects... but also:
As it is right now, the script assumes the images in the folder are all the same size and shape. This is not often a safe assumption to make.
So for both of those reasons, you'll need to open the images before you can determine their size. Once you open it you should set the width, and scale the images to that width so there is no empty space.
Also, you didn't set miniature_filename anywhere in the script.
| How to complete this python function to save in the same folder? | I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.
I have this code now, which should be pretty much ok, but propably needs some modification:
import os
import Image
def filmstripOfImages():
imgpath = '/path/here/'
files = glob.glob(imgpath + '*.jpg')
imgwidth = files[0].size[0]
imgheight = files[0].size[1]
totalheight = imgheight * len(files)
filename = 'filmstrip.jpg'
filmstrip_url = imgpath + filename
# Create the new image. The background doesn't have to be white
white = (255,255,255)
filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)
row = 0
for file in files:
img = Image.open(file)
left = 0
right = left + imgwidth
upper = row*imgheight
lower = upper + imgheight
box = (left,upper,right,lower)
row += 1
filmstripimage.paste(img, box)
try:
filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
except:
filmstripimage.save(miniature_filename, 'jpg', quality=90)")
How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?
Related question: How to generate a filmstrip image in python from a folder of images?
| [
"It is not an answer to your question, but It might be helpful:\n#!/usr/bin/env python\nfrom PIL import Image\n\ndef makefilmstrip(images, mode='RGB', color='white'):\n \"\"\"Return a combined (filmstripped, each on top of the other) image of the images.\n\n \"\"\"\n width = max(img.size[0] for img in images)\n height = sum(img.size[1] for img in images)\n \n image = Image.new(mode, (width, height), color) \n \n left, upper = 0, 0\n for img in images:\n image.paste(img, (left, upper))\n upper += img.size[1]\n\n return image\n\nif __name__=='__main__':\n # Here's how it could be used:\n from glob import glob\n from optparse import OptionParser\n\n # process command-line args\n parser = OptionParser()\n parser.add_option(\"-o\", \"--output\", dest=\"file\",\n help=\"write combined image to OUTPUT\")\n\n options, filepatterns = parser.parse_args()\n outfilename = options.file\n \n filenames = []\n for files in map(glob, filepatterns):\n if files:\n filenames += files\n\n # construct image\n images = map(Image.open, filenames) \n img = makefilmstrip(images)\n img.save(outfilename) \n\nExample:\n$ python filmstrip.py -o output.jpg *.jpg\n\n",
"I think if you change your try section to this:\nfilmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)\n\n",
"In the case you are not joking there are several problems with your script e.g. glob.glob() returns list of filenames (string objects, not Image objects) therefore files[0].size[0] will not work.\n",
"as J. F. Sebastian mentioned, glob does not return image objects... but also:\nAs it is right now, the script assumes the images in the folder are all the same size and shape. This is not often a safe assumption to make.\nSo for both of those reasons, you'll need to open the images before you can determine their size. Once you open it you should set the width, and scale the images to that width so there is no empty space.\nAlso, you didn't set miniature_filename anywhere in the script.\n"
] | [
2,
1,
1,
1
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0000335896_image_processing_python_python_imaging_library.txt |
Q:
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.
#!/bin/bash
cd /Users/stuartcw/Documents/Wiki/moin-1.7.2
/usr/bin/python wikiserver.py >> logs/`date +"%d%b%Y"`.log 2>&1 &
I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.
A:
Try using launchd. More info at http://www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself
A:
launchd is one of the best parts of MacOS X, and it causes me great pain to not be able to find it on other systems.
Edit and place this in /Library/LaunchDaemons as com.you.wiki.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.you.wiki</string>
<key>LowPriorityIO</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>RunAtLoad</key>
<true/>
<key>Nice</key>
<integer>1</integer>
<key>WorkingDirectory</key>
<string>/Users/stuartcw/Documents/Wiki/moin-1.7.2</string>
<key>UserName</key>
<string>user to run this as</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/python</string>
<string>wikiserver.py</string>
</array>
</dict>
</plist>
A:
Some helpful links:
Mac OS X: Creating a login hook
Making Shell Scripts Start at Login or System Startup
See also Lingon for a front end, should you decide to use Launchd instead.
A:
I don't know much about it, since I don't use login items. Just a suggestion, maybe try with applescript that calls those shell commands, and put that in Login Items.
| Shell Script doesn't run automatically though it is registered in Mac OS X Login Items | I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.
#!/bin/bash
cd /Users/stuartcw/Documents/Wiki/moin-1.7.2
/usr/bin/python wikiserver.py >> logs/`date +"%d%b%Y"`.log 2>&1 &
I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.
| [
"Try using launchd. More info at http://www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself\n",
"launchd is one of the best parts of MacOS X, and it causes me great pain to not be able to find it on other systems.\nEdit and place this in /Library/LaunchDaemons as com.you.wiki.plist\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>com.you.wiki</string>\n <key>LowPriorityIO</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>RunAtLoad</key>\n <true/>\n <key>Nice</key>\n <integer>1</integer>\n <key>WorkingDirectory</key>\n <string>/Users/stuartcw/Documents/Wiki/moin-1.7.2</string> \n <key>UserName</key>\n <string>user to run this as</string>\n <key>ProgramArguments</key>\n <array>\n <string>/usr/bin/python</string>\n <string>wikiserver.py</string>\n </array>\n</dict>\n</plist>\n\n",
"Some helpful links:\nMac OS X: Creating a login hook\n Making Shell Scripts Start at Login or System Startup\nSee also Lingon for a front end, should you decide to use Launchd instead.\n",
"I don't know much about it, since I don't use login items. Just a suggestion, maybe try with applescript that calls those shell commands, and put that in Login Items.\n"
] | [
4,
4,
3,
1
] | [] | [] | [
"bash",
"launchd",
"macos",
"moinmoin",
"python"
] | stackoverflow_0000335891_bash_launchd_macos_moinmoin_python.txt |
Q:
How would you design a very "Pythonic" UI framework?
I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)
Shoes takes things from web devlopment (like #f0c2f0 style colour notation, CSS layout techniques, like :margin => 10), and from ruby (extensively using blocks in sensible ways)
Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
No where near as clean, and wouldn't be nearly as flexible, and I'm not even sure if it would be implementable.
Using decorators seems like an interesting way to map blocks of code to a specific action:
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.
The scope of various stuff (say, the la label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..
A:
You could actually pull this off, but it would require using metaclasses, which are deep magic (there be dragons). If you want an intro to metaclasses, there's a series of articles from IBM which manage to introduce the ideas without melting your brain.
The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.
A:
I was never satisfied with David Mertz's articles at IBM on metaclsses so I recently wrote my own metaclass article. Enjoy.
A:
This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new "with" statement.
with Shoes():
t = Para("Not clicked!")
with Button("The Label"):
Alert("You clicked the button!")
t.replace("Clicked!")
The hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...
Anyway, here's the backend code I ran this with:
context = None
class Nestable(object):
def __init__(self,caption=None):
self.caption = caption
self.things = []
global context
if context:
context.add(self)
def __enter__(self):
global context
self.parent = context
context = self
def __exit__(self, type, value, traceback):
global context
context = self.parent
def add(self,thing):
self.things.append(thing)
print "Adding a %s to %s" % (thing,self)
def __str__(self):
return "%s(%s)" % (self.__class__.__name__, self.caption)
class Shoes(Nestable):
pass
class Button(Nestable):
pass
class Alert(Nestable):
pass
class Para(Nestable):
def replace(self,caption):
Command(self,"replace",caption)
class Command(Nestable):
def __init__(self, target, command, caption):
self.command = command
self.target = target
Nestable.__init__(self,caption)
def __str__(self):
return "Command(%s text of %s with \"%s\")" % (self.command, self.target, self.caption)
def execute(self):
self.target.caption = self.caption
A:
## All you need is this class:
class MainWindow(Window):
my_button = Button('Click Me')
my_paragraph = Text('This is the text you wish to place')
my_alert = AlertBox('What what what!!!')
@my_button.clicked
def my_button_clicked(self, button, event):
self.my_paragraph.text.append('And now you clicked on it, the button that is.')
@my_paragraph.text.changed
def my_paragraph_text_changed(self, text, event):
self.button.text = 'No more clicks!'
@my_button.text.changed
def my_button_text_changed(self, text, event):
self.my_alert.show()
## The Style class is automatically gnerated by the framework
## but you can override it by defining it in the class:
##
## class MainWindow(Window):
## class Style:
## my_blah = {'style-info': 'value'}
##
## or like you see below:
class Style:
my_button = {
'background-color': '#ccc',
'font-size': '14px'}
my_paragraph = {
'background-color': '#fff',
'color': '#000',
'font-size': '14px',
'border': '1px solid black',
'border-radius': '3px'}
MainWindow.Style = Style
## The layout class is automatically generated
## by the framework but you can override it by defining it
## in the class, same as the Style class above, or by
## defining it like this:
class MainLayout(Layout):
def __init__(self, style):
# It takes the custom or automatically generated style class upon instantiation
style.window.pack(HBox().pack(style.my_paragraph, style.my_button))
MainWindow.Layout = MainLayout
if __name__ == '__main__':
run(App(main=MainWindow))
It would be relatively easy to do in python with a bit of that metaclass python magic know how. Which I have. And a knowledge of PyGTK. Which I also have. Gets ideas?
A:
With some Metaclass magic to keep the ordering I have the following working. I'm not sure how pythonic it is but it is good fun for creating simple things.
class w(Wndw):
title='Hello World'
class txt(Txt): # either a new class
text='Insert name here'
lbl=Lbl(text='Hello') # or an instance
class greet(Bbt):
text='Greet'
def click(self): #on_click method
self.frame.lbl.text='Hello %s.'%self.frame.txt.text
app=w()
A:
The only attempt to do this that I know of is Hans Nowak's Wax (which is unfortunately dead).
A:
The closest you can get to rubyish blocks is the with statement from pep343:
http://www.python.org/dev/peps/pep-0343/
A:
If you use PyGTK with glade and this glade wrapper, then PyGTK actually becomes somewhat pythonic. A little at least.
Basically, you create the GUI layout in Glade. You also specify event callbacks in glade. Then you write a class for your window like this:
class MyWindow(GladeWrapper):
GladeWrapper.__init__(self, "my_glade_file.xml", "mainWindow")
self.GtkWindow.show()
def button_click_event (self, *args):
self.button1.set_label("CLICKED")
Here, I'm assuming that I have a GTK Button somewhere called button1 and that I specified button_click_event as the clicked callback. The glade wrapper takes a lot of effort out of event mapping.
If I were to design a Pythonic GUI library, I would support something similar, to aid rapid development. The only difference is that I would ensure that the widgets have a more pythonic interface too. The current PyGTK classes seem very C to me, except that I use foo.bar(...) instead of bar(foo, ...) though I'm not sure exactly what I'd do differently. Probably allow for a Django models style declarative means of specifying widgets and events in code and allowing you to access data though iterators (where it makes sense, eg widget lists perhaps), though I haven't really thought about it.
A:
Maybe not as slick as the Ruby version, but how about something like this:
from Boots import App, Para, Button, alert
def Shoeless(App):
t = Para(text = 'Not Clicked')
b = Button(label = 'The label')
def on_b_clicked(self):
alert('You clicked the button!')
self.t.text = 'Clicked!'
Like Justin said, to implement this you would need to use a custom metaclass on class App, and a bunch of properties on Para and Button. This actually wouldn't be too hard.
The problem you run into next is: how do you keep track of the order that things appear in the class definition? In Python 2.x, there is no way to know if t should be above b or the other way around, since you receive the contents of the class definition as a python dict.
However, in Python 3.0 metaclasses are being changed in a couple of (minor) ways. One of them is the __prepare__ method, which allows you to supply your own custom dictionary-like object to be used instead -- this means you'll be able to track the order in which items are defined, and position them accordingly in the window.
A:
This could be an oversimplification, i don't think it would be a good idea to try to make a general purpose ui library this way. On the other hand you could use this approach (metaclasses and friends) to simplify the definition of certain classes of user interfaces for an existing ui library and depending of the application that could actually save you a significant amount of time and code lines.
A:
I have this same problem. I wan to to create a wrapper around any GUI toolkit for Python that is easy to use, and inspired by Shoes, but needs to be a OOP approach (against ruby blocks).
More information in: http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited
Anyone's welcome to join the project.
A:
If you really want to code UI, you could try to get something similar to django's ORM; sth like this to get a simple help browser:
class MyWindow(Window):
class VBox:
entry = Entry()
bigtext = TextView()
def on_entry_accepted(text):
bigtext.value = eval(text).__doc__
The idea would be to interpret some containers (like windows) as simple classes, some containers (like tables, v/hboxes) recognized by object names, and simple widgets as objects.
I dont think one would have to name all containers inside a window, so some shortcuts (like old-style classes being recognized as widgets by names) would be desirable.
About the order of elements: in MyWindow above you don't have to track this (window is conceptually a one-slot container). In other containers you can try to keep track of the order assuming that each widget constructor have access to some global widget list. This is how it is done in django (AFAIK).
Few hacks here, few tweaks there... There are still few things to think of, but I believe it is possible... and usable, as long as you don't build complicated UIs.
However I am pretty happy with PyGTK+Glade. UI is just kind of data for me and it should be treated as data. There's just too much parameters to tweak (like spacing in different places) and it is better to manage that using a GUI tool. Therefore I build my UI in glade, save as xml and parse using gtk.glade.XML().
A:
Personally, I would try to implement JQuery like API in a GUI framework.
class MyWindow(Window):
contents = (
para('Hello World!'),
button('Click Me', id='ok'),
para('Epilog'),
)
def __init__(self):
self['#ok'].click(self.message)
self['para'].hover(self.blend_in, self.blend_out)
def message(self):
print 'You clicked!'
def blend_in(self, object):
object.background = '#333333'
def blend_out(self, object):
object.background = 'WindowBackground'
A:
Here's an approach that goes about GUI definitions a bit differently using class-based meta-programming rather than inheritance.
This is largley Django/SQLAlchemy inspired in that it is heavily based on meta-programming and separates your GUI code from your "code code". I also think it should make heavy use of layout managers like Java does because when you're dropping code, no one wants to constantly tweak pixel alignment. I also think it would be cool if we could have CSS-like properties.
Here is a rough brainstormed example that will show a column with a label on top, then a text box, then a button to click on the bottom which shows a message.
from happygui.controls import *
MAIN_WINDOW = Window(width="500px", height="350px",
my_layout=ColumnLayout(padding="10px",
my_label=Label(text="What's your name kiddo?", bold=True, align="center"),
my_edit=EditBox(placeholder=""),
my_btn=Button(text="CLICK ME!", on_click=Handler('module.file.btn_clicked')),
),
)
MAIN_WINDOW.show()
def btn_clicked(sender): # could easily be in a handlers.py file
name = MAIN_WINDOW.my_layout.my_edit.text
# same thing: name = sender.parent.my_edit.text
# best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text
MessageBox("Your name is '%s'" % ()).show(modal=True)
One cool thing to notice is the way you can reference the input of my_edit by saying MAIN_WINDOW.my_layout.my_edit.text. In the declaration for the window, I think it's important to be able to arbitrarily name controls in the function kwargs.
Here is the same app only using absolute positioning (the controls will appear in different places because we're not using a fancy layout manager):
from happygui.controls import *
MAIN_WINDOW = Window(width="500px", height="350px",
my_label=Label(text="What's your name kiddo?", bold=True, align="center", x="10px", y="10px", width="300px", height="100px"),
my_edit=EditBox(placeholder="", x="10px", y="110px", width="300px", height="100px"),
my_btn=Button(text="CLICK ME!", on_click=Handler('module.file.btn_clicked'), x="10px", y="210px", width="300px", height="100px"),
)
MAIN_WINDOW.show()
def btn_clicked(sender): # could easily be in a handlers.py file
name = MAIN_WINDOW.my_edit.text
# same thing: name = sender.parent.my_edit.text
# best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text
MessageBox("Your name is '%s'" % ()).show(modal=True)
I'm not entirely sure yet if this is a super great approach, but I definitely think it's on the right path. I don't have time to explore this idea more, but if someone took this up as a project, I would love them.
A:
Declarative is not necessarily more (or less) pythonic than functional IMHO. I think a layered approach would be the best (from buttom up):
A native layer that accepts and returns python data types.
A functional dynamic layer.
One or more declarative/object-oriented layers.
Similar to Elixir + SQLAlchemy.
| How would you design a very "Pythonic" UI framework? | I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)
Shoes takes things from web devlopment (like #f0c2f0 style colour notation, CSS layout techniques, like :margin => 10), and from ruby (extensively using blocks in sensible ways)
Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
No where near as clean, and wouldn't be nearly as flexible, and I'm not even sure if it would be implementable.
Using decorators seems like an interesting way to map blocks of code to a specific action:
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.
The scope of various stuff (say, the la label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..
| [
"You could actually pull this off, but it would require using metaclasses, which are deep magic (there be dragons). If you want an intro to metaclasses, there's a series of articles from IBM which manage to introduce the ideas without melting your brain.\nThe source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.\n",
"I was never satisfied with David Mertz's articles at IBM on metaclsses so I recently wrote my own metaclass article. Enjoy.\n",
"This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new \"with\" statement.\nwith Shoes():\n t = Para(\"Not clicked!\")\n with Button(\"The Label\"):\n Alert(\"You clicked the button!\")\n t.replace(\"Clicked!\")\n\nThe hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...\nAnyway, here's the backend code I ran this with:\ncontext = None\n\nclass Nestable(object):\n def __init__(self,caption=None):\n self.caption = caption\n self.things = []\n\n global context\n if context:\n context.add(self)\n\n def __enter__(self):\n global context\n self.parent = context\n context = self\n\n def __exit__(self, type, value, traceback):\n global context\n context = self.parent\n\n def add(self,thing):\n self.things.append(thing)\n print \"Adding a %s to %s\" % (thing,self)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.caption)\n\n\nclass Shoes(Nestable):\n pass\n\nclass Button(Nestable):\n pass\n\nclass Alert(Nestable):\n pass\n\nclass Para(Nestable):\n def replace(self,caption):\n Command(self,\"replace\",caption)\n\nclass Command(Nestable):\n def __init__(self, target, command, caption):\n self.command = command\n self.target = target\n Nestable.__init__(self,caption)\n\n def __str__(self):\n return \"Command(%s text of %s with \\\"%s\\\")\" % (self.command, self.target, self.caption)\n\n def execute(self):\n self.target.caption = self.caption\n\n",
"## All you need is this class:\n\nclass MainWindow(Window):\n my_button = Button('Click Me')\n my_paragraph = Text('This is the text you wish to place')\n my_alert = AlertBox('What what what!!!')\n\n @my_button.clicked\n def my_button_clicked(self, button, event):\n self.my_paragraph.text.append('And now you clicked on it, the button that is.')\n\n @my_paragraph.text.changed\n def my_paragraph_text_changed(self, text, event):\n self.button.text = 'No more clicks!'\n\n @my_button.text.changed\n def my_button_text_changed(self, text, event):\n self.my_alert.show()\n\n\n## The Style class is automatically gnerated by the framework\n## but you can override it by defining it in the class:\n##\n## class MainWindow(Window):\n## class Style:\n## my_blah = {'style-info': 'value'}\n##\n## or like you see below:\n\nclass Style:\n my_button = {\n 'background-color': '#ccc',\n 'font-size': '14px'}\n my_paragraph = {\n 'background-color': '#fff',\n 'color': '#000',\n 'font-size': '14px',\n 'border': '1px solid black',\n 'border-radius': '3px'}\n\nMainWindow.Style = Style\n\n## The layout class is automatically generated\n## by the framework but you can override it by defining it\n## in the class, same as the Style class above, or by\n## defining it like this:\n\nclass MainLayout(Layout):\n def __init__(self, style):\n # It takes the custom or automatically generated style class upon instantiation\n style.window.pack(HBox().pack(style.my_paragraph, style.my_button))\n\nMainWindow.Layout = MainLayout\n\nif __name__ == '__main__':\n run(App(main=MainWindow))\n\nIt would be relatively easy to do in python with a bit of that metaclass python magic know how. Which I have. And a knowledge of PyGTK. Which I also have. Gets ideas?\n",
"With some Metaclass magic to keep the ordering I have the following working. I'm not sure how pythonic it is but it is good fun for creating simple things. \nclass w(Wndw):\n title='Hello World'\n class txt(Txt): # either a new class\n text='Insert name here'\n lbl=Lbl(text='Hello') # or an instance\n class greet(Bbt):\n text='Greet'\n def click(self): #on_click method\n self.frame.lbl.text='Hello %s.'%self.frame.txt.text\n\napp=w()\n\n",
"The only attempt to do this that I know of is Hans Nowak's Wax (which is unfortunately dead).\n",
"The closest you can get to rubyish blocks is the with statement from pep343: \nhttp://www.python.org/dev/peps/pep-0343/\n",
"If you use PyGTK with glade and this glade wrapper, then PyGTK actually becomes somewhat pythonic. A little at least.\nBasically, you create the GUI layout in Glade. You also specify event callbacks in glade. Then you write a class for your window like this:\nclass MyWindow(GladeWrapper):\n GladeWrapper.__init__(self, \"my_glade_file.xml\", \"mainWindow\")\n self.GtkWindow.show()\n\n def button_click_event (self, *args):\n self.button1.set_label(\"CLICKED\")\n\nHere, I'm assuming that I have a GTK Button somewhere called button1 and that I specified button_click_event as the clicked callback. The glade wrapper takes a lot of effort out of event mapping.\nIf I were to design a Pythonic GUI library, I would support something similar, to aid rapid development. The only difference is that I would ensure that the widgets have a more pythonic interface too. The current PyGTK classes seem very C to me, except that I use foo.bar(...) instead of bar(foo, ...) though I'm not sure exactly what I'd do differently. Probably allow for a Django models style declarative means of specifying widgets and events in code and allowing you to access data though iterators (where it makes sense, eg widget lists perhaps), though I haven't really thought about it.\n",
"Maybe not as slick as the Ruby version, but how about something like this:\nfrom Boots import App, Para, Button, alert\n\ndef Shoeless(App):\n t = Para(text = 'Not Clicked')\n b = Button(label = 'The label')\n\n def on_b_clicked(self):\n alert('You clicked the button!')\n self.t.text = 'Clicked!'\n\nLike Justin said, to implement this you would need to use a custom metaclass on class App, and a bunch of properties on Para and Button. This actually wouldn't be too hard.\nThe problem you run into next is: how do you keep track of the order that things appear in the class definition? In Python 2.x, there is no way to know if t should be above b or the other way around, since you receive the contents of the class definition as a python dict.\nHowever, in Python 3.0 metaclasses are being changed in a couple of (minor) ways. One of them is the __prepare__ method, which allows you to supply your own custom dictionary-like object to be used instead -- this means you'll be able to track the order in which items are defined, and position them accordingly in the window.\n",
"This could be an oversimplification, i don't think it would be a good idea to try to make a general purpose ui library this way. On the other hand you could use this approach (metaclasses and friends) to simplify the definition of certain classes of user interfaces for an existing ui library and depending of the application that could actually save you a significant amount of time and code lines.\n",
"I have this same problem. I wan to to create a wrapper around any GUI toolkit for Python that is easy to use, and inspired by Shoes, but needs to be a OOP approach (against ruby blocks).\nMore information in: http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited\nAnyone's welcome to join the project.\n",
"If you really want to code UI, you could try to get something similar to django's ORM; sth like this to get a simple help browser:\nclass MyWindow(Window):\n class VBox:\n entry = Entry()\n bigtext = TextView()\n\n def on_entry_accepted(text):\n bigtext.value = eval(text).__doc__\n\nThe idea would be to interpret some containers (like windows) as simple classes, some containers (like tables, v/hboxes) recognized by object names, and simple widgets as objects.\nI dont think one would have to name all containers inside a window, so some shortcuts (like old-style classes being recognized as widgets by names) would be desirable.\nAbout the order of elements: in MyWindow above you don't have to track this (window is conceptually a one-slot container). In other containers you can try to keep track of the order assuming that each widget constructor have access to some global widget list. This is how it is done in django (AFAIK).\nFew hacks here, few tweaks there... There are still few things to think of, but I believe it is possible... and usable, as long as you don't build complicated UIs.\nHowever I am pretty happy with PyGTK+Glade. UI is just kind of data for me and it should be treated as data. There's just too much parameters to tweak (like spacing in different places) and it is better to manage that using a GUI tool. Therefore I build my UI in glade, save as xml and parse using gtk.glade.XML().\n",
"Personally, I would try to implement JQuery like API in a GUI framework.\nclass MyWindow(Window):\n contents = (\n para('Hello World!'),\n button('Click Me', id='ok'),\n para('Epilog'),\n )\n\n def __init__(self):\n self['#ok'].click(self.message)\n self['para'].hover(self.blend_in, self.blend_out)\n\n def message(self):\n print 'You clicked!'\n\n def blend_in(self, object):\n object.background = '#333333'\n\n def blend_out(self, object):\n object.background = 'WindowBackground'\n\n",
"Here's an approach that goes about GUI definitions a bit differently using class-based meta-programming rather than inheritance.\nThis is largley Django/SQLAlchemy inspired in that it is heavily based on meta-programming and separates your GUI code from your \"code code\". I also think it should make heavy use of layout managers like Java does because when you're dropping code, no one wants to constantly tweak pixel alignment. I also think it would be cool if we could have CSS-like properties.\nHere is a rough brainstormed example that will show a column with a label on top, then a text box, then a button to click on the bottom which shows a message.\n\nfrom happygui.controls import *\n\nMAIN_WINDOW = Window(width=\"500px\", height=\"350px\",\n my_layout=ColumnLayout(padding=\"10px\",\n my_label=Label(text=\"What's your name kiddo?\", bold=True, align=\"center\"),\n my_edit=EditBox(placeholder=\"\"),\n my_btn=Button(text=\"CLICK ME!\", on_click=Handler('module.file.btn_clicked')),\n ),\n)\nMAIN_WINDOW.show()\n\ndef btn_clicked(sender): # could easily be in a handlers.py file\n name = MAIN_WINDOW.my_layout.my_edit.text\n # same thing: name = sender.parent.my_edit.text\n # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text\n MessageBox(\"Your name is '%s'\" % ()).show(modal=True)\n\nOne cool thing to notice is the way you can reference the input of my_edit by saying MAIN_WINDOW.my_layout.my_edit.text. In the declaration for the window, I think it's important to be able to arbitrarily name controls in the function kwargs.\nHere is the same app only using absolute positioning (the controls will appear in different places because we're not using a fancy layout manager):\n\nfrom happygui.controls import *\n\nMAIN_WINDOW = Window(width=\"500px\", height=\"350px\",\n my_label=Label(text=\"What's your name kiddo?\", bold=True, align=\"center\", x=\"10px\", y=\"10px\", width=\"300px\", height=\"100px\"),\n my_edit=EditBox(placeholder=\"\", x=\"10px\", y=\"110px\", width=\"300px\", height=\"100px\"),\n my_btn=Button(text=\"CLICK ME!\", on_click=Handler('module.file.btn_clicked'), x=\"10px\", y=\"210px\", width=\"300px\", height=\"100px\"),\n)\nMAIN_WINDOW.show()\n\ndef btn_clicked(sender): # could easily be in a handlers.py file\n name = MAIN_WINDOW.my_edit.text\n # same thing: name = sender.parent.my_edit.text\n # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text\n MessageBox(\"Your name is '%s'\" % ()).show(modal=True)\n\nI'm not entirely sure yet if this is a super great approach, but I definitely think it's on the right path. I don't have time to explore this idea more, but if someone took this up as a project, I would love them.\n",
"Declarative is not necessarily more (or less) pythonic than functional IMHO. I think a layered approach would be the best (from buttom up):\n\nA native layer that accepts and returns python data types.\nA functional dynamic layer.\nOne or more declarative/object-oriented layers.\n\nSimilar to Elixir + SQLAlchemy.\n"
] | [
7,
4,
4,
4,
3,
3,
3,
3,
2,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"frameworks",
"python",
"user_interface"
] | stackoverflow_0000058711_frameworks_python_user_interface.txt |
Q:
Python: smtpd (or alternative) for production mail receiving?
I'm looking to do various processing of email - eg. inspect the headers, and if they meet some criteria (look like spam), drop the connection, or inspect the recipient list and perform special filtering.
Looks like Python's smtpd library provides a nice and simple interface for processing the received email.
To deal with the message before it's fully processed (eg. to drop the message in case the headers look like spam), should I be using handle_connect? Are the internal APIs (other than process_message) documented somewhere? Example code anywhere?
Also, has anyone used smtpd in production? Any thoughts on reliability, etc?
Regarding Twisted: I've attempted to embrace Twisted several times and quite like the deferred model, but it's a bit too complex for my current taste. I'll give it another look, but for now I'm more interested in non-Twisted implementations.
A:
You may want to look at the twisted implementation as that will give you access to the full range of interaction with the client. I believe (though I have never used it in production) that twisted can be trusted in a production environment.
A:
Another approach: use Postfix for receiving email and write a policy script in Python.
| Python: smtpd (or alternative) for production mail receiving? | I'm looking to do various processing of email - eg. inspect the headers, and if they meet some criteria (look like spam), drop the connection, or inspect the recipient list and perform special filtering.
Looks like Python's smtpd library provides a nice and simple interface for processing the received email.
To deal with the message before it's fully processed (eg. to drop the message in case the headers look like spam), should I be using handle_connect? Are the internal APIs (other than process_message) documented somewhere? Example code anywhere?
Also, has anyone used smtpd in production? Any thoughts on reliability, etc?
Regarding Twisted: I've attempted to embrace Twisted several times and quite like the deferred model, but it's a bit too complex for my current taste. I'll give it another look, but for now I'm more interested in non-Twisted implementations.
| [
"You may want to look at the twisted implementation as that will give you access to the full range of interaction with the client. I believe (though I have never used it in production) that twisted can be trusted in a production environment.\n",
"Another approach: use Postfix for receiving email and write a policy script in Python.\n"
] | [
5,
1
] | [] | [] | [
"python",
"smtp",
"smtpd"
] | stackoverflow_0000335582_python_smtp_smtpd.txt |
Q:
Python: Invalid Token
Some of you may recognize this as Project Euler's problem number 11. The one with the grid.
I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why
grid = [
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ],
[ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ],
[ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ],
...
And I get this error:
File "D:\development\Python\ProjectEuler\p11.py", line 3
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ],
^ SyntaxError: invalid token
Why is it throwing an error before the comma?
A:
I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.
A:
Note that the "^" symbol in the error points exactly to the erroneous column. Together with the line number it points exactly on the digit 8. This can help lead you to what Jeremy suggested.
A:
Just remove leading zeros.
First zero makes number octal.
| Python: Invalid Token | Some of you may recognize this as Project Euler's problem number 11. The one with the grid.
I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why
grid = [
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ],
[ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ],
[ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ],
...
And I get this error:
File "D:\development\Python\ProjectEuler\p11.py", line 3
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ],
^ SyntaxError: invalid token
Why is it throwing an error before the comma?
| [
"I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.\n",
"Note that the \"^\" symbol in the error points exactly to the erroneous column. Together with the line number it points exactly on the digit 8. This can help lead you to what Jeremy suggested.\n",
"Just remove leading zeros.\nFirst zero makes number octal.\n"
] | [
40,
3,
1
] | [] | [] | [
"octal",
"python"
] | stackoverflow_0000336181_octal_python.txt |
Q:
Dynamic Keyword Arguments in Python?
Does python have the ability to create dynamic keywords?
For example:
qset.filter(min_price__usd__range=(min_price, max_price))
I want to be able to change the usd part based on a selected currency.
A:
Yes, It does. Use **kwargs in a function definition.
Example:
def f(**kwargs):
print kwargs.keys()
f(a=2, b="b") # -> ['a', 'b']
f(**{'d'+'e': 1}) # -> ['de']
But why do you need that?
A:
If I understand what you're asking correctly,
qset.filter(**{
'min_price_' + selected_currency + '_range' :
(min_price, max_price)})
does what you need.
A:
You can easily do this by declaring your function like this:
def filter(**kwargs):
your function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word kwargs is meaningless; the ** is what causes the dynamic keyword behavior.
You can also do the reverse. If you are calling a function, and you have a dictionary that corresponds to the arguments, you can do
someFunction(**theDictionary)
There is also the lesser used *foo variant, which causes you to receive an array of arguments. This is similar to normal C vararg arrays.
A:
Yes, sort of.
In your filter method you can declare a wildcard variable that collects all the unknown keyword arguments. Your method might look like this:
def filter(self, **kwargs):
for key,value in kwargs:
if key.startswith('min_price__') and key.endswith('__range'):
currency = key.replace('min_price__', '').replace('__range','')
rate = self.current_conversion_rates[currency]
self.setCurrencyRange(value[0]*rate, value[1]*rate)
| Dynamic Keyword Arguments in Python? | Does python have the ability to create dynamic keywords?
For example:
qset.filter(min_price__usd__range=(min_price, max_price))
I want to be able to change the usd part based on a selected currency.
| [
"Yes, It does. Use **kwargs in a function definition.\nExample:\ndef f(**kwargs):\n print kwargs.keys()\n\n\nf(a=2, b=\"b\") # -> ['a', 'b']\nf(**{'d'+'e': 1}) # -> ['de']\n\nBut why do you need that?\n",
"If I understand what you're asking correctly,\nqset.filter(**{\n 'min_price_' + selected_currency + '_range' :\n (min_price, max_price)})\n\ndoes what you need.\n",
"You can easily do this by declaring your function like this:\ndef filter(**kwargs):\n\nyour function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word kwargs is meaningless; the ** is what causes the dynamic keyword behavior.\nYou can also do the reverse. If you are calling a function, and you have a dictionary that corresponds to the arguments, you can do\nsomeFunction(**theDictionary)\n\nThere is also the lesser used *foo variant, which causes you to receive an array of arguments. This is similar to normal C vararg arrays.\n",
"Yes, sort of.\nIn your filter method you can declare a wildcard variable that collects all the unknown keyword arguments. Your method might look like this:\ndef filter(self, **kwargs):\n for key,value in kwargs:\n if key.startswith('min_price__') and key.endswith('__range'):\n currency = key.replace('min_price__', '').replace('__range','')\n rate = self.current_conversion_rates[currency]\n self.setCurrencyRange(value[0]*rate, value[1]*rate)\n\n"
] | [
64,
37,
14,
0
] | [] | [] | [
"python"
] | stackoverflow_0000337688_python.txt |
Q:
Django FormWizard and Admin application
I have a series of forms that I need a user to complete in sequence, which is perfect for the formwizard app. However, I've some need of the admin application also and would like to set the whole thing up to trigger several forms within the admin app.
Is it possible/easy to integrate a 'formwizard' into the admin application?
If not, is extending the admin template a viable option and hooking the rest up manually? Opinions?
Update:
Some clarity in my 'problem'.
I wanted to use the admin app as I was thinking I only needed basic modelforms - one perhaps split across many forms, which would have been the role of formwizard.
What I have:
Form 1: 10 yes/no questions (each yes corresponds to a new form that needs to be filled out)
if yes is ticked, the corresponding forms are put into a formwizard and displayed for the user to complete.
However the suggested option (modelforms + styling) would take care of the majority of my concerns I guess - and is the seemingly simpler solution.
A:
There's a lot that you can do, but you'd need to be more specific about what you mean by "integrate a formwizard into the admin app" and "trigger several forms within the admin app."
The admin app at its core is basically just a wrapper around a bunch of stock ModelForms, so if you just build a formwizard using ModelForms and slap the admin styling on it, you may be 80% of the way there.
| Django FormWizard and Admin application | I have a series of forms that I need a user to complete in sequence, which is perfect for the formwizard app. However, I've some need of the admin application also and would like to set the whole thing up to trigger several forms within the admin app.
Is it possible/easy to integrate a 'formwizard' into the admin application?
If not, is extending the admin template a viable option and hooking the rest up manually? Opinions?
Update:
Some clarity in my 'problem'.
I wanted to use the admin app as I was thinking I only needed basic modelforms - one perhaps split across many forms, which would have been the role of formwizard.
What I have:
Form 1: 10 yes/no questions (each yes corresponds to a new form that needs to be filled out)
if yes is ticked, the corresponding forms are put into a formwizard and displayed for the user to complete.
However the suggested option (modelforms + styling) would take care of the majority of my concerns I guess - and is the seemingly simpler solution.
| [
"There's a lot that you can do, but you'd need to be more specific about what you mean by \"integrate a formwizard into the admin app\" and \"trigger several forms within the admin app.\"\nThe admin app at its core is basically just a wrapper around a bunch of stock ModelForms, so if you just build a formwizard using ModelForms and slap the admin styling on it, you may be 80% of the way there.\n"
] | [
1
] | [
"You do have the source, and it is Python, so... you can read the admin application source to see what options it has.\nLook at \nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates.\nIt appears that you can override templates easily. They even provide step-by-step instructions for adding your own customized admin templates.\n"
] | [
-3
] | [
"django",
"forms",
"python"
] | stackoverflow_0000336753_django_forms_python.txt |
Q:
Python: item for item until stopterm in item?
Disclaimer: I'm fairly new to python!
If I want all the lines of a file until (edit: and including) the line containing some string stopterm, is there a way of using the list syntax for it? I was hoping there would be something like:
usefullines = [line for line in file until stopterm in line]
For now, I've got
usefullines = []
for line in file:
usefullines.append(line)
if stopterm in line:
break
It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.
A:
from itertools import takewhile
usefullines = takewhile(lambda x: not re.search(stopterm, x), lines)
from itertools import takewhile
usefullines = takewhile(lambda x: stopterm not in x, lines)
Here's a way that keeps the stopterm line:
def useful_lines(lines, stopterm):
for line in lines:
if stopterm in line:
yield line
break
yield line
usefullines = useful_lines(lines, stopterm)
# or...
for line in useful_lines(lines, stopterm):
# ... do stuff
pass
A:
" I was hoping for a 1 thought->1 Python line mapping." Wouldn't we all love a programming language that somehow mirrored our natural language?
You can achieve that, you just need to define your unique thoughts once. Then you have the 1:1 mapping you were hoping for.
def usefulLines( aFile ):
for line in aFile:
yield line
if line == stopterm:
break
Is pretty much it.
for line in usefulLines( aFile ):
# process a line, knowing it occurs BEFORE stopterm.
There are more general approaches. The lassevk answers with enum_while and enum_until are generalizations of this simple design pattern.
A:
That itertools solution is neat. I have earlier been amazed by itertools.groupby, one handy tool.
But still i was just tinkering if I could do this without itertools. So here it is
(There is one assumption and one drawback though: the file is not huge and its goes for one extra complete iteration over the lines, respectively.)
I created a sample file named "try":
hello
world
happy
day
bye
once you read the file and have the lines in a variable name lines:
lines=open('./try').readlines()
then
print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'happy' in line][0]]
gives the result:
['hello\n', 'world\n', 'happy\n']
and
print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'day' in line][0]]
gives the result:
['hello\n', 'world\n', 'happy\n', 'day\n']
So you got the last line - the stop term line also included.
A:
Forget this
Leaving the answer, but marking it community. See Stewen Huwig's answer for the correct way to do this.
Well, [x for x in enumerable] will run until enumerable doesn't produce data any more, the if-part will simply allow you to filter along the way.
What you can do is add a function, and filter your enumerable through it:
def enum_until(source, until_criteria):
for k in source:
if until_criteria(k):
break;
yield k;
def enum_while(source, while_criteria):
for k in source:
if not while_criteria(k):
break;
yield k;
l1 = [k for k in enum_until(xrange(1, 100000), lambda y: y == 100)];
l2 = [k for k in enum_while(xrange(1, 100000), lambda y: y < 100)];
print l1;
print l2;
Of course, it doesn't look as nice as what you wanted...
A:
I think it's fine to keep it that way. Sophisticated one-liner are not really pythonic, and since Guido had to put a limit somewhere, I guess this is it...
A:
I'd go with Steven Huwig's or S.Lott's solutions for real usage, but as a slightly hacky solution, here's one way to obtain this behaviour:
def stop(): raise StopIteration()
usefullines = list(stop() if stopterm in line else line for line in file)
It's slightly abusing the fact that anything that raises StopIteration will abort the current iteration (here the generator expression) and uglier to read than your desired syntax, but will work.
| Python: item for item until stopterm in item? | Disclaimer: I'm fairly new to python!
If I want all the lines of a file until (edit: and including) the line containing some string stopterm, is there a way of using the list syntax for it? I was hoping there would be something like:
usefullines = [line for line in file until stopterm in line]
For now, I've got
usefullines = []
for line in file:
usefullines.append(line)
if stopterm in line:
break
It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.
| [
"from itertools import takewhile\nusefullines = takewhile(lambda x: not re.search(stopterm, x), lines)\n\nfrom itertools import takewhile\nusefullines = takewhile(lambda x: stopterm not in x, lines)\n\nHere's a way that keeps the stopterm line:\ndef useful_lines(lines, stopterm):\n for line in lines:\n if stopterm in line:\n yield line\n break\n yield line\n\nusefullines = useful_lines(lines, stopterm)\n# or...\nfor line in useful_lines(lines, stopterm):\n # ... do stuff\n pass\n\n",
"\" I was hoping for a 1 thought->1 Python line mapping.\" Wouldn't we all love a programming language that somehow mirrored our natural language?\nYou can achieve that, you just need to define your unique thoughts once. Then you have the 1:1 mapping you were hoping for.\ndef usefulLines( aFile ):\n for line in aFile:\n yield line\n if line == stopterm:\n break\n\nIs pretty much it.\nfor line in usefulLines( aFile ):\n # process a line, knowing it occurs BEFORE stopterm.\n\nThere are more general approaches. The lassevk answers with enum_while and enum_until are generalizations of this simple design pattern.\n",
"That itertools solution is neat. I have earlier been amazed by itertools.groupby, one handy tool.\nBut still i was just tinkering if I could do this without itertools. So here it is\n(There is one assumption and one drawback though: the file is not huge and its goes for one extra complete iteration over the lines, respectively.)\nI created a sample file named \"try\":\nhello\nworld\nhappy\nday\nbye\n\nonce you read the file and have the lines in a variable name lines:\nlines=open('./try').readlines()\n\nthen \n print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'happy' in line][0]]\n\ngives the result:\n['hello\\n', 'world\\n', 'happy\\n']\n\nand \nprint [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'day' in line][0]]\n\ngives the result:\n['hello\\n', 'world\\n', 'happy\\n', 'day\\n']\n\nSo you got the last line - the stop term line also included.\n",
"Forget this\nLeaving the answer, but marking it community. See Stewen Huwig's answer for the correct way to do this.\n\nWell, [x for x in enumerable] will run until enumerable doesn't produce data any more, the if-part will simply allow you to filter along the way.\nWhat you can do is add a function, and filter your enumerable through it:\ndef enum_until(source, until_criteria):\n for k in source:\n if until_criteria(k):\n break;\n yield k;\n\ndef enum_while(source, while_criteria):\n for k in source:\n if not while_criteria(k):\n break;\n yield k;\n \nl1 = [k for k in enum_until(xrange(1, 100000), lambda y: y == 100)];\nl2 = [k for k in enum_while(xrange(1, 100000), lambda y: y < 100)];\nprint l1;\nprint l2;\n\nOf course, it doesn't look as nice as what you wanted...\n",
"I think it's fine to keep it that way. Sophisticated one-liner are not really pythonic, and since Guido had to put a limit somewhere, I guess this is it...\n",
"I'd go with Steven Huwig's or S.Lott's solutions for real usage, but as a slightly hacky solution, here's one way to obtain this behaviour:\ndef stop(): raise StopIteration()\n\nusefullines = list(stop() if stopterm in line else line for line in file)\n\nIt's slightly abusing the fact that anything that raises StopIteration will abort the current iteration (here the generator expression) and uglier to read than your desired syntax, but will work.\n"
] | [
10,
5,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000337223_python.txt |
Q:
Setting the width of a wxPython TextCtrl in number of characters
I have a TextCtrl in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?
A:
There doesn't seem to be a way. You can, however, use wxWindow::GetTextExtent. This is C++ code, but can be easily adapted to wxPython:
int x, y;
textCtrl->GetTextExtent(wxT("T"), &x, &y);
textCtrl->SetMinSize(wxSize(x * N + 10, -1));
textCtrl->SetMaxSize(wxSize(x * N + 10, -1));
/* re-layout the children*/
this->Layout();
/* alternative to Layout, will resize the parent to fit around the new
* size of the text control. */
this->GetSizer()->SetSizeHints(this);
this->Fit();
This is, you take the size of a reasonable width character (fonts may have variable width characters) and multiply it properly, adding some small value to account for native padding (say, 10px).
A:
Realize that most fonts are proportional, which means that each character may take a different width. WWW and lll are both 3 characters, but they will require vastly different sizes of text box. Some fonts, such as Courier, are designed to be fixed width and will not have this problem. Unfortunately you may not have any control over which font is selected in the text box.
If you still want to try this, the key is to get the width of a character in pixels, multiply it by the number of characters, then add some padding for the borders around the characters. You may find this to be a good starting point:
http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents
or, as litb suggests:
http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent
| Setting the width of a wxPython TextCtrl in number of characters | I have a TextCtrl in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?
| [
"There doesn't seem to be a way. You can, however, use wxWindow::GetTextExtent. This is C++ code, but can be easily adapted to wxPython:\nint x, y;\ntextCtrl->GetTextExtent(wxT(\"T\"), &x, &y);\ntextCtrl->SetMinSize(wxSize(x * N + 10, -1));\ntextCtrl->SetMaxSize(wxSize(x * N + 10, -1));\n\n/* re-layout the children*/\nthis->Layout(); \n\n/* alternative to Layout, will resize the parent to fit around the new \n * size of the text control. */\nthis->GetSizer()->SetSizeHints(this);\nthis->Fit();\n\nThis is, you take the size of a reasonable width character (fonts may have variable width characters) and multiply it properly, adding some small value to account for native padding (say, 10px).\n",
"Realize that most fonts are proportional, which means that each character may take a different width. WWW and lll are both 3 characters, but they will require vastly different sizes of text box. Some fonts, such as Courier, are designed to be fixed width and will not have this problem. Unfortunately you may not have any control over which font is selected in the text box.\nIf you still want to try this, the key is to get the width of a character in pixels, multiply it by the number of characters, then add some padding for the borders around the characters. You may find this to be a good starting point:\nhttp://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents\nor, as litb suggests:\nhttp://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent\n"
] | [
3,
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0000338217_python_wxpython.txt |
Q:
How do I modify the last line of a file?
The last line of my file is:
29-dez,40,
How can I modify that line so that it reads:
29-Dez,40,90,100,50
Note: I don't want to write a new line. I want to take the same line and put new values after 29-Dez,40,
I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.
A:
Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.
On the other hand maybe your file is really huge - multiple GBs at least. In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line.
So perhaps:
f = open("foo.file", "wb")
f.seek(-len(os.linesep), os.SEEK_END)
f.write("new text at end of last line" + os.linesep)
f.close()
(Modulo line endings on different platforms)
A:
To expand on what Doug said, in order to read the file contents into a data structure you can use the readlines() method of the file object.
The below code sample reads the file into a list of "lines", edits the last line, then writes it back out to the file:
#!/usr/bin/python
MYFILE="file.txt"
# read the file into a list of lines
lines = open(MYFILE, 'r').readlines()
# now edit the last line of the list of lines
new_last_line = (lines[-1].rstrip() + ",90,100,50")
lines[-1] = new_last_line
# now write the modified list back out to the file
open(MYFILE, 'w').writelines(lines)
If the file is very large then this approach will not work well, because this reads all the file lines into memory each time and writes them back out to the file, which is very inefficient. For a small file however this will work fine.
A:
Don't work with files directly, make a data structure that fits your needs in form of a class and make read from/write to file methods.
A:
I recently wrote a script to do something very similar to this. It would traverse a project, find all module dependencies and add any missing import statements. I won't clutter this post up with the entire script, but I'll show how I went about modifying my files.
import os
from mmap import mmap
def insert_import(filename, text):
if len(text) < 1:
return
f = open(filename, 'r+')
m = mmap(f.fileno(), os.path.getsize(filename))
origSize = m.size()
m.resize(origSize + len(text))
pos = 0
while True:
l = m.readline()
if l.startswith(('import', 'from')):
continue
else:
pos = m.tell() - len(l)
break
m[pos+len(text):] = m[pos:origSize]
m[pos:pos+len(text)] = text
m.close()
f.close()
Summary: This snippet takes a filename and a blob of text to insert. It finds the last import statement already present, and sticks the text in at that location.
The part I suggest paying most attention to is the use of mmap. It lets you work with files in the same manner you may work with a string. Very handy.
| How do I modify the last line of a file? | The last line of my file is:
29-dez,40,
How can I modify that line so that it reads:
29-Dez,40,90,100,50
Note: I don't want to write a new line. I want to take the same line and put new values after 29-Dez,40,
I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.
| [
"Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.\nOn the other hand maybe your file is really huge - multiple GBs at least. In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line. \nSo perhaps:\nf = open(\"foo.file\", \"wb\")\nf.seek(-len(os.linesep), os.SEEK_END) \nf.write(\"new text at end of last line\" + os.linesep)\nf.close() \n\n(Modulo line endings on different platforms)\n",
"To expand on what Doug said, in order to read the file contents into a data structure you can use the readlines() method of the file object.\nThe below code sample reads the file into a list of \"lines\", edits the last line, then writes it back out to the file: \n#!/usr/bin/python\n\nMYFILE=\"file.txt\"\n\n# read the file into a list of lines\nlines = open(MYFILE, 'r').readlines()\n\n# now edit the last line of the list of lines\nnew_last_line = (lines[-1].rstrip() + \",90,100,50\")\nlines[-1] = new_last_line\n\n# now write the modified list back out to the file\nopen(MYFILE, 'w').writelines(lines)\n\nIf the file is very large then this approach will not work well, because this reads all the file lines into memory each time and writes them back out to the file, which is very inefficient. For a small file however this will work fine. \n",
"Don't work with files directly, make a data structure that fits your needs in form of a class and make read from/write to file methods.\n",
"I recently wrote a script to do something very similar to this. It would traverse a project, find all module dependencies and add any missing import statements. I won't clutter this post up with the entire script, but I'll show how I went about modifying my files.\nimport os\nfrom mmap import mmap\n\ndef insert_import(filename, text):\n if len(text) < 1:\n return\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(filename))\n origSize = m.size()\n m.resize(origSize + len(text))\n pos = 0\n while True:\n l = m.readline()\n if l.startswith(('import', 'from')):\n continue\n else:\n pos = m.tell() - len(l)\n break\n m[pos+len(text):] = m[pos:origSize]\n m[pos:pos+len(text)] = text\n m.close()\n f.close()\n\nSummary: This snippet takes a filename and a blob of text to insert. It finds the last import statement already present, and sticks the text in at that location.\nThe part I suggest paying most attention to is the use of mmap. It lets you work with files in the same manner you may work with a string. Very handy.\n"
] | [
6,
6,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0000327985_file_python.txt |
Q:
How do I strptime from a pattern like this?
I need to use a datetime.strptime on the text which looks like follows.
"Some Random text of undetermined length Jan 28, 1986"
how do i do this?
A:
You may find this question useful. I'll give the answer I gave there, which is to use the dateutil module. This accepts a fuzzy parameter which will ignore any text that doesn't look like a date. ie:
>>> from dateutil.parser import parse
>>> parse("Some Random text of undetermined length Jan 28, 1986", fuzzy=True)
datetime.datetime(1986, 1, 28, 0, 0)
A:
Don't try to use strptime to capture the non-date text. For good fuzzy matching, dateutil.parser is great, but if you know the format of the date, you could use a regular expression to find the date within the string, then use strptime to turn it into a datetime object, like this:
import datetime
import re
pattern = "((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]+, [0-9]+)"
datestr = re.search(, s).group(0)
d = datetime.datetime.strptime(datestr, "%b %d, %Y")
A:
Using the ending 3 words, no need for regexps (using the time module):
>>> import time
>>> a="Some Random text of undetermined length Jan 28, 1986"
>>> datetuple = a.rsplit(" ",3)[-3:]
>>> datetuple
['Jan', '28,', '1986']
>>> time.strptime(' '.join(datetuple),"%b %d, %Y")
time.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1)
>>>
Using the datetime module:
>>> from datetime import datetime
>>> datetime.strptime(" ".join(datetuple), "%b %d, %Y")
datetime.datetime(1986, 1, 28, 0, 0)
>>>
| How do I strptime from a pattern like this? | I need to use a datetime.strptime on the text which looks like follows.
"Some Random text of undetermined length Jan 28, 1986"
how do i do this?
| [
"You may find this question useful. I'll give the answer I gave there, which is to use the dateutil module. This accepts a fuzzy parameter which will ignore any text that doesn't look like a date. ie:\n>>> from dateutil.parser import parse\n>>> parse(\"Some Random text of undetermined length Jan 28, 1986\", fuzzy=True)\ndatetime.datetime(1986, 1, 28, 0, 0)\n\n",
"Don't try to use strptime to capture the non-date text. For good fuzzy matching, dateutil.parser is great, but if you know the format of the date, you could use a regular expression to find the date within the string, then use strptime to turn it into a datetime object, like this:\nimport datetime\nimport re\n\npattern = \"((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]+, [0-9]+)\"\ndatestr = re.search(, s).group(0)\nd = datetime.datetime.strptime(datestr, \"%b %d, %Y\")\n\n",
"Using the ending 3 words, no need for regexps (using the time module):\n>>> import time\n>>> a=\"Some Random text of undetermined length Jan 28, 1986\"\n>>> datetuple = a.rsplit(\" \",3)[-3:]\n>>> datetuple\n['Jan', '28,', '1986']\n>>> time.strptime(' '.join(datetuple),\"%b %d, %Y\")\ntime.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1)\n>>> \n\nUsing the datetime module:\n>>> from datetime import datetime\n>>> datetime.strptime(\" \".join(datetuple), \"%b %d, %Y\")\ndatetime.datetime(1986, 1, 28, 0, 0)\n>>> \n\n"
] | [
4,
3,
2
] | [] | [] | [
"datetime",
"python",
"regex"
] | stackoverflow_0000339856_datetime_python_regex.txt |
Q:
Proxy objects in IronPython
I'm trying to make a proxy object in IronPython, which should dynamically present underlying structure. The proxy itself shouldn't have any functions and properties, I'm trying to catch all the calls in the runtime. Catching the function calls is easy, I just need to define getattr() function for my object, and check does appropriate function exists in the underlying layer, and return some function-like object.
I have problems with properties - I don't know how to distinguish the calling context, is my property called as a lvalue or rvalue:
o = myproxy.myproperty # I need to call underlying.myproperty_get()
or
myproxy.myproperty = o # I need to call underlying.myproperty_set(o)
I looked at the list of special functions in Python, but I didn't found anything appropriate.
I also tried to make property in the object on the fly, with combination of exec() and builtin property() function, but I found that IronPython 1.1.2 lacks of entire 'new' module (which is present in IronPython 2.x beta, but I'll rather use IP 1.x, because of .NET 2.0 framework).
Any ideas?
A:
The usual implementation of what you want in python would be this:
class CallProxy(object):
'this class wraps a callable in an object'
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
return self.fun(*args, **kwargs)
class ObjProxy(object):
''' a proxy object intercepting attribute access
'''
def __init__(self, obj):
self.__dict__['_ObjProxy__obj'] = obj
def __getattr__(self, name):
attr = getattr(self.__obj, name)
if callable(attr):
return CallProxy(attr)
else:
return attr
def __setattr__(self, name, value):
setattr(self.__obj, name, value)
I wrote a test to prove that this behaves as expected:
#keep a list of calls to the TestObj for verification
call_log = list()
class TestObj(object):
''' test object on which to prove
that the proxy implementation is correct
'''
def __init__(self):
#example attribute
self.a = 1
self._c = 3
def b(self):
'example method'
call_log.append('b')
return 2
def get_c(self):
call_log.append('get_c')
return self._c
def set_c(self, value):
call_log.append('set_c')
self._c = value
c = property(get_c, set_c, 'example property')
def verify(obj, a_val, b_val, c_val):
'testing of the usual object semantics'
assert obj.a == a_val
obj.a = a_val + 1
assert obj.a == a_val + 1
assert obj.b() == b_val
assert call_log[-1] == 'b'
assert obj.c == c_val
assert call_log[-1] == 'get_c'
obj.c = c_val + 1
assert call_log[-1] == 'set_c'
assert obj.c == c_val + 1
def test():
test = TestObj()
proxy = ObjProxy(test)
#check validity of the test
verify(test, 1, 2, 3)
#check proxy equivalent behavior
verify(proxy, 2, 2, 4)
#check that change is in the original object
verify(test, 3, 2, 5)
if __name__ == '__main__':
test()
This executes on CPython without any assert throwing an exception. IronPython should be equivalent, otherwise it's broken and this test should be added to its unit test suite.
A:
Try this:
class Test(object):
_test = 0
def test():
def fget(self):
return self._test
def fset(self, value):
self._test = value
return locals()
test = property(**test())
def greet(self, name):
print "hello", name
class Proxy(object):
def __init__(self, obj):
self._obj = obj
def __getattribute__(self, key):
obj = object.__getattribute__(self, "_obj")
return getattr(obj, key)
def __setattr__(self, name, value):
if name == "_obj":
object.__setattr__(self, name, value)
else:
obj = object.__getattribute__(self, "_obj")
setattr(obj, name, value)
t = Test()
p = Proxy(t)
p.test = 1
assert t.test == p.test
p.greet("world")
| Proxy objects in IronPython | I'm trying to make a proxy object in IronPython, which should dynamically present underlying structure. The proxy itself shouldn't have any functions and properties, I'm trying to catch all the calls in the runtime. Catching the function calls is easy, I just need to define getattr() function for my object, and check does appropriate function exists in the underlying layer, and return some function-like object.
I have problems with properties - I don't know how to distinguish the calling context, is my property called as a lvalue or rvalue:
o = myproxy.myproperty # I need to call underlying.myproperty_get()
or
myproxy.myproperty = o # I need to call underlying.myproperty_set(o)
I looked at the list of special functions in Python, but I didn't found anything appropriate.
I also tried to make property in the object on the fly, with combination of exec() and builtin property() function, but I found that IronPython 1.1.2 lacks of entire 'new' module (which is present in IronPython 2.x beta, but I'll rather use IP 1.x, because of .NET 2.0 framework).
Any ideas?
| [
"The usual implementation of what you want in python would be this:\nclass CallProxy(object):\n 'this class wraps a callable in an object'\n def __init__(self, fun):\n self.fun = fun\n\n def __call__(self, *args, **kwargs):\n return self.fun(*args, **kwargs)\n\nclass ObjProxy(object):\n ''' a proxy object intercepting attribute access\n '''\n def __init__(self, obj):\n self.__dict__['_ObjProxy__obj'] = obj\n\n def __getattr__(self, name):\n attr = getattr(self.__obj, name)\n if callable(attr):\n return CallProxy(attr)\n else:\n return attr\n\n def __setattr__(self, name, value):\n setattr(self.__obj, name, value)\n\nI wrote a test to prove that this behaves as expected:\n#keep a list of calls to the TestObj for verification\ncall_log = list()\nclass TestObj(object):\n ''' test object on which to prove\n that the proxy implementation is correct\n '''\n def __init__(self):\n #example attribute\n self.a = 1\n self._c = 3\n\n def b(self):\n 'example method'\n call_log.append('b')\n return 2\n\n def get_c(self):\n call_log.append('get_c')\n return self._c\n def set_c(self, value):\n call_log.append('set_c')\n self._c = value\n c = property(get_c, set_c, 'example property')\n\ndef verify(obj, a_val, b_val, c_val):\n 'testing of the usual object semantics'\n assert obj.a == a_val\n obj.a = a_val + 1\n assert obj.a == a_val + 1\n assert obj.b() == b_val\n assert call_log[-1] == 'b'\n assert obj.c == c_val\n assert call_log[-1] == 'get_c'\n obj.c = c_val + 1\n assert call_log[-1] == 'set_c'\n assert obj.c == c_val + 1\n\ndef test():\n test = TestObj()\n proxy = ObjProxy(test)\n #check validity of the test\n verify(test, 1, 2, 3)\n #check proxy equivalent behavior\n verify(proxy, 2, 2, 4)\n #check that change is in the original object\n verify(test, 3, 2, 5)\n\nif __name__ == '__main__':\n test()\n\nThis executes on CPython without any assert throwing an exception. IronPython should be equivalent, otherwise it's broken and this test should be added to its unit test suite.\n",
"Try this:\nclass Test(object):\n _test = 0\n\n def test():\n def fget(self):\n return self._test\n def fset(self, value):\n self._test = value\n return locals()\n test = property(**test())\n\n def greet(self, name):\n print \"hello\", name\n\n\nclass Proxy(object):\n def __init__(self, obj):\n self._obj = obj\n\n def __getattribute__(self, key):\n obj = object.__getattribute__(self, \"_obj\")\n return getattr(obj, key)\n\n def __setattr__(self, name, value):\n if name == \"_obj\":\n object.__setattr__(self, name, value)\n else:\n obj = object.__getattribute__(self, \"_obj\")\n setattr(obj, name, value)\n\n\nt = Test()\np = Proxy(t)\np.test = 1\nassert t.test == p.test\np.greet(\"world\")\n\n"
] | [
2,
2
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0000340093_.net_ironpython_python.txt |
Q:
Suppressing Output of Paramiko SSHClient Class
When I call the connect function of the Paramiko SSHClient class, it outputs some log data about establishing the connection, which I would like to suppress.
Is there a way to do this either through Paramiko itself, or Python in general?
A:
Paramiko doesn't output anything by default. You probably have a call to the logging module, setting a loglevel that's inherited when paramiko sets up it's own logging.
If you want to get at the paramiko logger to override the settings:
logger = paramiko.util.logging.getLogger()
There's also a convenience function to log everything to a file:
paramiko.util.log_to_file('filename.log')
A:
I don't know what Paramiko is, and there must be a log level setting for sure, but if you are desperate and looking for a temporary solution and if your app is single threaded
import sys
dev_null = sys.stdout = sys.stderr = open('/dev/null', 'w')
try:
.
. connect()
.
finally:
dev_null.close()
you can use StringIO for output also, if you are on an OS not have a '/dev/null'
| Suppressing Output of Paramiko SSHClient Class | When I call the connect function of the Paramiko SSHClient class, it outputs some log data about establishing the connection, which I would like to suppress.
Is there a way to do this either through Paramiko itself, or Python in general?
| [
"Paramiko doesn't output anything by default. You probably have a call to the logging module, setting a loglevel that's inherited when paramiko sets up it's own logging.\nIf you want to get at the paramiko logger to override the settings:\nlogger = paramiko.util.logging.getLogger()\n\nThere's also a convenience function to log everything to a file:\nparamiko.util.log_to_file('filename.log')\n\n",
"I don't know what Paramiko is, and there must be a log level setting for sure, but if you are desperate and looking for a temporary solution and if your app is single threaded\nimport sys\ndev_null = sys.stdout = sys.stderr = open('/dev/null', 'w')\ntry:\n.\n. connect()\n.\nfinally:\n dev_null.close()\n\nyou can use StringIO for output also, if you are on an OS not have a '/dev/null'\n"
] | [
7,
0
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0000340341_paramiko_python.txt |
Q:
How can I reboot a Windows XP64 Machine in a Python Script?
How can I reboot a Windows XP64 Machine in a Python Script? This machine does not have the "shutdown" or "restart" executables available.
A:
found it
win32api.InitiateSystemShutdown("localhost", "Maintenance Reboot", 60, 1, 1)
A:
You can use win32api module and call WinApi functions.
Recipe at code.activestate.com
| How can I reboot a Windows XP64 Machine in a Python Script? | How can I reboot a Windows XP64 Machine in a Python Script? This machine does not have the "shutdown" or "restart" executables available.
| [
"found it \nwin32api.InitiateSystemShutdown(\"localhost\", \"Maintenance Reboot\", 60, 1, 1)\n",
"You can use win32api module and call WinApi functions.\nRecipe at code.activestate.com\n"
] | [
4,
2
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000341138_python_windows.txt |
Q:
Decorators run before function it is decorating is called?
As an example:
def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.
Output on start:
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
I haven't even made a call to a function that is decorated at this point.
I am just getting started with decorators, so maybe I am missing something.
A:
I believe python decorators are just syntactic sugar.
@foo
def bar ():
pass
is the same thing as
def bar ():
pass
bar = foo(bar)
As you can see, foo is being called even though bar has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.
A:
Since you are starting with decorators, I think reading these will be helpful, so that you know the pitfalls and workarounds beforehand.
Here are two links to earlier discussions on decorators.
Python decorator makes function forget that it belongs to a class
What does functools.wraps do?
Moreover the second link mentions 'functools' a module for higher-order functions, that act on or return other functions. Use of functools.wraps is advised since it preserves the doc string of the original function(decorated one).
Another issue was wrong method signatures while generating automatic docs for my project.
but there is a workaround:
Preserving signatures of decorated functions
Hope this helps.
A:
A decorator is called as soon as the decorated function is defined. It is equivalent to writing something like this:
def __do_stuff(...):
...
do_stuff = get_booking(__do_stuff)
A:
python decorators are functions applied to a function to transform it:
@my_decorator
def function (): ...
is like doing this:
def function():...
function = my_decorator(function)
What you want to do is:
def get_booking(f=None):
def wrapper(request, **kwargs):
print "Calling get_booking Decorator"
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
| Decorators run before function it is decorating is called? | As an example:
def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.
Output on start:
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
I haven't even made a call to a function that is decorated at this point.
I am just getting started with decorators, so maybe I am missing something.
| [
"I believe python decorators are just syntactic sugar.\n@foo\ndef bar ():\n pass\n\nis the same thing as\ndef bar ():\n pass\nbar = foo(bar)\n\nAs you can see, foo is being called even though bar has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.\n",
"Since you are starting with decorators, I think reading these will be helpful, so that you know the pitfalls and workarounds beforehand.\nHere are two links to earlier discussions on decorators.\nPython decorator makes function forget that it belongs to a class\nWhat does functools.wraps do?\nMoreover the second link mentions 'functools' a module for higher-order functions, that act on or return other functions. Use of functools.wraps is advised since it preserves the doc string of the original function(decorated one).\nAnother issue was wrong method signatures while generating automatic docs for my project.\nbut there is a workaround:\nPreserving signatures of decorated functions\nHope this helps.\n",
"A decorator is called as soon as the decorated function is defined. It is equivalent to writing something like this:\ndef __do_stuff(...):\n ...\n\ndo_stuff = get_booking(__do_stuff)\n\n",
"python decorators are functions applied to a function to transform it:\n@my_decorator\ndef function (): ...\n\nis like doing this: \ndef function():...\nfunction = my_decorator(function)\n\nWhat you want to do is:\ndef get_booking(f=None):\n def wrapper(request, **kwargs):\n print \"Calling get_booking Decorator\"\n booking = _get_booking_from_session(request)\n if booking == None:\n # we don't have a booking in our session.\n return HttpRedirect('/')\n else:\n return f(request=request, booking=booking, **kwargs)\n return wrapper\n\n"
] | [
37,
1,
0,
0
] | [] | [] | [
"decorator",
"django",
"python"
] | stackoverflow_0000341379_decorator_django_python.txt |
Q:
Is rewriting a PHP app into Python a productive step?
I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.
Is this worth the effort?
A:
You need to take some parts into mind here,
What will you gain from re-writing
Is it an economically wise decision
Will the code be easier to handle for new programmers
Performance-wise, will this be a good option?
These four points is something that is important, will the work be more efficient after you re-write the code? Probably. But will it be worth the cost of re-development?
One important step to follow, if you decide to re-write, make 3 documents, first Analyze the project, what needs to be done? How should everything work? Then put up a document with Requirements, what specificly do we need and how should this be done? Last but not least, the design document, where you put all your final class diagrams, the system operations and how the design and flow of the page should work.
This will help a new developer, and old ones, to actually think about "do we really need to re-write?".
A:
Be sure to resist the Second-system effect and you should be safe.
Rewriting an existing project gives you a reachable goal. You know which way you are heading. But don't try to do too much at once.
A:
Well, it depends... ;) If you're going to use the old code together with new Python code, it might be useful, not so much for speed but for easier integration. But usually: "If it ain't broke, don't fix it". Allso rewriting can result in better code, but only do it if you need to.
As a hobby project of course it's worth it, cause the process is the goal.
A:
Rewrites are very expensive: you spend a lot of time doing something which doesn't directly help you. Joel Spolsky elaborates on this:
Things You Should Never Do, Part I
You should do it if the benefits outweigh the costs; just be careful that you don't underestimate the costs.
A:
As others have said, look at why you are doing it.
For instance, at work I am rewriting our existing inventory/sales system to a Python/django backend. Why? Because the existing PHP code base is stale, and is going to scale poorly as we grow our business (plus it was built when our business model was different, then patched up to match our current needs which resulted in some spaghetti code)
So basically, if you think you're going to benefit from it in ways that aren't just "sweet this is in python now!" then go for it.
A:
Is your aim purely to improve the applications, or is it that you want to learn/work with Python?
If it's the first, I would say you should stick with PHP, since you already know that.
A:
If you are going to add more features to the code you already have working, then it might be a good idea to port it to python. After all, it will get you increased productivity. You just have to balance it, whether the rewriting task will not outweigh the potential gain...
And also, when you do that, try to unittest as much as you can.
A:
As others have said, re-writing will take a lot longer than you think and fixing all the bugs and making use everything worked like in the old version will take even longer. Chances are you are better off simply improving and refactoring the php code you have. There are only a few good reasons to port a project from one language to another:
Performance. Some languages are simply faster than others, and there comes a point where there is nothing left to optimize and throwing hardware at the problem ceases to be effective.
Maintainability. Sometimes it is hard to find good people who know some obscure language which your legacy code is written in. In those cases it might be a good idea to re-write it in a more popular language to ease maintenance down the road.
Porting to a different platform. If you all of a sudden need to make your old VB program run on OS X and Linux as well as Windows then you’re probably looking at a re-write in a different language
In your case it doesn't seem like any of the above points hold. Of course if it's an unimportant app and you want to do it for the learning experience then by all means go for it, but from a business or economic point of view I'd take a long hard look at what such a re-write will cost and what exactly you hope to gain.
A:
I did a conversion between a PHP site and a Turbogears(Python) site for my company. The initial reason for doing so was two fold, first so a redesign would be easier and second that features could be easily added. It did take a while to get the full conversion done, but what we end up with was a very flexible back end and an even more flexible and readable front end. We've added several features that would have been very hard in PHP and we are currently doing a complete overhaul of the front end, which is turning out to be very easy.
In short it's something I would recommend, and my boss would probably say the same thing. Some people here are making good points though. Python isn't as fast as what PHP can give you, but what it lacks in performance it more then makes up for in versatility.
A:
Other issues include how business critical are the applications and how hard will it be to find maintainers. If the pages are hobbies of yours then I don't see a reason why you shouldn't rewrite them since if you introduce bugs or the rewrite doesn't go according to schedule a business won't lose money. If the application is central to a business I wouldn’t rewrite it unless you are running into limitations with the current design that can not be overcome with out a complete rewrite at which point the language choice is secondary to the fact that you need to throw out several years of work because it’s not maintainable and no longer meets your needs.
A:
One item that has not come up is the size of the current code base. Depending on how much code there is should influence your decision.
Joel Spolsky's argument to never rewrite is valid in the context of a code base the size of Netscape. Whereas a smaller code base code significantly benefit from the rewrite.
| Is rewriting a PHP app into Python a productive step? | I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in experience to write things more robustly.
Is this worth the effort?
| [
"You need to take some parts into mind here,\n\nWhat will you gain from re-writing\nIs it an economically wise decision\nWill the code be easier to handle for new programmers\nPerformance-wise, will this be a good option?\n\nThese four points is something that is important, will the work be more efficient after you re-write the code? Probably. But will it be worth the cost of re-development?\nOne important step to follow, if you decide to re-write, make 3 documents, first Analyze the project, what needs to be done? How should everything work? Then put up a document with Requirements, what specificly do we need and how should this be done? Last but not least, the design document, where you put all your final class diagrams, the system operations and how the design and flow of the page should work.\nThis will help a new developer, and old ones, to actually think about \"do we really need to re-write?\".\n",
"Be sure to resist the Second-system effect and you should be safe.\nRewriting an existing project gives you a reachable goal. You know which way you are heading. But don't try to do too much at once.\n",
"Well, it depends... ;) If you're going to use the old code together with new Python code, it might be useful, not so much for speed but for easier integration. But usually: \"If it ain't broke, don't fix it\". Allso rewriting can result in better code, but only do it if you need to.\nAs a hobby project of course it's worth it, cause the process is the goal.\n",
"Rewrites are very expensive: you spend a lot of time doing something which doesn't directly help you. Joel Spolsky elaborates on this:\nThings You Should Never Do, Part I\nYou should do it if the benefits outweigh the costs; just be careful that you don't underestimate the costs.\n",
"As others have said, look at why you are doing it.\nFor instance, at work I am rewriting our existing inventory/sales system to a Python/django backend. Why? Because the existing PHP code base is stale, and is going to scale poorly as we grow our business (plus it was built when our business model was different, then patched up to match our current needs which resulted in some spaghetti code)\nSo basically, if you think you're going to benefit from it in ways that aren't just \"sweet this is in python now!\" then go for it.\n",
"Is your aim purely to improve the applications, or is it that you want to learn/work with Python?\nIf it's the first, I would say you should stick with PHP, since you already know that.\n",
"If you are going to add more features to the code you already have working, then it might be a good idea to port it to python. After all, it will get you increased productivity. You just have to balance it, whether the rewriting task will not outweigh the potential gain... \nAnd also, when you do that, try to unittest as much as you can.\n",
"As others have said, re-writing will take a lot longer than you think and fixing all the bugs and making use everything worked like in the old version will take even longer. Chances are you are better off simply improving and refactoring the php code you have. There are only a few good reasons to port a project from one language to another:\n\nPerformance. Some languages are simply faster than others, and there comes a point where there is nothing left to optimize and throwing hardware at the problem ceases to be effective. \nMaintainability. Sometimes it is hard to find good people who know some obscure language which your legacy code is written in. In those cases it might be a good idea to re-write it in a more popular language to ease maintenance down the road.\nPorting to a different platform. If you all of a sudden need to make your old VB program run on OS X and Linux as well as Windows then you’re probably looking at a re-write in a different language\n\nIn your case it doesn't seem like any of the above points hold. Of course if it's an unimportant app and you want to do it for the learning experience then by all means go for it, but from a business or economic point of view I'd take a long hard look at what such a re-write will cost and what exactly you hope to gain.\n",
"I did a conversion between a PHP site and a Turbogears(Python) site for my company. The initial reason for doing so was two fold, first so a redesign would be easier and second that features could be easily added. It did take a while to get the full conversion done, but what we end up with was a very flexible back end and an even more flexible and readable front end. We've added several features that would have been very hard in PHP and we are currently doing a complete overhaul of the front end, which is turning out to be very easy.\nIn short it's something I would recommend, and my boss would probably say the same thing. Some people here are making good points though. Python isn't as fast as what PHP can give you, but what it lacks in performance it more then makes up for in versatility.\n",
"Other issues include how business critical are the applications and how hard will it be to find maintainers. If the pages are hobbies of yours then I don't see a reason why you shouldn't rewrite them since if you introduce bugs or the rewrite doesn't go according to schedule a business won't lose money. If the application is central to a business I wouldn’t rewrite it unless you are running into limitations with the current design that can not be overcome with out a complete rewrite at which point the language choice is secondary to the fact that you need to throw out several years of work because it’s not maintainable and no longer meets your needs.\n",
"One item that has not come up is the size of the current code base. Depending on how much code there is should influence your decision. \nJoel Spolsky's argument to never rewrite is valid in the context of a code base the size of Netscape. Whereas a smaller code base code significantly benefit from the rewrite.\n"
] | [
14,
4,
2,
2,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0000340318_php_python.txt |
Q:
Best way to import version-specific python modules
Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:
if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
or this
try:
from string import Template
except ImportError:
from our.compat.string import Template
I know that either case is equally correct and works correctly but which one is preferable?
A:
Always the second way - you never know what different Python installations will have installed. Template is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.
That's how I make Testoob support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries.
Here's an extreme case - supporting different options for ElementTree to appear:
try: import elementtree.ElementTree as ET
except ImportError:
try: import cElementTree as ET
except ImportError:
try: import lxml.etree as ET
except ImportError:
import xml.etree.ElementTree as ET # Python 2.5 and up
A:
I would probably argue that the second one would be preferable. Sometimes, you can install a module from a newer version of python into an older one. For example, wsgiref comes with Python 2.5, but it isn't entirely uncommon for it to be installed into older versions (I think it will work with python 2.3 up).
| Best way to import version-specific python modules | Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:
if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
or this
try:
from string import Template
except ImportError:
from our.compat.string import Template
I know that either case is equally correct and works correctly but which one is preferable?
| [
"Always the second way - you never know what different Python installations will have installed. Template is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.\nThat's how I make Testoob support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries.\nHere's an extreme case - supporting different options for ElementTree to appear:\ntry: import elementtree.ElementTree as ET\nexcept ImportError:\n try: import cElementTree as ET\n except ImportError:\n try: import lxml.etree as ET\n except ImportError:\n import xml.etree.ElementTree as ET # Python 2.5 and up\n\n",
"I would probably argue that the second one would be preferable. Sometimes, you can install a module from a newer version of python into an older one. For example, wsgiref comes with Python 2.5, but it isn't entirely uncommon for it to be installed into older versions (I think it will work with python 2.3 up).\n"
] | [
28,
2
] | [] | [] | [
"code_migration",
"migration",
"module",
"python"
] | stackoverflow_0000342437_code_migration_migration_module_python.txt |
Q:
Problem regarding 3.0's "hashlib" module
I've been working on getting a 2.5 module ported to 3.0, mostly for my own education, when I've gotten stuck. The class "Builder" has as its init:
def __init__(self, **options):
self._verifyOptions(options)
self._options = options
self._initDigest()
self._initBuildNames()
self._methods = []
But the error occurs at:
def _initDigest(self):
import os, sys, hashlib
digester = hashlib.md5()
digester.update(self._options.get('code'))
self._digest = digester.hexdigest()
which has as its traceback:
Traceback (most recent call last):
File "<pyshell#5>", line 5, in <module>
""", language="Cee")
File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build
b = m.Builder(**args)
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__
self._initDigest()
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest
digester.update(self._options.get('code'))
TypeError: object supporting the buffer API required
I've run it through 2to3, but it isn't picking up on it. As far as I can tell, the update function is expecting the argument to be in the form of bytes/buffer, but I've tried several different methods to convert it and haven't succeeded.
As always, any assistance would be greatly appreciated. :)
A:
I'm guessing that this line:
digester.update(self._options.get('code'))
should become:
digester.update(self._options.get('code').encode("utf-8"))
The actual desired encoding could be different in your case, but UTF-8 will work in all cases.
A:
I havent tried 3.0 yet. But there is now a bigger distinction between a sequence of bytes and strings. The latter hold unicode codepoints while the former don't hold unicode but only encoded unicode strings. Hashes operate on sequences of bytes. So you will have to encode your (unicode) strings first bevore feeding them to a hash.
| Problem regarding 3.0's "hashlib" module | I've been working on getting a 2.5 module ported to 3.0, mostly for my own education, when I've gotten stuck. The class "Builder" has as its init:
def __init__(self, **options):
self._verifyOptions(options)
self._options = options
self._initDigest()
self._initBuildNames()
self._methods = []
But the error occurs at:
def _initDigest(self):
import os, sys, hashlib
digester = hashlib.md5()
digester.update(self._options.get('code'))
self._digest = digester.hexdigest()
which has as its traceback:
Traceback (most recent call last):
File "<pyshell#5>", line 5, in <module>
""", language="Cee")
File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build
b = m.Builder(**args)
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__
self._initDigest()
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest
digester.update(self._options.get('code'))
TypeError: object supporting the buffer API required
I've run it through 2to3, but it isn't picking up on it. As far as I can tell, the update function is expecting the argument to be in the form of bytes/buffer, but I've tried several different methods to convert it and haven't succeeded.
As always, any assistance would be greatly appreciated. :)
| [
"I'm guessing that this line:\ndigester.update(self._options.get('code'))\n\nshould become:\ndigester.update(self._options.get('code').encode(\"utf-8\"))\n\nThe actual desired encoding could be different in your case, but UTF-8 will work in all cases.\n",
"I havent tried 3.0 yet. But there is now a bigger distinction between a sequence of bytes and strings. The latter hold unicode codepoints while the former don't hold unicode but only encoded unicode strings. Hashes operate on sequences of bytes. So you will have to encode your (unicode) strings first bevore feeding them to a hash.\n"
] | [
4,
0
] | [] | [] | [
"python",
"python_2to3",
"python_3.x"
] | stackoverflow_0000343204_python_python_2to3_python_3.x.txt |
Q:
Best way of sharing/managing our internal python library between applications
Our company (xyz) is moving a lot of our Flash code to Python.
In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.
How would you approach this in Python, the shared library dependency.
App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 every time there was a new library, and this is just onerous.
My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)
I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.
A:
"explicitly tested against App1,2,3 every time there was a new library" actually isn't that onerous.
Two things.
You need a formal set of API unit tests that the library must pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your changes broke the API.
You also need a set of unit tests for functionality, separate from the API. This is bigger, and might be classified as "onerous".
Once you start unit testing, you get addicted. Once you have reasonably complete tests, this problem is easy to manage.
A:
I've used variations of this cookbook entry to distribute python apps. Basically it involves zipping all your python sources up into a zip file, then concatenating it with a shell script to import the source files.
This can be helpful if you need to give an app its own version of the library.
A:
I also favour the solution of packing everything together and limit the dependency on the OS libraries to the minimal (glibc and that's it). Hard drive is cheap, customer and support time is not.
On windows, it's trivial with py2exe + InnoSetup.
On Linux, it looks like bbfreeze is the right way to handle this. Quoting from the homepage, it offers:
zip/egg file import tracking :
bbfreeze tracks imports from zip files and includes whole egg files if some module is used from an eggfile. Packages using setuputils' pkg_resources module will now work (new in 0.95.0)
binary dependency tracking :
bbfreeze will track binary dependencies and will include DLLs and shared libraries needed by a frozen program.
| Best way of sharing/managing our internal python library between applications | Our company (xyz) is moving a lot of our Flash code to Python.
In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.
How would you approach this in Python, the shared library dependency.
App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 every time there was a new library, and this is just onerous.
My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)
I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.
| [
"\"explicitly tested against App1,2,3 every time there was a new library\" actually isn't that onerous.\nTwo things.\n\nYou need a formal set of API unit tests that the library must pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your changes broke the API.\nYou also need a set of unit tests for functionality, separate from the API. This is bigger, and might be classified as \"onerous\".\n\nOnce you start unit testing, you get addicted. Once you have reasonably complete tests, this problem is easy to manage.\n",
"I've used variations of this cookbook entry to distribute python apps. Basically it involves zipping all your python sources up into a zip file, then concatenating it with a shell script to import the source files.\nThis can be helpful if you need to give an app its own version of the library.\n",
"I also favour the solution of packing everything together and limit the dependency on the OS libraries to the minimal (glibc and that's it). Hard drive is cheap, customer and support time is not.\nOn windows, it's trivial with py2exe + InnoSetup.\nOn Linux, it looks like bbfreeze is the right way to handle this. Quoting from the homepage, it offers:\n\nzip/egg file import tracking : \nbbfreeze tracks imports from zip files and includes whole egg files if some module is used from an eggfile. Packages using setuputils' pkg_resources module will now work (new in 0.95.0)\nbinary dependency tracking : \nbbfreeze will track binary dependencies and will include DLLs and shared libraries needed by a frozen program.\n\n"
] | [
4,
1,
1
] | [] | [] | [
"deployment",
"projects_and_solutions",
"python",
"shared_libraries"
] | stackoverflow_0000342425_deployment_projects_and_solutions_python_shared_libraries.txt |
Q:
How do I work with multiple git branches of a python module?
I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.
Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'.
Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one.
How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.
edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under if __name__ == '__main__':, which from what I've read does not play with relative imports:
http://mail.python.org/pipermail/python-list/2006-October/408945.html
http://www.velocityreviews.com/forums/t502905-relative-import-broken.html
The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?
edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.
A:
Relative imports (PEP 328) might help:
eggs/
__init__.py
foo.py
bar.py
# foo.py
from __future__ import absolute_import
from . import bar
See How do you organize Python modules? for other options.
EDIT:
Yet another option is to use S.Lott's and Jim's suggestions i.e, restructure your package to factor out a eggs.foo part used by eggs.bar.a and use git to work on experimental branches (see Git Community Book).
Here's an example:
$ git status
# On branch master
nothing to commit (working directory clean)
[just to make sure that all is good]
$ git checkout -b experimental
Switched to a new branch "experimental"
[work on experimental stuff]
$ git commit -a
[commit to experimental branch]
$ git checkout master
Switched to branch "master"
[work on master branch]
$ git commit -a
To merge changes into master branch:
$ git merge experimental
See chapter Basic Branching and Merging from the above book.
A:
"say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'."
This may not be the best structure. I suggest you have some other modules struggling to get out.
You have eggs.bar.a depending on eggs.foo. I'm guessing other stuff on eggs depends on eggs.foo. Further, I suspect that eggs.foo could be partitioned into eggs.foo and eggs.quux and things might be simpler.
I'd recommend refactoring this to get a better structure. The PYTHONPATH issues are symptomatic of too many things in the wrong places in the module tree.
A:
Maybe I'm not understanding correctly, but it seems that git would be the solution here, since git's branches don't need separate paths.
Create a branch for each working version of your eggs module. Then when you checkout that branch, the entire module is changed to a state matching the version of your sub-module. You could then merge what you need back and forth between the branches.
And as S.Lott pointed out, may a little refactoring couldn't hurt either ;)
| How do I work with multiple git branches of a python module? | I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.
Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'.
Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one.
How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.
edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under if __name__ == '__main__':, which from what I've read does not play with relative imports:
http://mail.python.org/pipermail/python-list/2006-October/408945.html
http://www.velocityreviews.com/forums/t502905-relative-import-broken.html
The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?
edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.
| [
"Relative imports (PEP 328) might help:\neggs/\n __init__.py\n foo.py\n bar.py\n\n# foo.py\nfrom __future__ import absolute_import\nfrom . import bar\n\nSee How do you organize Python modules? for other options.\nEDIT:\nYet another option is to use S.Lott's and Jim's suggestions i.e, restructure your package to factor out a eggs.foo part used by eggs.bar.a and use git to work on experimental branches (see Git Community Book).\nHere's an example:\n$ git status\n# On branch master\nnothing to commit (working directory clean)\n\n[just to make sure that all is good]\n$ git checkout -b experimental\nSwitched to a new branch \"experimental\"\n\n[work on experimental stuff]\n$ git commit -a\n\n[commit to experimental branch]\n$ git checkout master\nSwitched to branch \"master\"\n\n[work on master branch]\n$ git commit -a\n\nTo merge changes into master branch: \n$ git merge experimental\n\nSee chapter Basic Branching and Merging from the above book.\n",
"\"say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'.\"\nThis may not be the best structure. I suggest you have some other modules struggling to get out.\nYou have eggs.bar.a depending on eggs.foo. I'm guessing other stuff on eggs depends on eggs.foo. Further, I suspect that eggs.foo could be partitioned into eggs.foo and eggs.quux and things might be simpler.\nI'd recommend refactoring this to get a better structure. The PYTHONPATH issues are symptomatic of too many things in the wrong places in the module tree.\n",
"Maybe I'm not understanding correctly, but it seems that git would be the solution here, since git's branches don't need separate paths.\nCreate a branch for each working version of your eggs module. Then when you checkout that branch, the entire module is changed to a state matching the version of your sub-module. You could then merge what you need back and forth between the branches.\nAnd as S.Lott pointed out, may a little refactoring couldn't hurt either ;)\n"
] | [
3,
1,
1
] | [] | [] | [
"git",
"module",
"python"
] | stackoverflow_0000343517_git_module_python.txt |
Q:
What can Pygame do in terms of graphics that wxPython can't?
I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a Tetris clone in it, and it was pretty smooth.
I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ?
It looks like I'm missing something here, but I don't know what.
A:
Well, in theory there is nothing you can do with Pygame that you can't with wxPython. The point is not what but how. In my opinion, it's easier to write a game with PyGame becasue:
It's faster. Pygame is based on SDL which is a C library specifically designed for games, it has been developed with speed in mind. When you develop games, you need speed.
Is a game library, not a general purpose canvas, It has classes and functions useful for sprites, transformations, input handling, drawing, collision detection. It also implements algorithms and techniques often used in games like dirty rectangles, page flipping, etc.
There are thousands of games and examples made with it. It will be easier for you to discover how to do any trick.
There are a lot of libraries with effects and utilities you could reuse. You want an isometric game, there is a library, you want a physics engine, there is a library, you what some cool visual effect, there is a library.
PyWeek. :) This is to make the development of your game even funnier!
For some very simple games like Tetris, the difference won't be too much, but if you want to develop a fairly complex game, believe me, you will want something like PyGame.
A:
wxPython is based on wxWidgets which is a GUI-oriented toolkit. It has the advantage of using the styles and decorations provided by the system it runs on and thus it is very easy to write portable applications that integrate nicely into the look and feel of whatever you're running. You want a checkbox? Use wxCheckBox and wxPython will handle looks and interaction.
pyGame, on the other hand, is oriented towards game development and thus brings you closer to the hardware in ways wxPython doesn't (and doesn't need to, since it calls the OS for drawing most of its controls). pyGame has lots of game related stuff like collision detection, fine-grained control of surfaces and layers or flipping display buffers at a time of your choosing.
That said, graphics-wise you can probably always find a way to do what you want with both toolkits. However, when speed counts or you wish to implement graphically more taxing game ideas than Tetris, you're probably better off with pyGame. If you want to use lots of GUI elements and don't need the fancy graphics and sound functions, you're better off with wxPython.
Portability is not an issue. Both are available for the big three (Linux, OSX, Windows).
It's more a question of what kind of special capabilities you need, really.
| What can Pygame do in terms of graphics that wxPython can't? | I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a Tetris clone in it, and it was pretty smooth.
I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ?
It looks like I'm missing something here, but I don't know what.
| [
"Well, in theory there is nothing you can do with Pygame that you can't with wxPython. The point is not what but how. In my opinion, it's easier to write a game with PyGame becasue:\n\nIt's faster. Pygame is based on SDL which is a C library specifically designed for games, it has been developed with speed in mind. When you develop games, you need speed.\nIs a game library, not a general purpose canvas, It has classes and functions useful for sprites, transformations, input handling, drawing, collision detection. It also implements algorithms and techniques often used in games like dirty rectangles, page flipping, etc. \nThere are thousands of games and examples made with it. It will be easier for you to discover how to do any trick.\nThere are a lot of libraries with effects and utilities you could reuse. You want an isometric game, there is a library, you want a physics engine, there is a library, you what some cool visual effect, there is a library.\nPyWeek. :) This is to make the development of your game even funnier!\n\nFor some very simple games like Tetris, the difference won't be too much, but if you want to develop a fairly complex game, believe me, you will want something like PyGame.\n",
"wxPython is based on wxWidgets which is a GUI-oriented toolkit. It has the advantage of using the styles and decorations provided by the system it runs on and thus it is very easy to write portable applications that integrate nicely into the look and feel of whatever you're running. You want a checkbox? Use wxCheckBox and wxPython will handle looks and interaction. \npyGame, on the other hand, is oriented towards game development and thus brings you closer to the hardware in ways wxPython doesn't (and doesn't need to, since it calls the OS for drawing most of its controls). pyGame has lots of game related stuff like collision detection, fine-grained control of surfaces and layers or flipping display buffers at a time of your choosing. \nThat said, graphics-wise you can probably always find a way to do what you want with both toolkits. However, when speed counts or you wish to implement graphically more taxing game ideas than Tetris, you're probably better off with pyGame. If you want to use lots of GUI elements and don't need the fancy graphics and sound functions, you're better off with wxPython.\nPortability is not an issue. Both are available for the big three (Linux, OSX, Windows).\nIt's more a question of what kind of special capabilities you need, really.\n"
] | [
19,
13
] | [] | [] | [
"graphics",
"pygame",
"python",
"wxpython"
] | stackoverflow_0000343505_graphics_pygame_python_wxpython.txt |
Q:
Having problem importing the PIL image library
i am trying to do something with the PIL Image library in django, but i experience some problems.
I do like this:
import Image
And then I do like this
images = map(Image.open, glob.glob(os.path.join(dirpath, '*.thumb.jpg')))
But when i try to run this i get an error and it leeds me to think that its not imported correctly, anybody know?
type object 'Image' has no attribute 'open'
A:
The error above happens because your file is called Image.py and you're trying to import yourself. As Manual pointed out, you should import Image from the PIL module, but you'd also need to rename your file so it's not called Image.py.
A:
Your example works fine in my machine. I don't know why you're getting that error. PIL documentation say you have to import the library in this way:
from PIL import Image
You should try that way. As I said, for me works in both ways.
| Having problem importing the PIL image library | i am trying to do something with the PIL Image library in django, but i experience some problems.
I do like this:
import Image
And then I do like this
images = map(Image.open, glob.glob(os.path.join(dirpath, '*.thumb.jpg')))
But when i try to run this i get an error and it leeds me to think that its not imported correctly, anybody know?
type object 'Image' has no attribute 'open'
| [
"The error above happens because your file is called Image.py and you're trying to import yourself. As Manual pointed out, you should import Image from the PIL module, but you'd also need to rename your file so it's not called Image.py.\n",
"Your example works fine in my machine. I don't know why you're getting that error. PIL documentation say you have to import the library in this way:\nfrom PIL import Image\n\nYou should try that way. As I said, for me works in both ways.\n"
] | [
1,
0
] | [] | [] | [
"django",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0000344753_django_image_python_python_imaging_library.txt |
Q:
Open file, read it, process, and write back - shortest method in Python
I want to do some basic filtering on a file. Read it, do processing, write it back.
I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:
from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
The with statement makes things shorter since I don't have to explicitly open and close the file.
Any other ideas ?
A:
Actually an easier way using fileinput is to use the inplace parameter:
import fileinput
for line in fileinput.input (filenameToProcess, inplace=1):
process (line)
If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file.
This example adds line numbers to your file:
import fileinput
for line in fileinput.input ("b.txt",inplace=1):
print "%d: %s" % (fileinput.lineno(),line),
A:
I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code.
See David M. Beazley's Generator Tricks for Systems Programmers, which is a really important thing for anyone who's writing this kind of code to read.
A:
This seems to work:
with open(filename, "r+") as f:
new_txt = process(f.read())
f.truncate(0)
f.write(new_txt)
A:
If you're looking for the python equivalent of "perl -pi", here's a pretty good one:
import fileinput
for line in fileinput.input():
# process line
See http://www.python.org/doc/2.5.2/lib/module-fileinput.html for more.
Done this way, you would use your python script in a pipe to create the new file:
$ myscript.py infile.txt > outfile.txt
A:
To do it in a way which won't eat your data if you crash in the middle:
from twisted.python.filepath import FilePath
p = FilePath(filename)
p.setContent(process(p.getContent()))
A:
My ugly (but short as stated in the question) solution with generator expressions;
# Some setup first
file('test.txt', 'w').write('\n'.join('%05d' % i for i in range(100)))
# This is the filter function
def f(i):
return i % 3
# This is the main part
file('test2.txt', 'w').write('\n'.join(str(f(int(l))) for l in file('test.txt', 'r').readlines()))
# And a wrapper for sanity
def filter_file(infile, outfile, filter_function)
outfile.write('\n'.join(filter_function(l) for l in infile.readlines()))
| Open file, read it, process, and write back - shortest method in Python | I want to do some basic filtering on a file. Read it, do processing, write it back.
I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:
from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
The with statement makes things shorter since I don't have to explicitly open and close the file.
Any other ideas ?
| [
"Actually an easier way using fileinput is to use the inplace parameter:\nimport fileinput\nfor line in fileinput.input (filenameToProcess, inplace=1):\n process (line)\n\nIf you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file.\nThis example adds line numbers to your file:\nimport fileinput\n\nfor line in fileinput.input (\"b.txt\",inplace=1):\n print \"%d: %s\" % (fileinput.lineno(),line),\n\n",
"I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code.\nSee David M. Beazley's Generator Tricks for Systems Programmers, which is a really important thing for anyone who's writing this kind of code to read.\n",
"This seems to work:\nwith open(filename, \"r+\") as f:\n new_txt = process(f.read())\n f.truncate(0)\n f.write(new_txt)\n\n",
"If you're looking for the python equivalent of \"perl -pi\", here's a pretty good one:\n\nimport fileinput\nfor line in fileinput.input():\n # process line\n\nSee http://www.python.org/doc/2.5.2/lib/module-fileinput.html for more.\nDone this way, you would use your python script in a pipe to create the new file:\n\n$ myscript.py infile.txt > outfile.txt\n\n",
"To do it in a way which won't eat your data if you crash in the middle:\nfrom twisted.python.filepath import FilePath\np = FilePath(filename)\np.setContent(process(p.getContent()))\n\n",
"My ugly (but short as stated in the question) solution with generator expressions;\n# Some setup first\nfile('test.txt', 'w').write('\\n'.join('%05d' % i for i in range(100)))\n\n\n# This is the filter function\ndef f(i):\n return i % 3\n\n\n# This is the main part \nfile('test2.txt', 'w').write('\\n'.join(str(f(int(l))) for l in file('test.txt', 'r').readlines()))\n\n\n# And a wrapper for sanity\ndef filter_file(infile, outfile, filter_function)\n outfile.write('\\n'.join(filter_function(l) for l in infile.readlines()))\n\n"
] | [
26,
4,
3,
2,
1,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0000227461_coding_style_python.txt |
Q:
How do I submit a form given only the HTML source?
I would like to be able to submit a form in an HTML source (string). In other words I need at least the ability to generate POST parameters from a string containing HTML source of the form. This is needed in unit tests for a Django project. I would like a solution that possibly;
Uses only standard Python library and Django.
Allows parameter generation from a specific form if there is more than one form present.
Allows me to change the values before submission.
A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.
NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.
A:
You should re-read the documentation about Django's testing framework, specifically the part about testing views (and forms) with the test client.
The test client acts as a simple web browser, and lets you make GET and POST requests to your Django views. You can read the response HTML or get the same Context object the template received. Your Context object should contain the actual forms.Form instance you're looking for.
As an example, if your view at the URL /form/ passes the context {'myform': forms.Form()} to the template, you could get to it this way:
from django.test.client import Client
c = Client()
# request the web page:
response = c.get('/form/')
# get the Form object:
form = response.context['myform']
form_data = form.cleaned_data
my_form_data = {} # put your filled-out data in here...
form_data.update(my_form_data)
# submit the form back to the web page:
new_form = forms.Form(form_data)
if new_form.is_valid():
c.post('/form/', new_form.cleaned_data)
Hopefully that accomplishes what you want, without having to mess with parsing HTML.
Edit: After I re-read the Django docs about Forms, it turns out that forms are immutable. That's okay, though, just create a new Form instance and submit that; I've changed my code example to match this.
A:
Since the Django test framework does this, I'm not sure what you're asking.
Do you want to test a Django app that has a form?
In which case, you need to do an initial GET
followed by the resulting POST
Do you want to write (and test) a Django app that submits a form to another site?
Here's how we test Django apps with forms.
class Test_HTML_Change_User( django.test.TestCase ):
fixtures = [ 'auth.json', 'someApp.json' ]
def test_chg_user_1( self ):
self.client.login( username='this', password='this' )
response= self.client.get( "/support/html/user/2/change/" )
self.assertEquals( 200, response.status_code )
self.assertTemplateUsed( response, "someApp/user.html")
def test_chg_user( self ):
self.client.login( username='this', password='this' )
# The truly fussy would redo the test_chg_user_1 test here
response= self.client.post(
"/support/html/user/2/change/",
{'web_services': 'P',
'username':'olduser',
'first_name':'asdf',
'last_name':'asdf',
'email':'asdf@asdf.com',
'password1':'passw0rd',
'password2':'passw0rd',} )
self.assertRedirects(response, "/support/html/user/2/" )
response= self.client.get( "/support/html/user/2/" )
self.assertContains( response, "<h2>Users: Details for", status_code=200 )
self.assertContains( response, "olduser" )
self.assertTemplateUsed( response, "someApp/user_detail.html")
Note - we don't parse the HTML in detail. If it has the right template and has the right response string, it has to be right.
A:
It is simple... and hard at the same time.
Disclaimer: I don't know much about Python and nothing at all about Django... So I give general, language agnostic advices...
If one of the above advices doesn't work for you, you might want to do it manually:
Load the page with an HTML parser, list the forms.
If the method attribute is POST (case insensitive), get the action attribute to get the URL of the request (can be relative).
In the form, get all input and select tags. The name (or id if no name) attributes are the keys of the request parameters. The value attributes (empty if absent) are the corresponding values.
For select, the value is the one of the selected option or the displayed text is no value attribute.
These names and values must be URL encoded in GET requests, but not in POST ones.
HTH.
A:
Check out mechanize or it's wrapper twill. I think it's ClientForm module will work for you.
| How do I submit a form given only the HTML source? | I would like to be able to submit a form in an HTML source (string). In other words I need at least the ability to generate POST parameters from a string containing HTML source of the form. This is needed in unit tests for a Django project. I would like a solution that possibly;
Uses only standard Python library and Django.
Allows parameter generation from a specific form if there is more than one form present.
Allows me to change the values before submission.
A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.
NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.
| [
"You should re-read the documentation about Django's testing framework, specifically the part about testing views (and forms) with the test client.\nThe test client acts as a simple web browser, and lets you make GET and POST requests to your Django views. You can read the response HTML or get the same Context object the template received. Your Context object should contain the actual forms.Form instance you're looking for.\nAs an example, if your view at the URL /form/ passes the context {'myform': forms.Form()} to the template, you could get to it this way:\nfrom django.test.client import Client\nc = Client()\n\n# request the web page:\nresponse = c.get('/form/')\n\n# get the Form object:\nform = response.context['myform']\n\nform_data = form.cleaned_data\nmy_form_data = {} # put your filled-out data in here...\nform_data.update(my_form_data)\n\n# submit the form back to the web page:\nnew_form = forms.Form(form_data)\nif new_form.is_valid():\n c.post('/form/', new_form.cleaned_data)\n\nHopefully that accomplishes what you want, without having to mess with parsing HTML.\nEdit: After I re-read the Django docs about Forms, it turns out that forms are immutable. That's okay, though, just create a new Form instance and submit that; I've changed my code example to match this.\n",
"Since the Django test framework does this, I'm not sure what you're asking.\nDo you want to test a Django app that has a form?\n\nIn which case, you need to do an initial GET\nfollowed by the resulting POST\n\nDo you want to write (and test) a Django app that submits a form to another site?\nHere's how we test Django apps with forms.\nclass Test_HTML_Change_User( django.test.TestCase ):\n fixtures = [ 'auth.json', 'someApp.json' ]\n def test_chg_user_1( self ):\n self.client.login( username='this', password='this' )\n response= self.client.get( \"/support/html/user/2/change/\" )\n self.assertEquals( 200, response.status_code )\n self.assertTemplateUsed( response, \"someApp/user.html\")\n\ndef test_chg_user( self ):\n self.client.login( username='this', password='this' )\n # The truly fussy would redo the test_chg_user_1 test here\n response= self.client.post(\n \"/support/html/user/2/change/\",\n {'web_services': 'P',\n 'username':'olduser',\n 'first_name':'asdf',\n 'last_name':'asdf',\n 'email':'asdf@asdf.com',\n 'password1':'passw0rd',\n 'password2':'passw0rd',} )\n self.assertRedirects(response, \"/support/html/user/2/\" )\n response= self.client.get( \"/support/html/user/2/\" )\n self.assertContains( response, \"<h2>Users: Details for\", status_code=200 )\n self.assertContains( response, \"olduser\" )\n self.assertTemplateUsed( response, \"someApp/user_detail.html\")\n\nNote - we don't parse the HTML in detail. If it has the right template and has the right response string, it has to be right.\n",
"It is simple... and hard at the same time.\nDisclaimer: I don't know much about Python and nothing at all about Django... So I give general, language agnostic advices...\nIf one of the above advices doesn't work for you, you might want to do it manually:\n\nLoad the page with an HTML parser, list the forms.\nIf the method attribute is POST (case insensitive), get the action attribute to get the URL of the request (can be relative).\nIn the form, get all input and select tags. The name (or id if no name) attributes are the keys of the request parameters. The value attributes (empty if absent) are the corresponding values.\nFor select, the value is the one of the selected option or the displayed text is no value attribute.\n\nThese names and values must be URL encoded in GET requests, but not in POST ones.\nHTH.\n",
"Check out mechanize or it's wrapper twill. I think it's ClientForm module will work for you.\n"
] | [
4,
2,
2,
0
] | [] | [] | [
"django",
"form_submit",
"parsing",
"python",
"testing"
] | stackoverflow_0000343622_django_form_submit_parsing_python_testing.txt |
Q:
Why doesn't Python 2.6 have set literals and comprehensions or dict comprehensions?
Python 2.6 was basically a stepping stone to make converting to Python 3 easier. A lot of the features destined for Python 3 were implemented in 2.6 if they didn't break backward compatibility with syntax and the class libs.
Why weren't set literals ({1, 2, 3}), set comprehensions ({v for v in l}), or dict comprehensions ({k: v for k, v in d}) among them? In particular dict comprehensions would have been a great boon... I find myself using the considerably uglier dict([(k, v) for k, v in d]) an awful lot lately.
Is there something obvious I'm missing, or was this just a feature that didn't make the cut?
A:
It wasn't done because nobody took the time to do it. There are bugs opened for months, and no one commented on them:
http://bugs.python.org/issue2333
http://bugs.python.org/issue2334
http://bugs.python.org/issue2335
So it wasn't important enough for anybody to care, probably.
A:
All these are syntax/grammar changes. Such changes are traditionally introduced first in a Python x.y version with a from __future__ import … statement, and implemented at least on Python x.(y+1) version. Such a transition hasn't happened yet for these changes.
Technically, I've answered your "why".
Now, if you meant, “why didn't anyone take the time to suggest, support and implement something that I would like to have in 2.x also, even if they don't know about it since I never tried to suggest/support backporting those syntax enhancements in either comp.lang.python or Python-Dev and I never tried to even read the PEPs?”, then the answer lies in you too, and you can offer an answer yourself.
HTH
BTW, you shouldn't use the dict([(k,v) for k,v in d]) form, but the dict((k,v) for k,v in d). More efficient. Why create an intermediate list?
| Why doesn't Python 2.6 have set literals and comprehensions or dict comprehensions? | Python 2.6 was basically a stepping stone to make converting to Python 3 easier. A lot of the features destined for Python 3 were implemented in 2.6 if they didn't break backward compatibility with syntax and the class libs.
Why weren't set literals ({1, 2, 3}), set comprehensions ({v for v in l}), or dict comprehensions ({k: v for k, v in d}) among them? In particular dict comprehensions would have been a great boon... I find myself using the considerably uglier dict([(k, v) for k, v in d]) an awful lot lately.
Is there something obvious I'm missing, or was this just a feature that didn't make the cut?
| [
"It wasn't done because nobody took the time to do it. There are bugs opened for months, and no one commented on them:\n\nhttp://bugs.python.org/issue2333\nhttp://bugs.python.org/issue2334\nhttp://bugs.python.org/issue2335\n\nSo it wasn't important enough for anybody to care, probably.\n",
"All these are syntax/grammar changes. Such changes are traditionally introduced first in a Python x.y version with a from __future__ import … statement, and implemented at least on Python x.(y+1) version. Such a transition hasn't happened yet for these changes.\nTechnically, I've answered your \"why\".\nNow, if you meant, “why didn't anyone take the time to suggest, support and implement something that I would like to have in 2.x also, even if they don't know about it since I never tried to suggest/support backporting those syntax enhancements in either comp.lang.python or Python-Dev and I never tried to even read the PEPs?”, then the answer lies in you too, and you can offer an answer yourself.\nHTH\nBTW, you shouldn't use the dict([(k,v) for k,v in d]) form, but the dict((k,v) for k,v in d). More efficient. Why create an intermediate list?\n"
] | [
19,
10
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0000345356_python_python_3.x.txt |
Q:
Is this idiom pythonic? (someBool and "True Result" or "False Result")
I just came across this idiom in some open-source Python, and I choked on my drink.
Rather than:
if isUp:
return "Up"
else:
return "Down"
or even:
return "Up" if isUp else "Down"
the code read:
return isUp and "Up" or "Down"
I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?
A:
The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before PEP 308 was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write
return (a and [b] or [c])[0]
An alternative way of spelling it was
return (b,c)[not a]
which, with the introduction of the bool type, could be rewritten as
return (c,b)[bool(a)]
(in case it isn't clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)
Today, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.
A:
You should read Using the and-or trick (section 4.6.1) of Dive Into Python by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of.
A:
That code is a big fugly and clever for my tastes, but I suppose there's not anything wrong with it per se. I think this is really just a case of "make it all fit in one line" syndrome.
I personally would have opted for the first form though.
| Is this idiom pythonic? (someBool and "True Result" or "False Result") | I just came across this idiom in some open-source Python, and I choked on my drink.
Rather than:
if isUp:
return "Up"
else:
return "Down"
or even:
return "Up" if isUp else "Down"
the code read:
return isUp and "Up" or "Down"
I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?
| [
"The \"a and b or c\" idiom was the canonical way to express the ternary arithmetic if in Python, before PEP 308 was written and implemented. This idiom fails the \"b\" answer is false itself; to support the general case, you could write\n return (a and [b] or [c])[0]\n\nAn alternative way of spelling it was\n return (b,c)[not a]\n\nwhich, with the introduction of the bool type, could be rewritten as\n return (c,b)[bool(a)]\n\n(in case it isn't clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)\nToday, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.\n",
"You should read Using the and-or trick (section 4.6.1) of Dive Into Python by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of.\n",
"That code is a big fugly and clever for my tastes, but I suppose there's not anything wrong with it per se. I think this is really just a case of \"make it all fit in one line\" syndrome.\nI personally would have opted for the first form though.\n"
] | [
17,
9,
0
] | [
"No, it is not.\nI had a somehow similar question the other day. \nif the construct \nval if cond else alt\n\nWas not very welcome ( at least by the SO community ) and the preferred one was:\nif cond:\n val\nelse:\n alt\n\nYou can get your own conclusion. :) \n",
"Yikes. Not readable at all. For me pythonic means easy to read.\nreturn isUp and \"Up\" or \"Down\"\n\nSounds something you would do in perl.\n"
] | [
-1,
-1
] | [
"coding_style",
"python"
] | stackoverflow_0000345745_coding_style_python.txt |
Q:
Read file object as string in python
I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?
A:
You can use Python in interactive mode to search for solutions.
if f is your object, you can enter dir(f) to see all methods and attributes. There's one called read. Enter help(f.read) and it tells you that f.read() is the way to retrieve a string from an file object.
A:
From the doc file.read() (my emphasis):
file.read([size])
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.
Be aware that a regexp search on a large string object may not be efficient, and consider doing the search line-by-line, using file.next() (a file object is its own iterator).
A:
Michael Foord, aka Voidspace has an excellent tutorial on urllib2 which you can find here:
urllib2 - The Missing Manual
What you are doing should be pretty straightforward, observe this sample code:
import urllib2
import re
response = urllib2.urlopen("http://www.voidspace.org.uk/python/articles/urllib2.shtml")
html = response.read()
pattern = '(V.+space)'
wordPattern = re.compile(pattern, re.IGNORECASE)
results = wordPattern.search(html)
print results.groups()
| Read file object as string in python | I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?
| [
"You can use Python in interactive mode to search for solutions.\nif f is your object, you can enter dir(f) to see all methods and attributes. There's one called read. Enter help(f.read) and it tells you that f.read() is the way to retrieve a string from an file object.\n",
"From the doc file.read() (my emphasis):\n\nfile.read([size])\nRead at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.\n\nBe aware that a regexp search on a large string object may not be efficient, and consider doing the search line-by-line, using file.next() (a file object is its own iterator).\n",
"Michael Foord, aka Voidspace has an excellent tutorial on urllib2 which you can find here: \nurllib2 - The Missing Manual\nWhat you are doing should be pretty straightforward, observe this sample code:\nimport urllib2\nimport re\nresponse = urllib2.urlopen(\"http://www.voidspace.org.uk/python/articles/urllib2.shtml\")\nhtml = response.read()\npattern = '(V.+space)'\nwordPattern = re.compile(pattern, re.IGNORECASE)\nresults = wordPattern.search(html)\nprint results.groups()\n\n"
] | [
77,
14,
5
] | [] | [] | [
"file",
"python",
"urllib2"
] | stackoverflow_0000346230_file_python_urllib2.txt |
Q:
Python Version for a Newbie
I am extremely new to python, having started to learn it less than a month ago, but experienced with some other programming languages (primarily C# and SQL). But now that Python 3.0 has been released and is not backwards compatible, what would be the advantages and disadvantages of deciding to focus on Python 3.0 or Python 2.6?
A:
Go with 2.6 since that's what most libraries(pygame, wxpython, django, etc) target.
The differences in 3.0 aren't that huge, so transitioning to it later shouldn't be much of a problem.
A:
Since they have incompatibilities, I suggest you start going for Python 3.0 which is more useful in the future anyway. It's a better language. You can see the precise differences in What's new page on its Web site.
A:
I would say begin with 2.6 since the vast, vast majority of documentation regarding Python will be applicable to 2.6 as well most open source projects you may want to contribute to will be in 2.6 for awhile. Then, once you have a good foundation in 2.6, you can learn 3.0. That way you can kind of appreciate how the language has evolved and where the "aesthetic" of the code comes from.
A:
Start with 2.6, and when you get a bit more proficient with the language (few thousands of lines of code written), transitioning to 3.0 will be easy and natural. While learning I suggest you ignore classic classes, and pay special attention to iterators, generators, and list comprehension.
A:
It depends on what you are willing to do.
Python 3.0 is the newer release, and with time should become the standard.
However, it has almost no libraries or frameworks available, and even the tools are not so up to date (e.g. the Eclipse plug-in for Python is still in the migration phase).
On the other hand, there are no huge differences, and once you learn one, moving to the other is quite easy.
So, if you plan just to play around, you can go with 3.0.
If you plan to use it on a new project, I would stick on an older release.
A:
Be careful though. Libraries such as the mysql driver are still in 2.5
A:
If you're looking at it from a getting-a-job perspective, I'd definitely at least learn 2.x as well. The code I work on is still targeting python 2.4 and to the best of my knowledge there is no plans to move to even 2.6, let alone 3.0 in the near future. There will be a ton of 2.x python code floating around for years to come and the vast majority of python jobs will involve working with that code.
So I'd start by learning python 2.6 while the whole time keeping an eye on 3.0 so that you are at least aware of what bits of your 2.x code won't work in 3.0
| Python Version for a Newbie | I am extremely new to python, having started to learn it less than a month ago, but experienced with some other programming languages (primarily C# and SQL). But now that Python 3.0 has been released and is not backwards compatible, what would be the advantages and disadvantages of deciding to focus on Python 3.0 or Python 2.6?
| [
"Go with 2.6 since that's what most libraries(pygame, wxpython, django, etc) target. \nThe differences in 3.0 aren't that huge, so transitioning to it later shouldn't be much of a problem.\n",
"Since they have incompatibilities, I suggest you start going for Python 3.0 which is more useful in the future anyway. It's a better language. You can see the precise differences in What's new page on its Web site.\n",
"I would say begin with 2.6 since the vast, vast majority of documentation regarding Python will be applicable to 2.6 as well most open source projects you may want to contribute to will be in 2.6 for awhile. Then, once you have a good foundation in 2.6, you can learn 3.0. That way you can kind of appreciate how the language has evolved and where the \"aesthetic\" of the code comes from.\n",
"Start with 2.6, and when you get a bit more proficient with the language (few thousands of lines of code written), transitioning to 3.0 will be easy and natural. While learning I suggest you ignore classic classes, and pay special attention to iterators, generators, and list comprehension.\n",
"It depends on what you are willing to do.\nPython 3.0 is the newer release, and with time should become the standard.\nHowever, it has almost no libraries or frameworks available, and even the tools are not so up to date (e.g. the Eclipse plug-in for Python is still in the migration phase).\nOn the other hand, there are no huge differences, and once you learn one, moving to the other is quite easy.\nSo, if you plan just to play around, you can go with 3.0.\nIf you plan to use it on a new project, I would stick on an older release.\n",
"Be careful though. Libraries such as the mysql driver are still in 2.5\n",
"If you're looking at it from a getting-a-job perspective, I'd definitely at least learn 2.x as well. The code I work on is still targeting python 2.4 and to the best of my knowledge there is no plans to move to even 2.6, let alone 3.0 in the near future. There will be a ton of 2.x python code floating around for years to come and the vast majority of python jobs will involve working with that code. \nSo I'd start by learning python 2.6 while the whole time keeping an eye on 3.0 so that you are at least aware of what bits of your 2.x code won't work in 3.0\n"
] | [
14,
6,
5,
3,
2,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0000345255_python_python_3.x.txt |
Q:
Installation problems with django-tagging
I am having problems using django-tagging. I try to follow the documentation but it fails at the second step
Once you've installed Django Tagging and want to use it in your Django applications, do the following:
Put 'tagging' in your INSTALLED_APPS setting.
Run the command manage.py syncdb.
The syncdb command creates the necessary database tables and creates permission objects for all installed apps that need them.
I get a python Traceback with the following error:
ImportError: cannot import name parse_lookup
The following works, so I think it is correctly installed:
>> import tagging
>> tagging.VERSION
(0, 2.1000000000000001, None)
What am I missing?
A:
http://code.djangoproject.com/ticket/7680
parse_lookup has been removed. Not sure how this will affect tagging. Might want to do some searching.
Update: apparently it's been fixed in the trunk version of tagging. Download the latest SVN build of tagging.
A:
I had the same bug me recently. I checked out the trunk release which seems to work fine.
In [1]: import tagging; tagging.VERSION
Out[1]: (0, 3, 'pre')
| Installation problems with django-tagging | I am having problems using django-tagging. I try to follow the documentation but it fails at the second step
Once you've installed Django Tagging and want to use it in your Django applications, do the following:
Put 'tagging' in your INSTALLED_APPS setting.
Run the command manage.py syncdb.
The syncdb command creates the necessary database tables and creates permission objects for all installed apps that need them.
I get a python Traceback with the following error:
ImportError: cannot import name parse_lookup
The following works, so I think it is correctly installed:
>> import tagging
>> tagging.VERSION
(0, 2.1000000000000001, None)
What am I missing?
| [
"http://code.djangoproject.com/ticket/7680\nparse_lookup has been removed. Not sure how this will affect tagging. Might want to do some searching. \nUpdate: apparently it's been fixed in the trunk version of tagging. Download the latest SVN build of tagging.\n",
"I had the same bug me recently. I checked out the trunk release which seems to work fine. \nIn [1]: import tagging; tagging.VERSION\nOut[1]: (0, 3, 'pre')\n\n"
] | [
4,
0
] | [] | [] | [
"django",
"django_tagging",
"python"
] | stackoverflow_0000346426_django_django_tagging_python.txt |
Q:
Django.contrib.flatpages without models
I have some flatpages with empty content field and their content inside the template (given with template_name field).
Why I am using django.contrib.flatpages
It allows me to serve (mostly) static pages with minimal URL configuration.
I don't have to write views for each of them.
Why I don't need the model FlatPage
I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file;
I can edit the source directly from the file system, without the help of a server (such as admin).
I can take advantage of syntax highlightning and other editor features.
With the model I have to maintain fixtures for flatpages.
So the data for the same entity is in two seperate places.
If I move the content inside the fixture it'll be more difficult to edit.
Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.
What I am looking for
Basically; getting rid of FlatPage model while maintaining contrib.flatpages functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like add_to_class) FlatPages to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of FlatPages.
If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?
A:
Using the direct_to_template generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:
r'^foo/(?P<template_name>.+)/$','direct_to_template', {'template': 'foo_index.html'}),
Then import the template in your foo_index.html:
{% include template_name %}
| Django.contrib.flatpages without models | I have some flatpages with empty content field and their content inside the template (given with template_name field).
Why I am using django.contrib.flatpages
It allows me to serve (mostly) static pages with minimal URL configuration.
I don't have to write views for each of them.
Why I don't need the model FlatPage
I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file;
I can edit the source directly from the file system, without the help of a server (such as admin).
I can take advantage of syntax highlightning and other editor features.
With the model I have to maintain fixtures for flatpages.
So the data for the same entity is in two seperate places.
If I move the content inside the fixture it'll be more difficult to edit.
Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.
What I am looking for
Basically; getting rid of FlatPage model while maintaining contrib.flatpages functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like add_to_class) FlatPages to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of FlatPages.
If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?
| [
"Using the direct_to_template generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:\nr'^foo/(?P<template_name>.+)/$','direct_to_template', {'template': 'foo_index.html'}),\n\nThen import the template in your foo_index.html:\n{% include template_name %}\n\n"
] | [
9
] | [] | [] | [
"django",
"django_flatpages",
"python",
"templates"
] | stackoverflow_0000346840_django_django_flatpages_python_templates.txt |
Q:
Is it more efficient to use "import " or "from import "?
Say I only needed to use findall() from the re module, is it more efficient to do:
from re import findall
or
import re
Is there actually any difference in speed/memory usage etc?
A:
There is no difference on the import, however there is a small difference on access.
When you access the function as
re.findall()
python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times.
A:
When in doubt, time it:
from timeit import Timer
print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit()
print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit()
I get the following results, using the minimum of 5 repetitions of 10,000,000 calls:
re.findall(): 123.444600105
findall(): 122.056155205
There appears to be a very slight usage advantage to using findall() directly, rather than re.findall().
However, the actual import statements differ in their speed by a significant amount. On my computer, I get the following results:
>>> Timer("import re").timeit()
2.39156508446
>>> Timer("from re import findall").timeit()
4.41387701035
So import re appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import.
A:
There is no difference, except for what names from re are visible in you local namespace after the import.
| Is it more efficient to use "import " or "from import "? | Say I only needed to use findall() from the re module, is it more efficient to do:
from re import findall
or
import re
Is there actually any difference in speed/memory usage etc?
| [
"There is no difference on the import, however there is a small difference on access.\nWhen you access the function as\nre.findall() \n\npython will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times.\n",
"When in doubt, time it:\nfrom timeit import Timer\n\nprint Timer(\"\"\"re.findall(r\"\\d+\", \"fg12f 1414 21af 144\")\"\"\", \"import re\").timeit()\nprint Timer(\"\"\"findall(r\"\\d+\", \"fg12f 1414 21af 144\")\"\"\", \"from re import findall\").timeit()\n\nI get the following results, using the minimum of 5 repetitions of 10,000,000 calls:\nre.findall(): 123.444600105\nfindall(): 122.056155205\n\nThere appears to be a very slight usage advantage to using findall() directly, rather than re.findall().\nHowever, the actual import statements differ in their speed by a significant amount. On my computer, I get the following results:\n>>> Timer(\"import re\").timeit()\n2.39156508446\n>>> Timer(\"from re import findall\").timeit()\n4.41387701035\n\nSo import re appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import.\n",
"There is no difference, except for what names from re are visible in you local namespace after the import.\n"
] | [
15,
12,
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0000346723_import_python.txt |
Q:
Refactoring python module configuration to avoid relative imports
This is related to a previous question of mine.
I understand how to store and read configuration files. There are choices such as ConfigParser and ConfigObj.
Consider this structure for a hypothetical 'eggs' module:
eggs/
common/
__init__.py
config.py
foo/
__init__.py
a.py
'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', import eggs.common.config. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.
A possible alternative to the above absolute import is a relative import. Thus, in 'a',
import .common.config
Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?
edit- Removed the VCS context
A:
"imports ... require your module to be on your PYTHONPATH"
Right.
So, what's wrong with setting PYTHONPATH?
A:
require statement from pkg_resources maybe what you need.
A:
As I understand it from this and previous questions you only need one path to be in sys.path. If we are talking about git as VCS (mentioned in previous question) when only one branch is checked out at any time (single working directory). You can switch, merge branches as frequently as you like.
A:
I'm thinking of something along the lines of a more 'push-based' kind of solution. Instead of importing the shared objects (be they for configuration, or utility functions of some sort), have the top-level init export it, and each intermediate init import it from the layer above, and immediately re-export it.
I'm not sure if I've got the python terminology right, please correct me if I'm wrong.
Like this, any module that needs to use the shared object(which in the context of this example represents configuration information) simply imports it from the init at its own level.
Does this sound sensible/feasible?
A:
You can trick the import mechanism, by adding each subdirectory to egg/__init__.py:
__path__.append(__path__[0]+"\\common")
__path__.append(__path__[0]+"\\foo")
then, you simply import all modules from the egg namespace; e.g. import egg.bar (provided you have file egg/foo/bar.py).
Note that foo and common should not be a package - in other words, they should not contain __init__.py file.
This solution completely solves the issue of eventually moving files around; however it flattens the namespace and therefore it may not be as good, especially in big projects - personally, I prefer full name resolution.
| Refactoring python module configuration to avoid relative imports | This is related to a previous question of mine.
I understand how to store and read configuration files. There are choices such as ConfigParser and ConfigObj.
Consider this structure for a hypothetical 'eggs' module:
eggs/
common/
__init__.py
config.py
foo/
__init__.py
a.py
'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', import eggs.common.config. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.
A possible alternative to the above absolute import is a relative import. Thus, in 'a',
import .common.config
Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?
edit- Removed the VCS context
| [
"\"imports ... require your module to be on your PYTHONPATH\"\nRight. \nSo, what's wrong with setting PYTHONPATH?\n",
"require statement from pkg_resources maybe what you need. \n",
"As I understand it from this and previous questions you only need one path to be in sys.path. If we are talking about git as VCS (mentioned in previous question) when only one branch is checked out at any time (single working directory). You can switch, merge branches as frequently as you like.\n",
"I'm thinking of something along the lines of a more 'push-based' kind of solution. Instead of importing the shared objects (be they for configuration, or utility functions of some sort), have the top-level init export it, and each intermediate init import it from the layer above, and immediately re-export it. \nI'm not sure if I've got the python terminology right, please correct me if I'm wrong. \nLike this, any module that needs to use the shared object(which in the context of this example represents configuration information) simply imports it from the init at its own level.\nDoes this sound sensible/feasible?\n",
"You can trick the import mechanism, by adding each subdirectory to egg/__init__.py:\n__path__.append(__path__[0]+\"\\\\common\")\n__path__.append(__path__[0]+\"\\\\foo\")\n\nthen, you simply import all modules from the egg namespace; e.g. import egg.bar (provided you have file egg/foo/bar.py).\nNote that foo and common should not be a package - in other words, they should not contain __init__.py file.\nThis solution completely solves the issue of eventually moving files around; however it flattens the namespace and therefore it may not be as good, especially in big projects - personally, I prefer full name resolution.\n"
] | [
2,
0,
0,
0,
0
] | [] | [] | [
"configuration",
"module",
"python"
] | stackoverflow_0000345746_configuration_module_python.txt |
Q:
Python crypt module -- what's the correct use of salts?
First, context: I'm trying to create a command-line-based tool (Linux) that
requires login. Accounts on this tool have nothing to do with
system-level accounts -- none of this looks at /etc/passwd.
I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.
Despite not using the system-level password files, using crypt seemed
to be a good practice to use, as opposed to storing passwords in
cleartext. (While crypt is certainly better than storing passwords in
cleartext, I'm open to other ways of doing this.)
My crypt knowledge is based on this:
https://docs.python.org/2/library/crypt.html
The documentation seems to ask for something that isn't possible: "it
is recommended to use the full crypted password as salt when checking
for a password."
Huh? If I'm creating the crypted password (as in, when creating a user
record) how can I use the crypted password as a salt? It
doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)
I've tried using the plaintext password as a salt. This does
work, but has two problems; one easily overcome, and one serious:
1) The first two letters of the plaintext password are included in the
crypted password. You can fix this by not writing the first two
characters to the file:
user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type)
2) By using the plaintext password as the salt, you would seem to be
reducing the amount of entropy in the system. Possibly I'm
misunderstanding the purpose of the salt.
The best practice I've been able to derive is to use the first two
characters from the username as the salt. Would this be appropriate,
or is there something I've missed that makes that a bad move?
My understanding of a salt is that it prevents pre-computing password
hashes from a dictionary. I could use a standard salt for all
passwords (such as my initials, "JS,") but that seems to be less of a
burden for an attacker than using two characters from each user's username.
A:
Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page:
char *crypt(const char *key, const char *salt);
key is a user’s typed password.
salt is a two-character string chosen from the set [a–zA–Z0–9./].
This string is used to perturb the algorithm in one of 4096
different ways.
Emphasis is on "two-character string". Now, if you look at crypt()'s behavior in Python:
>>> crypt.crypt("Hello", "World")
'Wo5pEi/H5/mxU'
>>> crypt.crypt("Hello", "ABCDE")
'AB/uOsC7P93EI'
you discover that the first two characters of the result always coincide with the first two characters of the original salt, which indeed form the true two-character-salt itself.
That is, the result of crypt() has the form 2char-salt + encrypted-pass.
Hence, there is no difference in the result if instead of passing the two-character-salt or the original many-characters-salt you pass the whole encrypted password.
Note: the set [a–zA–Z0–9./] contains 64 characters, and 64*64=4096. Here's how two characters relate to "4096 different ways".
A:
For the use of the crypt module:
When GENERATING the crypted password, you provide the salt. It might as well be random to increase resistance to brute-forcing, as long as it meets the listed conditions. When CHECKING a password, you should provide the value from getpwname, in case you are on a system that supports larger salt sizes and didn't generate it yourself.
General comments:
If this has nothing to do w/ actual system logins, there is nothing preventing you from using a stronger method than crypt. You could randomly generate N characters of per-user salt, to be combined with the user's password in a SHA-1 hash.
string_to_hash = user.stored_salt + entered_password
successful_login = (sha1(string_to_hash) == user.stored_password_hash)
UPDATE: While this is far more secure against rainbow tables, the method above still has cryptographic weaknesses. Correct application of an HMAC algorithm can yet further increase your security, but is beyond my realm of expertise.
A:
You're misunderstanding the documentation; it says that since the length of the salt may vary depending on the underlying crypt() implementation, you should provide the entire crypted password as the salt value when checking passwords. That is, instead of pulling the first two chars off to be the salt, just toss in the whole thing.
Your idea of having the initial salt be based on the username seems okay.
A:
Here's some general advice on salting passwords:
In general, salts are used to make ranbow tables too costly to compute. So, you should add a little randomized salt to all your password hashes, and just store it in plaintext next to the hashed password value.
Use HMAC - it's a good standard, and it's more secure than concatenating the password and salt.
Use SHA1: MD5 is broken. No offense intended if you knew this, just being thorough. ;)
I would not have the salt be a function of the password. An attacker would have to generate a rainbow table to have an instant-lookup database of passwords, but they'd only have to do that once. If you choose a random 32-bit integer, they'd have to generate 2^32 tables, which (unlike a deterministic salt) costs way, way too much memory (and time).
A:
For some added strength, you can get the crypt module to use md5 by using a salt in the format.
$1$ABCDEFGH$
where ABCDEFGH is your salt string.
>>> p = crypt.crypt('password', '$1$s8Ty3/f$')
>>> p
Out: '$1$s8Ty3/f$0H/M0JswK9pl3X/e.n55G1'
>>> p == crypt.crypt('password', p)
Out: True
(note that this is a gnu extension to crypt, see "man crypt" on a linux system). MD5 (and now even SHA1) may be "broken", but they are still relatively good for password hashes, and md5 is still the standard for linux local passwords.
A:
The password, or anything derived from the password, should never be used as salt. The salt for a particular password should be unpredictable.
A username or part of the user name is tolerable, but even better would be random bytes from a cryptographic RNG.
A:
Use PBKDF2, see this comment on a different thread (includes Python implementation).
| Python crypt module -- what's the correct use of salts? | First, context: I'm trying to create a command-line-based tool (Linux) that
requires login. Accounts on this tool have nothing to do with
system-level accounts -- none of this looks at /etc/passwd.
I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.
Despite not using the system-level password files, using crypt seemed
to be a good practice to use, as opposed to storing passwords in
cleartext. (While crypt is certainly better than storing passwords in
cleartext, I'm open to other ways of doing this.)
My crypt knowledge is based on this:
https://docs.python.org/2/library/crypt.html
The documentation seems to ask for something that isn't possible: "it
is recommended to use the full crypted password as salt when checking
for a password."
Huh? If I'm creating the crypted password (as in, when creating a user
record) how can I use the crypted password as a salt? It
doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)
I've tried using the plaintext password as a salt. This does
work, but has two problems; one easily overcome, and one serious:
1) The first two letters of the plaintext password are included in the
crypted password. You can fix this by not writing the first two
characters to the file:
user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type)
2) By using the plaintext password as the salt, you would seem to be
reducing the amount of entropy in the system. Possibly I'm
misunderstanding the purpose of the salt.
The best practice I've been able to derive is to use the first two
characters from the username as the salt. Would this be appropriate,
or is there something I've missed that makes that a bad move?
My understanding of a salt is that it prevents pre-computing password
hashes from a dictionary. I could use a standard salt for all
passwords (such as my initials, "JS,") but that seems to be less of a
burden for an attacker than using two characters from each user's username.
| [
"Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page:\n\nchar *crypt(const char *key, const char *salt);\n\nkey is a user’s typed password.\nsalt is a two-character string chosen from the set [a–zA–Z0–9./]. \nThis string is used to perturb the algorithm in one of 4096 \ndifferent ways.\n\nEmphasis is on \"two-character string\". Now, if you look at crypt()'s behavior in Python:\n>>> crypt.crypt(\"Hello\", \"World\")\n'Wo5pEi/H5/mxU'\n>>> crypt.crypt(\"Hello\", \"ABCDE\")\n'AB/uOsC7P93EI'\n\nyou discover that the first two characters of the result always coincide with the first two characters of the original salt, which indeed form the true two-character-salt itself.\nThat is, the result of crypt() has the form 2char-salt + encrypted-pass.\nHence, there is no difference in the result if instead of passing the two-character-salt or the original many-characters-salt you pass the whole encrypted password.\nNote: the set [a–zA–Z0–9./] contains 64 characters, and 64*64=4096. Here's how two characters relate to \"4096 different ways\".\n",
"For the use of the crypt module:\nWhen GENERATING the crypted password, you provide the salt. It might as well be random to increase resistance to brute-forcing, as long as it meets the listed conditions. When CHECKING a password, you should provide the value from getpwname, in case you are on a system that supports larger salt sizes and didn't generate it yourself.\nGeneral comments:\nIf this has nothing to do w/ actual system logins, there is nothing preventing you from using a stronger method than crypt. You could randomly generate N characters of per-user salt, to be combined with the user's password in a SHA-1 hash.\nstring_to_hash = user.stored_salt + entered_password\nsuccessful_login = (sha1(string_to_hash) == user.stored_password_hash)\n\nUPDATE: While this is far more secure against rainbow tables, the method above still has cryptographic weaknesses. Correct application of an HMAC algorithm can yet further increase your security, but is beyond my realm of expertise.\n",
"You're misunderstanding the documentation; it says that since the length of the salt may vary depending on the underlying crypt() implementation, you should provide the entire crypted password as the salt value when checking passwords. That is, instead of pulling the first two chars off to be the salt, just toss in the whole thing.\nYour idea of having the initial salt be based on the username seems okay. \n",
"Here's some general advice on salting passwords:\n\nIn general, salts are used to make ranbow tables too costly to compute. So, you should add a little randomized salt to all your password hashes, and just store it in plaintext next to the hashed password value.\nUse HMAC - it's a good standard, and it's more secure than concatenating the password and salt.\nUse SHA1: MD5 is broken. No offense intended if you knew this, just being thorough. ;)\n\nI would not have the salt be a function of the password. An attacker would have to generate a rainbow table to have an instant-lookup database of passwords, but they'd only have to do that once. If you choose a random 32-bit integer, they'd have to generate 2^32 tables, which (unlike a deterministic salt) costs way, way too much memory (and time).\n",
"For some added strength, you can get the crypt module to use md5 by using a salt in the format.\n$1$ABCDEFGH$\n\nwhere ABCDEFGH is your salt string. \n>>> p = crypt.crypt('password', '$1$s8Ty3/f$')\n>>> p\nOut: '$1$s8Ty3/f$0H/M0JswK9pl3X/e.n55G1'\n>>> p == crypt.crypt('password', p)\nOut: True\n\n(note that this is a gnu extension to crypt, see \"man crypt\" on a linux system). MD5 (and now even SHA1) may be \"broken\", but they are still relatively good for password hashes, and md5 is still the standard for linux local passwords.\n",
"The password, or anything derived from the password, should never be used as salt. The salt for a particular password should be unpredictable.\nA username or part of the user name is tolerable, but even better would be random bytes from a cryptographic RNG.\n",
"Use PBKDF2, see this comment on a different thread (includes Python implementation).\n"
] | [
7,
4,
3,
3,
2,
1,
1
] | [
"Take a look at the article TrueCrypt explained by Björn Edström. It contains easy to understand explanation of how truecrypt works and a simple Python implementation of some of truecrypt's functionality including password management.\n\nHe's talking about the Python crypt() module, not about TrueCrypt in Python\n\nDefault crypt.crypt() in Python 2 is not very secure and the article explains how more secure alternatives might work.\n"
] | [
-2
] | [
"crypt",
"cryptography",
"linux",
"python"
] | stackoverflow_0000329956_crypt_cryptography_linux_python.txt |
Q:
Where do I go from here -- regarding programming?
I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.
I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.
I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.
Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.
A:
You will only have a first language for a little while. Pick any direction that interests you, and follow it. There is no way around the introduction "Drink from the Firehose" experience.
Keep early project simple, and tangible. Build useful things and the motivation will be there.
Web / desktop / mobile / etc, its all good. Find the one that gets you thinking about code when your not coding, and you'll know your going in the right direction.
A:
The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.
This is exactly the course to follow. I think most of us get into programming the same way. Find a problem and work out its solution in whatever technology is appropriate. Keep looking for problems that are interesting to you, and you'll find your own answer (which is probably different than my own answer) to this question.
A:
One of pragmatic programmer's advice is to learn a new language per year. Possibly, a completely different one each time (see Martin Fowler's opinion on this matter).
Back to your specifics, you have chosen the way of programming because you enjoyed it (I hope :-)); if you are not satisfied by your current environment, go and change it.
A:
Don't worry so much about the direction you're going, just make sure that:
a) You are enjoying it, and are understanding what you are doing. You don't have to initially understand concepts like polymorphism for example, but you should be understanding the basics of what you are doing. Just can't wrap your mind around Tuples and Dictionaries in Python after awhile? Then it's probably not for you. Of course, that's a very low level example as if you don't get Dictionaries, then there's a problem in general :-)
b) You are working on things that you want to solve, not just because you think you NEED to learn this. You used the phrase "Windows is a necessary evil" No, it isn't. Many companies (big and small) do not use the .NET platform for development. Your approach to Linux was interesting as you could not achieve something you wanted on it and your result was "it's clunky" which seems kind of awkward.
Either way, this isn't about Linux vs. Windows, but I hope that helps. Just go with the flow, and don't worry about what way you're going as long as you're enjoying and learning! :)
A:
I find some of my junior colleagues (atleast the ones that are very passionate about CS) asking similar questions (sometimes I find myself asking this too, even though I am now 12+ yrs into the industry). One advice I give them (and to myself too), which helped me, is -
Focus on the job that is already assigned to you. As part of that task, make sure you dont just "get the job done", but also make sure that you understand the fundamentals behind the same. If you want to be a good programmer, you need to understand the underlying principles of "how things work". Using an API to do matrix multiplication is easy, but if you dont really know what is matrix multiplication and how to do it by hand, you are actually losing out. So in your chosen web programming domain, make sure you go beyond the surface. Understand what is really happening behind your back, when you click that button.
As part of "doing the job" you typically can figure out what is your interest area. If you are more passionate about how things are implemented, and keep figuring it out, then you are, IMO, a systems guy. If you are more passionate about finding out all the new tools and the newer features and seem to be keen in putting things together to create newer and cooler outputs, then you are an application programmer. Both are interesting areas in their own ways and as people adviced above, realize what you like and see if you can stick with it.
And I like one of the advices above. If you are still confused, try doing this "rotation" thingie. There are lots of scope in just about every domain/field and so keep rotating (but give each rotation due time), until you find what you like.
All the best.
:-)
A:
Thanks for the thoughtful responses
That seemed to be another distraction from learning programming for me anyway. I spent more time chasing apparent fixes for upgraded packages and such. Mostly things that were already working and it just seemed to not make much sense to spend time recreating the wheel so to speak. Believe me the jury is still out for ma as to whether it makes good sense to chase the dream of Linux as a real alternative to a usable desktop. Now remember ex-Windows users will always have to compare their experience with Linux to how they were previously able to work before trying Windows.
Just my two cents
A:
This is a ruff business. Technology churn keeps everyone busy and workers who want to excel at their craft can become constantly busy in a sea of new technology. But, in the end all of these technologies follow the same patterns and practices to one degree or another. Becoming an expert in the fundamentals will go a long way to forwarding a career in this business. The Pragamatic Programmer is a classic source for direction.
Also, what you can or should do (Windows vs. Linux) may depend greatly on Geography. I follow the job market in my area. Spend a little time finding out what business are looking for and what contractors are doing and choose technologies to learn based on this information. User groups, conferences, and code camps are also a good source.
If the real problem here is that you are on your own building your first web app and find what you see on channel 9 is more compelling then maybe you should follow your instincts! BTW, I think you will find "clunkiness" everywhere, might as well get used to it.
A:
Really all you need to do is make sure you take baby steps and are doing something you are enjoying.
I started off programming in visual basic on a little game. Not the best language, but it was a good starting point for me at the time. My point is, you don't need to pick the best language/operating system/anything from the start, just iterate. It is the programming way.
By the way, just because you use windows as your OS doesn't mean you have to do everything .NET I use windows and then have a server for all my web hosting that I SSH into.
A:
I had the same issue for a little while myself. I was getting bored of just being in PHP and wanted to be able to do more. I ended up settling on C# since it not only fulfilled the 'necessary evil' argument, but allows me to do anything I want in the MS realm, and is the closest syntax wise to another language (Java).
Thinking about all the different types of projects this opened me up to made me choose this direction. Both languages can be used for web development, mobile devices, and desktop applications.
| Where do I go from here -- regarding programming? | I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.
I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.
I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.
Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.
| [
"You will only have a first language for a little while. Pick any direction that interests you, and follow it. There is no way around the introduction \"Drink from the Firehose\" experience.\nKeep early project simple, and tangible. Build useful things and the motivation will be there.\nWeb / desktop / mobile / etc, its all good. Find the one that gets you thinking about code when your not coding, and you'll know your going in the right direction.\n",
"\n\nThe reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.\n\n\nThis is exactly the course to follow. I think most of us get into programming the same way. Find a problem and work out its solution in whatever technology is appropriate. Keep looking for problems that are interesting to you, and you'll find your own answer (which is probably different than my own answer) to this question.\n",
"One of pragmatic programmer's advice is to learn a new language per year. Possibly, a completely different one each time (see Martin Fowler's opinion on this matter).\nBack to your specifics, you have chosen the way of programming because you enjoyed it (I hope :-)); if you are not satisfied by your current environment, go and change it.\n",
"Don't worry so much about the direction you're going, just make sure that:\na) You are enjoying it, and are understanding what you are doing. You don't have to initially understand concepts like polymorphism for example, but you should be understanding the basics of what you are doing. Just can't wrap your mind around Tuples and Dictionaries in Python after awhile? Then it's probably not for you. Of course, that's a very low level example as if you don't get Dictionaries, then there's a problem in general :-)\nb) You are working on things that you want to solve, not just because you think you NEED to learn this. You used the phrase \"Windows is a necessary evil\" No, it isn't. Many companies (big and small) do not use the .NET platform for development. Your approach to Linux was interesting as you could not achieve something you wanted on it and your result was \"it's clunky\" which seems kind of awkward.\nEither way, this isn't about Linux vs. Windows, but I hope that helps. Just go with the flow, and don't worry about what way you're going as long as you're enjoying and learning! :)\n",
"I find some of my junior colleagues (atleast the ones that are very passionate about CS) asking similar questions (sometimes I find myself asking this too, even though I am now 12+ yrs into the industry). One advice I give them (and to myself too), which helped me, is - \n\nFocus on the job that is already assigned to you. As part of that task, make sure you dont just \"get the job done\", but also make sure that you understand the fundamentals behind the same. If you want to be a good programmer, you need to understand the underlying principles of \"how things work\". Using an API to do matrix multiplication is easy, but if you dont really know what is matrix multiplication and how to do it by hand, you are actually losing out. So in your chosen web programming domain, make sure you go beyond the surface. Understand what is really happening behind your back, when you click that button.\nAs part of \"doing the job\" you typically can figure out what is your interest area. If you are more passionate about how things are implemented, and keep figuring it out, then you are, IMO, a systems guy. If you are more passionate about finding out all the new tools and the newer features and seem to be keen in putting things together to create newer and cooler outputs, then you are an application programmer. Both are interesting areas in their own ways and as people adviced above, realize what you like and see if you can stick with it.\nAnd I like one of the advices above. If you are still confused, try doing this \"rotation\" thingie. There are lots of scope in just about every domain/field and so keep rotating (but give each rotation due time), until you find what you like.\n\nAll the best.\n:-)\n",
"Thanks for the thoughtful responses\nThat seemed to be another distraction from learning programming for me anyway. I spent more time chasing apparent fixes for upgraded packages and such. Mostly things that were already working and it just seemed to not make much sense to spend time recreating the wheel so to speak. Believe me the jury is still out for ma as to whether it makes good sense to chase the dream of Linux as a real alternative to a usable desktop. Now remember ex-Windows users will always have to compare their experience with Linux to how they were previously able to work before trying Windows.\nJust my two cents \n",
"This is a ruff business. Technology churn keeps everyone busy and workers who want to excel at their craft can become constantly busy in a sea of new technology. But, in the end all of these technologies follow the same patterns and practices to one degree or another. Becoming an expert in the fundamentals will go a long way to forwarding a career in this business. The Pragamatic Programmer is a classic source for direction. \nAlso, what you can or should do (Windows vs. Linux) may depend greatly on Geography. I follow the job market in my area. Spend a little time finding out what business are looking for and what contractors are doing and choose technologies to learn based on this information. User groups, conferences, and code camps are also a good source. \nIf the real problem here is that you are on your own building your first web app and find what you see on channel 9 is more compelling then maybe you should follow your instincts! BTW, I think you will find \"clunkiness\" everywhere, might as well get used to it.\n",
"Really all you need to do is make sure you take baby steps and are doing something you are enjoying.\nI started off programming in visual basic on a little game. Not the best language, but it was a good starting point for me at the time. My point is, you don't need to pick the best language/operating system/anything from the start, just iterate. It is the programming way.\nBy the way, just because you use windows as your OS doesn't mean you have to do everything .NET I use windows and then have a server for all my web hosting that I SSH into.\n",
"I had the same issue for a little while myself. I was getting bored of just being in PHP and wanted to be able to do more. I ended up settling on C# since it not only fulfilled the 'necessary evil' argument, but allows me to do anything I want in the MS realm, and is the closest syntax wise to another language (Java).\nThinking about all the different types of projects this opened me up to made me choose this direction. Both languages can be used for web development, mobile devices, and desktop applications.\n"
] | [
7,
2,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"asp.net",
"linux",
"php",
"python"
] | stackoverflow_0000347054_asp.net_linux_php_python.txt |
Q:
Rounding float to the nearest factor?
I have a small math problem I am trying to solve
Given a number x and resolution y, I need to find the next x' with the required resolution.
e.g.
x = 1.002 y = 0.1 x'= 1.1
x = 0.348 y = 0.1 x'= 0.4
x = 0.50 y = 1 x'= 1
x = 0.32 y = 0.05 x'= 0.35
Is there any smart way of doing this in Python?
A:
import math
def next_multiple(x, y):
return math.ceil(x/y)*y
def try_it(x, y):
print x, y, next_multiple(x, y)
for x, y in [
(1.002, 0.1),
(0.348, 0.1),
(0.50, 1),
(0.32, 0.05)
]:
try_it(x, y)
produces:
1.002 0.1 1.1
0.348 0.1 0.4
0.5 1 1.0
0.32 0.05 0.35
I think your first example output is wrong, The correct answer for x' is 1.1, right?
| Rounding float to the nearest factor? | I have a small math problem I am trying to solve
Given a number x and resolution y, I need to find the next x' with the required resolution.
e.g.
x = 1.002 y = 0.1 x'= 1.1
x = 0.348 y = 0.1 x'= 0.4
x = 0.50 y = 1 x'= 1
x = 0.32 y = 0.05 x'= 0.35
Is there any smart way of doing this in Python?
| [
"import math\n\ndef next_multiple(x, y):\n return math.ceil(x/y)*y\n\ndef try_it(x, y):\n print x, y, next_multiple(x, y)\n\nfor x, y in [\n (1.002, 0.1),\n (0.348, 0.1),\n (0.50, 1),\n (0.32, 0.05)\n ]:\n try_it(x, y)\n\nproduces:\n1.002 0.1 1.1\n0.348 0.1 0.4\n0.5 1 1.0\n0.32 0.05 0.35\n\nI think your first example output is wrong, The correct answer for x' is 1.1, right?\n"
] | [
12
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0000347538_algorithm_math_python.txt |
Q:
Emitting headers from a tiny Python web-framework
I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code on github
Basically it's written to be as simple to use as possible. An example "Hello World" like site:
from pyerweb import GET, runner
@GET("/")
def index():
return "<strong>This</strong> would be the output HTML for the URL / "
@GET("/view/([0-9]+?)$")
def view_something(id):
return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123"
runner(url = "/", # url would be from a web server, in actual use
output_helper = "html_tidy" # run returned HTML though "HTML tidy"
Basically you have a function that returns HTML, and the GET decorator maps this to a URL.
When runner() is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.
Now, the problem - outputting headers. Currently for development I've just put a line before the runner() call which does print Content-type:text/html\n - this is obviously a bit limiting..
My first ideas was to have the functions return a dict, something like..
@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..
I could check if the returned data is a dict, if so use returned_data['html'] as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from return my_html to return {'html':my_html} which isn't very elegant either..
After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:
get "/" do
content_type 'text/css', :charset => 'utf-8'
end
This seems like it could be nice enough in Python:
@GET("/")
def index():
header("location", "http://google.com")
To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change sys.stdout to a StringIO, so you could do..
def index():
print "<html>"
print "<head><title>Something</title></head>"
print "<body>...</body>"
print "</html>
..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above header() function would write to this.. Something like:
def header(name, value):
pyerweb.header_stream.write("%s: %s" % (name, value))
Basically, the question is, how would you output headers from this web-framework (mostly in terms of use, but to a lesser extent implementation)?
A:
Look at PEP 333 for an excellent design pattern for a very lightweight web server. If your server has this exact API, you can reuse it in a lot of context with a lot of other products.
PEP 333 (WSGI) suggests that you don't directly return the page, but you provide the HTML page to a "start_response" callable object, which wraps your HTML in the proper HTTP response, with the proper headers.
A:
you could use that idea of returning a dict or a string, but add a new decorator, so the 'evolution' for a user would be:
simple html:
@GET("/")
def index():
return "<html><body>...</body></html>"
with constant headers (one @HEADER for each one, or a dict with all of them):
@GET("/")
@HEADER("Location","http://google.com")
def index():
return "<html><body>...</body></html>"
with complex, maybe calculated headers:
@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
the @HEADER() decorator would simply change the returned value, so the 'framework' code would stay simple.
A:
You should reconsider the notion of returning HTML - headers are part of HTTP.
If you build your framework around an HTTP stream, the headers are simply lines that precede the HTML payload.
A headers example from the above link:
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Etag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
For a Python example, see the implementaion of BaseHTTPRequestHandler.send_header(keyword, value).
| Emitting headers from a tiny Python web-framework | I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code on github
Basically it's written to be as simple to use as possible. An example "Hello World" like site:
from pyerweb import GET, runner
@GET("/")
def index():
return "<strong>This</strong> would be the output HTML for the URL / "
@GET("/view/([0-9]+?)$")
def view_something(id):
return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123"
runner(url = "/", # url would be from a web server, in actual use
output_helper = "html_tidy" # run returned HTML though "HTML tidy"
Basically you have a function that returns HTML, and the GET decorator maps this to a URL.
When runner() is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.
Now, the problem - outputting headers. Currently for development I've just put a line before the runner() call which does print Content-type:text/html\n - this is obviously a bit limiting..
My first ideas was to have the functions return a dict, something like..
@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..
I could check if the returned data is a dict, if so use returned_data['html'] as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from return my_html to return {'html':my_html} which isn't very elegant either..
After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:
get "/" do
content_type 'text/css', :charset => 'utf-8'
end
This seems like it could be nice enough in Python:
@GET("/")
def index():
header("location", "http://google.com")
To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change sys.stdout to a StringIO, so you could do..
def index():
print "<html>"
print "<head><title>Something</title></head>"
print "<body>...</body>"
print "</html>
..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above header() function would write to this.. Something like:
def header(name, value):
pyerweb.header_stream.write("%s: %s" % (name, value))
Basically, the question is, how would you output headers from this web-framework (mostly in terms of use, but to a lesser extent implementation)?
| [
"Look at PEP 333 for an excellent design pattern for a very lightweight web server. If your server has this exact API, you can reuse it in a lot of context with a lot of other products.\nPEP 333 (WSGI) suggests that you don't directly return the page, but you provide the HTML page to a \"start_response\" callable object, which wraps your HTML in the proper HTTP response, with the proper headers.\n",
"you could use that idea of returning a dict or a string, but add a new decorator, so the 'evolution' for a user would be:\nsimple html:\n@GET(\"/\")\ndef index():\nreturn \"<html><body>...</body></html>\"\n\nwith constant headers (one @HEADER for each one, or a dict with all of them):\n@GET(\"/\")\n@HEADER(\"Location\",\"http://google.com\")\ndef index():\nreturn \"<html><body>...</body></html>\"\n\nwith complex, maybe calculated headers:\n@GET(\"/\")\ndef index():\nreturn {\n \"html\": \"<html><body>...</body></html>\",\n \"headers\": {\"Location\":\"http://google.com\"}\n}\n\nthe @HEADER() decorator would simply change the returned value, so the 'framework' code would stay simple.\n",
"You should reconsider the notion of returning HTML - headers are part of HTTP.\nIf you build your framework around an HTTP stream, the headers are simply lines that precede the HTML payload.\nA headers example from the above link:\nHTTP/1.1 200 OK\nDate: Mon, 23 May 2005 22:38:34 GMT\nServer: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\nLast-Modified: Wed, 08 Jan 2003 23:11:55 GMT\nEtag: \"3f80f-1b6-3e1cb03b\"\nAccept-Ranges: bytes\nContent-Length: 438\nConnection: close\nContent-Type: text/html; charset=UTF-8\n\nFor a Python example, see the implementaion of BaseHTTPRequestHandler.send_header(keyword, value).\n"
] | [
5,
3,
1
] | [] | [] | [
"frameworks",
"python"
] | stackoverflow_0000347497_frameworks_python.txt |
Q:
mod_python.publisher always gives content type 'text/plain'
I've just set up mod python with apache and I'm trying to get a simple script to work, but what happens is it publishes all my html as plain text when I load the page. I figured this is a problem with mod_python.publisher, The handler I set it too. I searched through the source of it and found the line where it differentiates between 'text/plain' and 'text/html' and it searches the last hundred characters of the file it's outputting for ' in my script, so I put it in, and then it still didn't work. I even tried commenting out some of the code so that publisher would set everything as 'text/html' but it still did the same thing when I refreshed the page. Maybe I've set up something wrong.
Heres my configuration in the httpd.conf
< Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">
SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On
< /Directory >
A:
Your configuration looks okay: I've got a working mod_python.publisher script with essentially the same settings.
A few other thoughts:
When you tried editing the publisher source code, did you restart your web server? It only loads Python libraries once, when the server is first started.
Publisher's autodetection looks for a closing HTML tag: </html>. Is that what you added? (I can't see it in your question, but possibly it just got stripped out when you posted it.)
If nothing else works, you can always set the content type explicitly. It's more code, but it's guaranteed to work consistently. Set the content_type field on your request to 'text/html'.
For example, if your script looks like this right now:
def index(req, an_arg='default'):
return some_html
it would become:
def index(req, an_arg='default'):
req.content_type = 'text/html'
return some_html
| mod_python.publisher always gives content type 'text/plain' | I've just set up mod python with apache and I'm trying to get a simple script to work, but what happens is it publishes all my html as plain text when I load the page. I figured this is a problem with mod_python.publisher, The handler I set it too. I searched through the source of it and found the line where it differentiates between 'text/plain' and 'text/html' and it searches the last hundred characters of the file it's outputting for ' in my script, so I put it in, and then it still didn't work. I even tried commenting out some of the code so that publisher would set everything as 'text/html' but it still did the same thing when I refreshed the page. Maybe I've set up something wrong.
Heres my configuration in the httpd.conf
< Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">
SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On
< /Directory >
| [
"Your configuration looks okay: I've got a working mod_python.publisher script with essentially the same settings.\nA few other thoughts:\n\nWhen you tried editing the publisher source code, did you restart your web server? It only loads Python libraries once, when the server is first started.\nPublisher's autodetection looks for a closing HTML tag: </html>. Is that what you added? (I can't see it in your question, but possibly it just got stripped out when you posted it.)\nIf nothing else works, you can always set the content type explicitly. It's more code, but it's guaranteed to work consistently. Set the content_type field on your request to 'text/html'. \n\nFor example, if your script looks like this right now:\ndef index(req, an_arg='default'):\n return some_html\n\nit would become:\ndef index(req, an_arg='default'):\n req.content_type = 'text/html'\n return some_html\n\n"
] | [
3
] | [] | [] | [
"content_type",
"mod_python",
"python"
] | stackoverflow_0000347632_content_type_mod_python_python.txt |
Q:
Gauss-Legendre Algorithm in python
I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use.
I have read about the Gauss-Legendre Algorithm, and I have tried porting it to Python with no success.
I am reading from Here, and I would appreciate any input as to where I am going wrong!
It outputs: 0.163991276262
from __future__ import division
import math
def square(x):return x*x
a = 1
b = 1/math.sqrt(2)
t = 1/4
x = 1
for i in range(1000):
y = a
a = (a+b)/2
b = math.sqrt(b*y)
t = t - x * square((y-a))
x = 2* x
pi = (square((a+b)))/4*t
print pi
raw_input()
A:
You forgot parentheses around 4*t:
pi = (a+b)**2 / (4*t)
You can use decimal to perform calculation with higher precision.
#!/usr/bin/env python
from __future__ import with_statement
import decimal
def pi_gauss_legendre():
D = decimal.Decimal
with decimal.localcontext() as ctx:
ctx.prec += 2
a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1
pi = None
while 1:
an = (a + b) / 2
b = (a * b).sqrt()
t -= p * (a - an) * (a - an)
a, p = an, 2*p
piold = pi
pi = (a + b) * (a + b) / (4 * t)
if pi == piold: # equal within given precision
break
return +pi
decimal.getcontext().prec = 100
print pi_gauss_legendre()
Output:
3.141592653589793238462643383279502884197169399375105820974944592307816406286208\
998628034825342117068
A:
pi = (square((a+b)))/4*t
should be
pi = (square((a+b)))/(4*t)
A:
If you want to calculate PI to 1000 digits you need to use a data type that supports 1000 digits of precision (e.g., mxNumber)
You need to calculate a,b,t, and x until |a-b| < 10**-digits, not iterate digits times.
Calculate square and pi as @J.F. suggests.
| Gauss-Legendre Algorithm in python | I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use.
I have read about the Gauss-Legendre Algorithm, and I have tried porting it to Python with no success.
I am reading from Here, and I would appreciate any input as to where I am going wrong!
It outputs: 0.163991276262
from __future__ import division
import math
def square(x):return x*x
a = 1
b = 1/math.sqrt(2)
t = 1/4
x = 1
for i in range(1000):
y = a
a = (a+b)/2
b = math.sqrt(b*y)
t = t - x * square((y-a))
x = 2* x
pi = (square((a+b)))/4*t
print pi
raw_input()
| [
"\nYou forgot parentheses around 4*t:\npi = (a+b)**2 / (4*t)\n\nYou can use decimal to perform calculation with higher precision.\n#!/usr/bin/env python\nfrom __future__ import with_statement\nimport decimal\n\ndef pi_gauss_legendre():\n D = decimal.Decimal\n with decimal.localcontext() as ctx:\n ctx.prec += 2 \n a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1 \n pi = None\n while 1:\n an = (a + b) / 2\n b = (a * b).sqrt()\n t -= p * (a - an) * (a - an)\n a, p = an, 2*p\n piold = pi\n pi = (a + b) * (a + b) / (4 * t)\n if pi == piold: # equal within given precision\n break\n return +pi\n\ndecimal.getcontext().prec = 100\nprint pi_gauss_legendre()\n\n\nOutput:\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208\\\n 998628034825342117068\n\n",
"pi = (square((a+b)))/4*t\n\nshould be\npi = (square((a+b)))/(4*t)\n\n",
"\nIf you want to calculate PI to 1000 digits you need to use a data type that supports 1000 digits of precision (e.g., mxNumber)\nYou need to calculate a,b,t, and x until |a-b| < 10**-digits, not iterate digits times.\nCalculate square and pi as @J.F. suggests.\n\n"
] | [
29,
3,
3
] | [] | [] | [
"algorithm",
"pi",
"python"
] | stackoverflow_0000347734_algorithm_pi_python.txt |
Q:
Ticking function grapher
I am trying to figure out the following problem.
I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.
Now I am working on the background and the ticking of X, Y axes (if any axes are shown).
I worked out the following.
I have a fixed width of 250 p
The tick gap should be between 12.5 and 50p.
The ticks should indicate either unit or half unit range, by that i mean the following.
x range (-5, 5): one tick = 1
x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate.
x range (0.1, 0.3): 0.05
Given a Xrange
How would you get the number of ticks between either full or half unit range ?
Or maybe there are other way to approach this type of problems.
A:
One way to do this would be to "normalise" the difference between the minimum and maximum and do a case distinction on that value. In python:
delta = maximum - minimum
factor = 10**math.ceil(math.log(delta,10)) # smallest power of 10 greater than delta
normalised_delta = delta / factor # 0.1 <= normalised_delta < 1
if normalised_delta/5 >= 0.1:
step_size = 0.1
elif normalised_delta/5 >= 0.05:
step_size = 0.05
elif normalised_delta/20 <= 0.01:
step_size = 0.01
step_size = step_size * factor
The above code assumes you want the biggest possible gap. For the smallest you would use the following if:
if normalised_delta/20 == 0.005:
step_size = 0.005
elif normalised_delta/20 <= 0.01:
step_size = 0.01
elif normalised_delta/5 >= 0.05:
step_size = 0.05
Besides the possibility that there are more than one suitable values, there is also the somewhat worrisome possibility that there are none. Take for example the range [0,24] where a gap of 12.5p would give a step size of 1.2 and a gap of 50p would give step size 4.8. There is no "unit" or "half unit" in between. The problem is that the difference between a gap of 12.5p and one of 50p is a factor 4 while the difference between 0.01 and 0.05 is a factor 5. So you will have to widen the range of allowable gaps a bit and adjust the code accordingly.
Clarification of some of the magic numbers: divisions by 20 and 5 correspond to the number of segments with the minimal and maximal gap size, respectively (ie. 250/12.5 and 250/50). As the normalised delta is in the range [0.1,1), you get that dividing it by 20 and 5 gives you [0.005,0.05) and [0.02,0.2), respectively. These ranges result in the possible (normalised) step sizes of 0.005 and 0.01 for the first range and 0.05 and 0.1 for the second.
A:
Using deltaX
if deltax between 2 and 10 half increment
if deltax between 10 and 20 unit increment
if smaller than 2 we multiply by 10 and test again
if larger than 20 we divide
Then we get the position of the first unit or half increment on the width using xmin.
I still need to test this solution.
A:
You might want to take a look at Jgraph, which solves a complementary problem: it is a data grapher rather than a function grapher. But there are a lot of things in common such as dealing with major and minor tick marks, axis labels, and so on and so forth. I find the input language a little verbose for my taste, but Jgraph produces really nice technical graphs. There are a lot of examples on the web site and probably some good ideas you could steal.
And you know what they say: talent imitates, but genius steals :-)
A:
This seems to do what i was expecting.
import math
def main():
getTickGap(-1,1.5)
def next_multiple(x, y):
return math.ceil(x/y)*y
def getTickGap(xmin, xmax):
xdelta = xmax -xmin
width = 250
# smallest power of 10 greater than delta
factor = 10**math.ceil(math.log(xdelta,10))
# 0.1 <= normalised_delta < 1
normalised_delta = xdelta / factor
print("normalised_delta", normalised_delta)
# we want largest gap
if normalised_delta/4 >= 0.1:
step_size = 0.1
elif normalised_delta/4 >= 0.05:
step_size = 0.05
elif normalised_delta/20 <= 0.01:
step_size = 0.01
step_size = step_size * factor
## if normalised_delta/20 == 0.005:
## step_size = 0.005
## elif normalised_delta/20 <= 0.01:
## step_size = 0.01
## elif normalised_delta/4 >= 0.05:
## step_size = 0.05
## step_size = step_size * factor
print("step_size", step_size)
totalsteps = xdelta/step_size
print("Total steps", totalsteps)
print("Range [", xmin, ",", xmax, "]")
firstInc = next_multiple(xmin, step_size)
count = (250/xdelta)*(firstInc - xmin)
print("firstInc ", firstInc, 'tick at ', count)
print("start at ", firstInc - xmin, (width/totalsteps)*(firstInc - xmin))
inc = firstInc
while (inc <xmax):
inc += step_size
count += (width/totalsteps)
print(" inc", inc, "tick at ", count)
if name == "main":
main()
A:
On range -1, 0
i get
normalised_delta 1.0
step_size 0.1
Total steps 10.0
Range [ -1 , 0 ]
firstInc -1.0 tick at 0.0
start at 0.0 0.0
inc -0.9 tick at 25.0
inc -0.8 tick at 50.0
inc -0.7 tick at 75.0
inc -0.6 tick at 100.0
inc -0.5 tick at 125.0
inc -0.4 tick at 150.0
inc -0.3 tick at 175.0
inc -0.2 tick at 200.0
inc -0.1 tick at 225.0
inc -1.38777878078e-16 tick at 250.0
inc 0.1 tick at 275.0
How come the second line from bottom get this number ????
| Ticking function grapher | I am trying to figure out the following problem.
I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.
Now I am working on the background and the ticking of X, Y axes (if any axes are shown).
I worked out the following.
I have a fixed width of 250 p
The tick gap should be between 12.5 and 50p.
The ticks should indicate either unit or half unit range, by that i mean the following.
x range (-5, 5): one tick = 1
x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate.
x range (0.1, 0.3): 0.05
Given a Xrange
How would you get the number of ticks between either full or half unit range ?
Or maybe there are other way to approach this type of problems.
| [
"One way to do this would be to \"normalise\" the difference between the minimum and maximum and do a case distinction on that value. In python:\ndelta = maximum - minimum\nfactor = 10**math.ceil(math.log(delta,10)) # smallest power of 10 greater than delta\nnormalised_delta = delta / factor # 0.1 <= normalised_delta < 1\nif normalised_delta/5 >= 0.1:\n step_size = 0.1\nelif normalised_delta/5 >= 0.05:\n step_size = 0.05\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nstep_size = step_size * factor\n\nThe above code assumes you want the biggest possible gap. For the smallest you would use the following if:\nif normalised_delta/20 == 0.005:\n step_size = 0.005\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nelif normalised_delta/5 >= 0.05:\n step_size = 0.05\n\nBesides the possibility that there are more than one suitable values, there is also the somewhat worrisome possibility that there are none. Take for example the range [0,24] where a gap of 12.5p would give a step size of 1.2 and a gap of 50p would give step size 4.8. There is no \"unit\" or \"half unit\" in between. The problem is that the difference between a gap of 12.5p and one of 50p is a factor 4 while the difference between 0.01 and 0.05 is a factor 5. So you will have to widen the range of allowable gaps a bit and adjust the code accordingly.\nClarification of some of the magic numbers: divisions by 20 and 5 correspond to the number of segments with the minimal and maximal gap size, respectively (ie. 250/12.5 and 250/50). As the normalised delta is in the range [0.1,1), you get that dividing it by 20 and 5 gives you [0.005,0.05) and [0.02,0.2), respectively. These ranges result in the possible (normalised) step sizes of 0.005 and 0.01 for the first range and 0.05 and 0.1 for the second.\n",
"Using deltaX\nif deltax between 2 and 10 half increment\nif deltax between 10 and 20 unit increment\nif smaller than 2 we multiply by 10 and test again\nif larger than 20 we divide \nThen we get the position of the first unit or half increment on the width using xmin.\nI still need to test this solution.\n",
"You might want to take a look at Jgraph, which solves a complementary problem: it is a data grapher rather than a function grapher. But there are a lot of things in common such as dealing with major and minor tick marks, axis labels, and so on and so forth. I find the input language a little verbose for my taste, but Jgraph produces really nice technical graphs. There are a lot of examples on the web site and probably some good ideas you could steal. \nAnd you know what they say: talent imitates, but genius steals :-)\n",
"This seems to do what i was expecting.\nimport math\ndef main():\n getTickGap(-1,1.5)\ndef next_multiple(x, y):\n return math.ceil(x/y)*y\ndef getTickGap(xmin, xmax):\n xdelta = xmax -xmin\n width = 250\n # smallest power of 10 greater than delta\n factor = 10**math.ceil(math.log(xdelta,10))\n # 0.1 <= normalised_delta < 1\n normalised_delta = xdelta / factor\n print(\"normalised_delta\", normalised_delta)\n# we want largest gap\nif normalised_delta/4 >= 0.1:\n step_size = 0.1\nelif normalised_delta/4 >= 0.05:\n step_size = 0.05\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nstep_size = step_size * factor\n\n\n## if normalised_delta/20 == 0.005:\n## step_size = 0.005\n## elif normalised_delta/20 <= 0.01:\n## step_size = 0.01\n## elif normalised_delta/4 >= 0.05:\n## step_size = 0.05\n## step_size = step_size * factor\nprint(\"step_size\", step_size)\ntotalsteps = xdelta/step_size\nprint(\"Total steps\", totalsteps)\nprint(\"Range [\", xmin, \",\", xmax, \"]\")\n\nfirstInc = next_multiple(xmin, step_size)\ncount = (250/xdelta)*(firstInc - xmin)\nprint(\"firstInc \", firstInc, 'tick at ', count)\nprint(\"start at \", firstInc - xmin, (width/totalsteps)*(firstInc - xmin))\ninc = firstInc\n\nwhile (inc <xmax):\n inc += step_size\n count += (width/totalsteps)\n print(\" inc\", inc, \"tick at \", count)\n\nif name == \"main\":\n main()\n",
"On range -1, 0\ni get \nnormalised_delta 1.0\nstep_size 0.1\nTotal steps 10.0\nRange [ -1 , 0 ]\nfirstInc -1.0 tick at 0.0\nstart at 0.0 0.0\n inc -0.9 tick at 25.0\n inc -0.8 tick at 50.0\n inc -0.7 tick at 75.0\n inc -0.6 tick at 100.0\n inc -0.5 tick at 125.0\n inc -0.4 tick at 150.0\n inc -0.3 tick at 175.0\n inc -0.2 tick at 200.0\n inc -0.1 tick at 225.0\n inc -1.38777878078e-16 tick at 250.0\n inc 0.1 tick at 275.0\n\nHow come the second line from bottom get this number ????\n"
] | [
4,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0000346823_algorithm_math_python.txt |
Q:
Questions for python->scheme conversion
I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.
I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.
I have a python function which can swap two tiles easily:
def swap(p, (r1, c1), (r2, c2)):
# Swaps *any* two locations and returns new configuration
# Does not concern itself with zero location, etc
# Not sure how to do this functionally
p_p = p[:]
temp = p_p[r1][c1]
p_p[r1][c1] = p_p[r2][c2]
p_p[r2][c2] = temp
return p_p
I'd like to turn this into something you might find in SICP, avoiding side effects, etc.
But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.
In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment?
How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?
A:
You identified that your initial problem was trying to write C semantics in Lisp. Is it not repeating the mistake to try to write scheme semantics in python? I always try to learn language X as a paradigm as much as a language and write in the most x-ish way.
It might be justifiable if this was a business app you knew was going to be migrated, but otherwise I'd just write it in scheme to begin with.
A:
I wrote an 8-puzzle solver in Lisp about a year ago. I just used a list of 3 lists, each sublist with 3 elements being the numbers. It's not constant time, but it is portable.
Anyways, if you are really interested in doing this functionally (Scheme doesn't require you to) what is easiest to do is to create some helper functions that will get a specific value given row/col and 'set' a value given row/col. Instead of modifying the original data structure, the set operation will construct the new state based on the old state.
Then you can write a swap operation based on these get and set operations. Here's what I wrote about a year ago in Common Lisp, but it's easily convertible to Scheme:
; getval
;
; This function takes a position (r . c) where and returns the corresponding
; number in the 8-puzzle state. For example, if you wanted (1 . 2) from
; ((1 2 3) (4 5 6) (7 8 9)), the value would be 6. The r and c values begin
; at 0.
;
; parameters: pos The position to get
; state The 8-puzzle state
; returns: The value at pos in state
(defun getval (pos state)
(if (null state) 'no-value
(if (= 0 (car pos))
(if (= 0 (cdr pos))
(caar state)
(getval (cons (car pos) (- (cdr pos) 1)) (list (cdar state))))
(getval (cons (- (car pos) 1) (cdr pos)) (cdr state)))))
; setval
;
; This function returns a state where the value at pos is replaced by val.
; Like getval, this function is zero-based. Accessing beyond the size of
; the state is undefined (and probably broken)
;
; parameters: pos Position to set
; val Value to set
; state State to modify
; returns: New state where pos is val
(defun setval (pos val state)
(if (null state) '()
(if (= 0 (car pos))
(if (= 0 (cdr pos))
(cons (cons val (cdar state)) (cdr state))
(let ((temp (setval (cons (car pos) (- (cdr pos) 1)) val
(cons (cdar state) (cdr state)))))
(cons (cons (caar state) (car temp)) (cdr temp))))
(cons (car state) (setval (cons (- (car pos) 1) (cdr pos)) val (cdr state))))))
; state-swap
;
; This function takes a state and two positions and returns a new state with
; the values in those two positions swapped.
;
; parameters: state State to swap within
; a Position to swap with b
; b Position to swap with a
; return: State with a swapped with b
(defun state-swap (state a b)
(let ((olda (getval a state)) (oldb (getval b state)))
(setval a oldb (setval b olda state))))
A:
Here's one way to achieve it. Recreate the list using a function which will apply the appropriate mapping.
def swap(p, (r1,c1), (r2,c2)):
def getitem(r,c):
if (r,c) == (r1,c1): return p[r2][c2]
elif (r,c) == (r2,c2): return p[r1][c1]
return p[r][c]
return [ [getitem(r,c) for c in range(len(p[0]))] for r in range(len(p)) ]
You could even take this a step further and make the function be the actual interface, where each swap merely returns a function that does the appropriate conversions before passing through to the function below. Not particularly performant, but a fairly simple functional approach that dispenses with nasty mutable datastructures:
def swap(f, (r1,c1), (r2,c2)):
def getitem(r,c):
if (r,c) == (r1,c1): return f(r2,c2)
elif (r,c) == (r2,c2): return f(r1,c1)
return f(r,c)
return getitem
l=[ [1,2,3], [4,5,6], [7,8,0]]
f=lambda r,c: l[r][c] # Initial accessor function
f=swap(f, (2,1), (2,2)) # 8 right
f=swap(f, (1,1), (2,1)) # 5 down
print [[f(x,y) for y in range(3)] for x in range(3)]
# Gives: [[1, 2, 3], [4, 0, 6], [7, 5, 8]]
A:
Cool, thanks for the lisp code. I'll need to study it to make sure I get it.
As for the first answer, the first time I was "writing c" in lisp because that's the only way I knew how to program and didn't have a clue why anyone would use lisp. This time around, I've been playing around with scheme, but wanted to use python so if I got stuck on something I could "cheat" and use something pythonish, then while waiting for usenet answers go on to the next part of the problem.
| Questions for python->scheme conversion | I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.
I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.
I have a python function which can swap two tiles easily:
def swap(p, (r1, c1), (r2, c2)):
# Swaps *any* two locations and returns new configuration
# Does not concern itself with zero location, etc
# Not sure how to do this functionally
p_p = p[:]
temp = p_p[r1][c1]
p_p[r1][c1] = p_p[r2][c2]
p_p[r2][c2] = temp
return p_p
I'd like to turn this into something you might find in SICP, avoiding side effects, etc.
But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.
In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment?
How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?
| [
"You identified that your initial problem was trying to write C semantics in Lisp. Is it not repeating the mistake to try to write scheme semantics in python? I always try to learn language X as a paradigm as much as a language and write in the most x-ish way.\nIt might be justifiable if this was a business app you knew was going to be migrated, but otherwise I'd just write it in scheme to begin with.\n",
"I wrote an 8-puzzle solver in Lisp about a year ago. I just used a list of 3 lists, each sublist with 3 elements being the numbers. It's not constant time, but it is portable.\nAnyways, if you are really interested in doing this functionally (Scheme doesn't require you to) what is easiest to do is to create some helper functions that will get a specific value given row/col and 'set' a value given row/col. Instead of modifying the original data structure, the set operation will construct the new state based on the old state.\nThen you can write a swap operation based on these get and set operations. Here's what I wrote about a year ago in Common Lisp, but it's easily convertible to Scheme:\n; getval\n;\n; This function takes a position (r . c) where and returns the corresponding\n; number in the 8-puzzle state. For example, if you wanted (1 . 2) from\n; ((1 2 3) (4 5 6) (7 8 9)), the value would be 6. The r and c values begin\n; at 0.\n;\n; parameters: pos The position to get\n; state The 8-puzzle state\n; returns: The value at pos in state\n(defun getval (pos state)\n (if (null state) 'no-value\n (if (= 0 (car pos))\n (if (= 0 (cdr pos))\n (caar state)\n (getval (cons (car pos) (- (cdr pos) 1)) (list (cdar state))))\n (getval (cons (- (car pos) 1) (cdr pos)) (cdr state)))))\n\n; setval\n;\n; This function returns a state where the value at pos is replaced by val.\n; Like getval, this function is zero-based. Accessing beyond the size of\n; the state is undefined (and probably broken)\n;\n; parameters: pos Position to set\n; val Value to set\n; state State to modify\n; returns: New state where pos is val\n(defun setval (pos val state)\n (if (null state) '()\n (if (= 0 (car pos))\n (if (= 0 (cdr pos))\n (cons (cons val (cdar state)) (cdr state))\n (let ((temp (setval (cons (car pos) (- (cdr pos) 1)) val\n (cons (cdar state) (cdr state)))))\n (cons (cons (caar state) (car temp)) (cdr temp))))\n (cons (car state) (setval (cons (- (car pos) 1) (cdr pos)) val (cdr state))))))\n\n; state-swap\n;\n; This function takes a state and two positions and returns a new state with\n; the values in those two positions swapped.\n;\n; parameters: state State to swap within\n; a Position to swap with b\n; b Position to swap with a\n; return: State with a swapped with b\n(defun state-swap (state a b)\n (let ((olda (getval a state)) (oldb (getval b state)))\n (setval a oldb (setval b olda state))))\n\n",
"Here's one way to achieve it. Recreate the list using a function which will apply the appropriate mapping.\ndef swap(p, (r1,c1), (r2,c2)):\n def getitem(r,c):\n if (r,c) == (r1,c1): return p[r2][c2]\n elif (r,c) == (r2,c2): return p[r1][c1]\n return p[r][c]\n return [ [getitem(r,c) for c in range(len(p[0]))] for r in range(len(p)) ]\n\nYou could even take this a step further and make the function be the actual interface, where each swap merely returns a function that does the appropriate conversions before passing through to the function below. Not particularly performant, but a fairly simple functional approach that dispenses with nasty mutable datastructures:\ndef swap(f, (r1,c1), (r2,c2)):\n def getitem(r,c):\n if (r,c) == (r1,c1): return f(r2,c2)\n elif (r,c) == (r2,c2): return f(r1,c1)\n return f(r,c)\n return getitem\n\nl=[ [1,2,3], [4,5,6], [7,8,0]]\nf=lambda r,c: l[r][c] # Initial accessor function\nf=swap(f, (2,1), (2,2)) # 8 right\nf=swap(f, (1,1), (2,1)) # 5 down\nprint [[f(x,y) for y in range(3)] for x in range(3)]\n# Gives: [[1, 2, 3], [4, 0, 6], [7, 5, 8]]\n\n",
"Cool, thanks for the lisp code. I'll need to study it to make sure I get it.\nAs for the first answer, the first time I was \"writing c\" in lisp because that's the only way I knew how to program and didn't have a clue why anyone would use lisp. This time around, I've been playing around with scheme, but wanted to use python so if I got stuck on something I could \"cheat\" and use something pythonish, then while waiting for usenet answers go on to the next part of the problem.\n"
] | [
4,
2,
1,
0
] | [] | [] | [
"arrays",
"python",
"scheme"
] | stackoverflow_0000347010_arrays_python_scheme.txt |
Q:
Can I use Python to intercept global keystrokes in KDE?
I want to make a simple app, ideally in Python, that would run in the background on KDE, listening to all keystrokes being done by the user, so that the app goes to the foreground if a specific combination of keys is pressed. Is that doable? Can anyone point me to such resource?
A:
A quick google found this:
http://sourceforge.net/projects/pykeylogger/
You might be able to use some of the source code.
| Can I use Python to intercept global keystrokes in KDE? | I want to make a simple app, ideally in Python, that would run in the background on KDE, listening to all keystrokes being done by the user, so that the app goes to the foreground if a specific combination of keys is pressed. Is that doable? Can anyone point me to such resource?
| [
"A quick google found this:\nhttp://sourceforge.net/projects/pykeylogger/\nYou might be able to use some of the source code.\n"
] | [
1
] | [] | [] | [
"kde_plasma",
"python"
] | stackoverflow_0000347475_kde_plasma_python.txt |
Q:
What features of Python 3.0 will change your everyday coding?
Py3k just came out and has gobs of neat new stuff! I'm curious, what are SO pythonistas most excited about? What features are going to affect the way you write code on a daily basis, or have you been looking forward to?
A:
There are a few things I'm quite interested in:
Text and data instead of unicode and 8 bit
Extended Iterable Unpacking
Function annotations
Binary literals
New exception catching syntax
A number of Python 2.6 features, eg: the with statement
A:
I hope that exception chaining catches on. Losing exception stack traces due to the antipattern presented below had been my pet peeve for a long time:
try:
doSomething( someObject)
except:
someCleanup()
# Thanks for passing the error-causing object,
# but the original stack trace is lost :-(
raise MyError("Bad, bad object!", someObject)
I know, I know, adding some context info to the original exception and preserving the original stack trace was possible, but it required a really ugly hack. Now you can (and should!) just:
raise MyError("Bad, bad object!", someObject) from original_exception
and easily get both of the above. So, as a part of my holy mission against lost stack traces:
Folks, don't forget the from clause when reraising exceptions! Thank you.
A:
Quite frankly, none of it. While I'll probably find myself using some of the new syntax, I mainly use Python for quick and simple scripts and regular expressions.
I think the new features will make a lot of little things a little easier for a lot of people and a few big things easy for a few people. However, I am skeptical of any claims that a lot of people will end up finding massive gains in productivity.
In short, I think these changes will make things a little better overall, but don't expect any miracles.
A:
Not so much a feature, but I think the library cleanup will be of great help, esp. to new python programmers. On more than one occasion have I wanted to do something in python only to find two included libraries that offer that functionality, with no obvious reason why I should chose one over the other.
A:
Despite what they did to achieve smallest possible migration course with interpreted languages, I find the whole release of python3 as ten years of painful path of migration. Therefore I don't find it particularly attracting.
The improvements they did are all good and important. Two different types for strings have been a real source of annoyances everywhere, therefore it's good they got rid from unicode object and introduced bytes object aside now unicode str.
The bignum vs. num -change was from convenience and I think that too was a good choice. In overall they cleaned the language from harmful components they accumulated during the last ten years.
Second worst thing they did was 10% slower implementation, as if speed wouldn't be python's problem already.
I believe the release of python3 pushes down python's reputation rather than improves it. Right now they are back in the start with their language when it comes down to library support.
A:
Not having to do as much..
Not having to worry about using unicode() or u"".
Not having to search though the docs of urllib urllib2 and httplib to find where that functions I need to to encode a file and upload it via a POST request
Not having to worry about wether except TypeError, something: will catch a TypeError and something, or TypeError into `something..
And conversely, having to look at the docs again! I know python well enough now I can do most stuff without referring to pydoc, but every time that I do, I discover some other useful module or function.
A:
The print statement. <sniff> I'm starting to miss it already.
Actually, before even going to Python 2.6, we're purging print in favor of logging.debug. This is just to get out of the habit of using print casually for debugging, support and development.
What remains are some programs that actually produce stuff on stdout. For those, we may introduce a 2.6/3.0 compatible "print" function in one of our libraries.
A:
Dictionary comprehensions aren't necessarily earth-shattering but they're very nice.
While {k: v for k, v in list} is longer than dict(list) it's more flexible and self-explanitory.
A:
One of the most underestimated features of Python 3 is the introduction of Abstract Base Classes. This is something that won't revolutionize Python programming straight away, but represents an interesting shift from a loose duck typing approach into the direction of better defined interfaces.
More information can be found in PEP 3119.
A:
Just about all of them as I am taking the release of Python 3 as motivation to learn the language.
A:
Unicode (utf-8) is really important for people living in non-english speaking countries.
I didn't like to specify the encoding at the beginning of the file, because I always forget. Usually my text is compatible with ASCII because I'm using UTF-8, so it is working without the encoding specification. But If I write my name (with an accent) or a € sign, it breaks ... I ended up writing unicode characters with their \uxxxx representation but it is kinda cryptic!
| What features of Python 3.0 will change your everyday coding? | Py3k just came out and has gobs of neat new stuff! I'm curious, what are SO pythonistas most excited about? What features are going to affect the way you write code on a daily basis, or have you been looking forward to?
| [
"There are a few things I'm quite interested in:\n\nText and data instead of unicode and 8 bit\nExtended Iterable Unpacking\nFunction annotations\nBinary literals\nNew exception catching syntax\nA number of Python 2.6 features, eg: the with statement\n\n",
"I hope that exception chaining catches on. Losing exception stack traces due to the antipattern presented below had been my pet peeve for a long time:\ntry:\n doSomething( someObject)\nexcept:\n someCleanup()\n\n # Thanks for passing the error-causing object,\n # but the original stack trace is lost :-(\n\n raise MyError(\"Bad, bad object!\", someObject)\n\nI know, I know, adding some context info to the original exception and preserving the original stack trace was possible, but it required a really ugly hack. Now you can (and should!) just:\nraise MyError(\"Bad, bad object!\", someObject) from original_exception\n\nand easily get both of the above. So, as a part of my holy mission against lost stack traces:\nFolks, don't forget the from clause when reraising exceptions! Thank you.\n",
"Quite frankly, none of it. While I'll probably find myself using some of the new syntax, I mainly use Python for quick and simple scripts and regular expressions.\nI think the new features will make a lot of little things a little easier for a lot of people and a few big things easy for a few people. However, I am skeptical of any claims that a lot of people will end up finding massive gains in productivity.\nIn short, I think these changes will make things a little better overall, but don't expect any miracles.\n",
"Not so much a feature, but I think the library cleanup will be of great help, esp. to new python programmers. On more than one occasion have I wanted to do something in python only to find two included libraries that offer that functionality, with no obvious reason why I should chose one over the other. \n",
"Despite what they did to achieve smallest possible migration course with interpreted languages, I find the whole release of python3 as ten years of painful path of migration. Therefore I don't find it particularly attracting.\nThe improvements they did are all good and important. Two different types for strings have been a real source of annoyances everywhere, therefore it's good they got rid from unicode object and introduced bytes object aside now unicode str.\nThe bignum vs. num -change was from convenience and I think that too was a good choice. In overall they cleaned the language from harmful components they accumulated during the last ten years.\nSecond worst thing they did was 10% slower implementation, as if speed wouldn't be python's problem already.\nI believe the release of python3 pushes down python's reputation rather than improves it. Right now they are back in the start with their language when it comes down to library support.\n",
"Not having to do as much..\n\nNot having to worry about using unicode() or u\"\".\nNot having to search though the docs of urllib urllib2 and httplib to find where that functions I need to to encode a file and upload it via a POST request\nNot having to worry about wether except TypeError, something: will catch a TypeError and something, or TypeError into `something..\n\nAnd conversely, having to look at the docs again! I know python well enough now I can do most stuff without referring to pydoc, but every time that I do, I discover some other useful module or function.\n",
"The print statement. <sniff> I'm starting to miss it already.\nActually, before even going to Python 2.6, we're purging print in favor of logging.debug. This is just to get out of the habit of using print casually for debugging, support and development.\nWhat remains are some programs that actually produce stuff on stdout. For those, we may introduce a 2.6/3.0 compatible \"print\" function in one of our libraries.\n",
"Dictionary comprehensions aren't necessarily earth-shattering but they're very nice.\nWhile {k: v for k, v in list} is longer than dict(list) it's more flexible and self-explanitory.\n",
"One of the most underestimated features of Python 3 is the introduction of Abstract Base Classes. This is something that won't revolutionize Python programming straight away, but represents an interesting shift from a loose duck typing approach into the direction of better defined interfaces.\nMore information can be found in PEP 3119.\n",
"Just about all of them as I am taking the release of Python 3 as motivation to learn the language.\n",
"Unicode (utf-8) is really important for people living in non-english speaking countries.\nI didn't like to specify the encoding at the beginning of the file, because I always forget. Usually my text is compatible with ASCII because I'm using UTF-8, so it is working without the encoding specification. But If I write my name (with an accent) or a € sign, it breaks ... I ended up writing unicode characters with their \\uxxxx representation but it is kinda cryptic!\n"
] | [
17,
7,
6,
4,
3,
3,
2,
2,
2,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0000340972_python_python_3.x.txt |
Q:
What is the most efficient way of extracting information from a large number of xml files in python?
I have a directory full (~103, 104) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data.
Is there a more efficient way? (simple text matching doesn't work)
Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?
Any caveats?
Thanks!
A:
Usually, I would suggest using ElementTree's iterparse, or for extra-speed, its counterpart from lxml. Also try to use Processing (comes built-in with 2.6) to parallelize.
The important thing about iterparse is that you get the element (sub-)structures as they are parsed.
import xml.etree.cElementTree as ET
xml_it = ET.iterparse("some.xml")
event, elem = xml_it.next()
event will always be the string "end" in this case, but you can also initialize the parser to also tell you about new elements as they are parsed. You don't have any guarantee that all children elements will have been parsed at that point, but the attributes are there, if you are only interested in that.
Another point is that you can stop reading elements from iterator early, i.e. before the whole document has been processed.
If the files are large (are they?), there is a common idiom to keep memory usage constant just as in a streaming parser.
A:
The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work.
But the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amount of time, and will give you real numbers do drive you forward.
EDIT:
Are the files on a local drive or network drive? Network I/O will kill you here.
The problem parallelizes trivially - you can split the work among several computers (or several processes on a multicore computer).
A:
If you know that the XML files are generated using the ever-same algorithm, it might be more efficient to not do any XML parsing at all. E.g. if you know that the data is in lines 3, 4, and 5, you might read through the file line-by-line, and then use regular expressions.
Of course, that approach would fail if the files are not machine-generated, or originate from different generators, or if the generator changes over time. However, I'm optimistic that it would be more efficient.
Whether or not you recycle the parser objects is largely irrelevant. Many more objects will get created, so a single parser object doesn't really count much.
A:
One thing you didn't indicate is whether or not you're reading the XML into a DOM of some kind. I'm guessing that you're probably not, but on the off chance you are, don't. Use xml.sax instead. Using SAX instead of DOM will get you a significant performance boost.
| What is the most efficient way of extracting information from a large number of xml files in python? | I have a directory full (~103, 104) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data.
Is there a more efficient way? (simple text matching doesn't work)
Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?
Any caveats?
Thanks!
| [
"Usually, I would suggest using ElementTree's iterparse, or for extra-speed, its counterpart from lxml. Also try to use Processing (comes built-in with 2.6) to parallelize.\nThe important thing about iterparse is that you get the element (sub-)structures as they are parsed.\nimport xml.etree.cElementTree as ET\nxml_it = ET.iterparse(\"some.xml\")\nevent, elem = xml_it.next()\n\nevent will always be the string \"end\" in this case, but you can also initialize the parser to also tell you about new elements as they are parsed. You don't have any guarantee that all children elements will have been parsed at that point, but the attributes are there, if you are only interested in that.\nAnother point is that you can stop reading elements from iterator early, i.e. before the whole document has been processed.\nIf the files are large (are they?), there is a common idiom to keep memory usage constant just as in a streaming parser.\n",
"The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work.\nBut the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amount of time, and will give you real numbers do drive you forward.\nEDIT:\n\nAre the files on a local drive or network drive? Network I/O will kill you here.\nThe problem parallelizes trivially - you can split the work among several computers (or several processes on a multicore computer).\n\n",
"If you know that the XML files are generated using the ever-same algorithm, it might be more efficient to not do any XML parsing at all. E.g. if you know that the data is in lines 3, 4, and 5, you might read through the file line-by-line, and then use regular expressions.\nOf course, that approach would fail if the files are not machine-generated, or originate from different generators, or if the generator changes over time. However, I'm optimistic that it would be more efficient.\nWhether or not you recycle the parser objects is largely irrelevant. Many more objects will get created, so a single parser object doesn't really count much.\n",
"One thing you didn't indicate is whether or not you're reading the XML into a DOM of some kind. I'm guessing that you're probably not, but on the off chance you are, don't. Use xml.sax instead. Using SAX instead of DOM will get you a significant performance boost.\n"
] | [
4,
3,
1,
1
] | [] | [] | [
"expat_parser",
"large_files",
"performance",
"python",
"xml"
] | stackoverflow_0000344559_expat_parser_large_files_performance_python_xml.txt |
Q:
Python distutils and replacing strings in code
I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?
A:
For modules paths, a common practice is putting them in .pth files, as documented here. The site module provides a space for Site-specific configuration hooks, you can use it to tailor your environment.
A:
Well, with distutils (in the standard library) you have "package data". This is data that lives inside the package itself. Explained here how to do it. This is clearly not ideal, as you will have to use some kind of __file__ hacks to look up the location of the data at runtime.
So then comes setuptools (not in the standard library), which additionally has ways of looking up the location of that data at runtime. Explained here how to do it. But again that has it's own set of problems, for example, it may have trouble finding the data files on an uninstalled raw package.
There are also additional third party tools. The one I have used is kiwi.environ. It offers data directories, and runtime lookup, but I wouldn't recommend it for general use, as it is geared towards PyGTK development and Glade file location.
I would imagine there are other third party tools around, and others will elaborate.
A:
Currently, the best way to bundle data with code is going the setuptools way and use pkg_resources:
from pkg_resources import resource_filename, resource_stream
stream = resource_stream("PACKAGE", "path/to/data_f.ile")
This has the advantage of also working with Python eggs. It has the (IMHO) disadvantage that you need to put your data files into your code directory, which is accepted practice (one of the very, very few practices I disagree with).
As for Linux distros, I can (reasonably) assure you that your program will run without any problems (and patches) on any modern Debian-derived system if you use pkg_resources. I don't know about Fedora/openSUSE, but I would assume that it works as well.
It works on Windows, but it does currently not work with py2exe - there are simple workarounds for that, however.
A:
The OP here, I've not finally managed to log in using my OpenID.
@S.Lott
Point well taken, but for some Linux distros it seems to be standard to install application-specific data and application-specific modules in specific locations. I think that making these locations configurable at build/install time is a nice thing to do for people packaging my application. AFAICS “the pythonic way” in this case would force these packagers to apply patches to my code.
I'm also in the habit of writing applications where the executable part is a tiny wrapper around a main function in an application-specific module. To me it doesn't seem right to stick this application-specific module in /usr/lib/python2.5/site-packages.
| Python distutils and replacing strings in code | I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?
| [
"For modules paths, a common practice is putting them in .pth files, as documented here. The site module provides a space for Site-specific configuration hooks, you can use it to tailor your environment.\n",
"Well, with distutils (in the standard library) you have \"package data\". This is data that lives inside the package itself. Explained here how to do it. This is clearly not ideal, as you will have to use some kind of __file__ hacks to look up the location of the data at runtime.\nSo then comes setuptools (not in the standard library), which additionally has ways of looking up the location of that data at runtime. Explained here how to do it. But again that has it's own set of problems, for example, it may have trouble finding the data files on an uninstalled raw package.\nThere are also additional third party tools. The one I have used is kiwi.environ. It offers data directories, and runtime lookup, but I wouldn't recommend it for general use, as it is geared towards PyGTK development and Glade file location.\nI would imagine there are other third party tools around, and others will elaborate.\n",
"Currently, the best way to bundle data with code is going the setuptools way and use pkg_resources:\nfrom pkg_resources import resource_filename, resource_stream\nstream = resource_stream(\"PACKAGE\", \"path/to/data_f.ile\")\n\nThis has the advantage of also working with Python eggs. It has the (IMHO) disadvantage that you need to put your data files into your code directory, which is accepted practice (one of the very, very few practices I disagree with). \nAs for Linux distros, I can (reasonably) assure you that your program will run without any problems (and patches) on any modern Debian-derived system if you use pkg_resources. I don't know about Fedora/openSUSE, but I would assume that it works as well.\nIt works on Windows, but it does currently not work with py2exe - there are simple workarounds for that, however.\n",
"The OP here, I've not finally managed to log in using my OpenID.\n@S.Lott\nPoint well taken, but for some Linux distros it seems to be standard to install application-specific data and application-specific modules in specific locations. I think that making these locations configurable at build/install time is a nice thing to do for people packaging my application. AFAICS “the pythonic way” in this case would force these packagers to apply patches to my code.\nI'm also in the habit of writing applications where the executable part is a tiny wrapper around a main function in an application-specific module. To me it doesn't seem right to stick this application-specific module in /usr/lib/python2.5/site-packages.\n"
] | [
1,
1,
1,
0
] | [
"\"I often find a need to put paths in my code\" -- this isn't very Pythonic to begin with.\nIdeally, your code lives in some place like site-packages and that's the end of that.\nOften, we have an installed \"application\" that uses a fairly fixed set of directories for working files. In linux, we get this information from environment variables and configuration files owned by the specific userid that's running the application.\nI don't think that you should be putting paths in your code. I think there's a better way.\n[I just wrote our app installation tool, which does create all the config files for a fairly complex app. I used the Mako templates tool to generate all four files from templates.]\n"
] | [
-1
] | [
"python"
] | stackoverflow_0000267977_python.txt |
Q:
Notification Library for Windows
I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.
I have looked at Snarl, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.
Which one do you recommend?
Python support is a huge plus.
A:
You can do it by depending on a GUI library.
For example, with PyQt,it is possible :
PyQt QSystemTrayIcon Documentation
QSystemTrayIcon Class Reference
Example of QSystemTrayIcon (in C++, easy to adapt to python)
A:
I wrote one for .NET for the Genghis project (link here) a while back. Looks like it is over at MS CodePlex now. Look for the "AniForm" class. Here is a screenshot.
It has more of an older MSN Messenger look and feel but should get you started.
A:
Are you developing the application in Python? It depends what GUI toolkit you're using.
If you're using wxPython, you could try ToasterBox, or the wxPopupWindow.
A:
You don't need anyhting.
Just use toasters windows with Win32 api
| Notification Library for Windows | I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.
I have looked at Snarl, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.
Which one do you recommend?
Python support is a huge plus.
| [
"You can do it by depending on a GUI library.\nFor example, with PyQt,it is possible :\n\nPyQt QSystemTrayIcon Documentation\nQSystemTrayIcon Class Reference\nExample of QSystemTrayIcon (in C++, easy to adapt to python)\n\n",
"I wrote one for .NET for the Genghis project (link here) a while back. Looks like it is over at MS CodePlex now. Look for the \"AniForm\" class. Here is a screenshot.\nIt has more of an older MSN Messenger look and feel but should get you started.\n",
"Are you developing the application in Python? It depends what GUI toolkit you're using.\nIf you're using wxPython, you could try ToasterBox, or the wxPopupWindow.\n",
"You don't need anyhting.\nJust use toasters windows with Win32 api\n"
] | [
3,
2,
2,
1
] | [] | [] | [
"notifications",
"python",
"windows"
] | stackoverflow_0000344442_notifications_python_windows.txt |
Q:
Run a shortcut under windows
The following doesn't work, because it doesn't wait until the process is finished:
import subprocess
p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True)
p.wait()
Any idea how to run a shortcut and wait that the subprocess returns ?
Edit: originally I was trying this without the shell option in my post, which caused Popen to fail. In effect, start is not an executable but a shell command. This was fixed thanks to Jim.
A:
You will need to invoke a shell to get the subprocess option to work:
p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True)
p.wait()
This however will still exit immediately (see @R. Bemrose).
If p.pid contains the correct pid (I'm not sure on windows), then you could use os.waitpid() to wait for the program to exit. Otherwise you may need to use some win32 com magic.
A:
cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ):
If Command Extensions are enabled,
external command invocation through
the command line or the START command
changes as follows:
...
When executing an application that is
a 32-bit GUI application, CMD.EXE
does not wait for the application to terminate before returning to
the command prompt. This new behavior does NOT occur if executing
within a command script.
How this is affected by the /wait flag, I'm not sure.
A:
Note: I am simply adding on Jim's reply, with a small trick.
What about using 'WAIT' option for start?
p = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True)
p.wait()
This should work.
| Run a shortcut under windows | The following doesn't work, because it doesn't wait until the process is finished:
import subprocess
p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True)
p.wait()
Any idea how to run a shortcut and wait that the subprocess returns ?
Edit: originally I was trying this without the shell option in my post, which caused Popen to fail. In effect, start is not an executable but a shell command. This was fixed thanks to Jim.
| [
"You will need to invoke a shell to get the subprocess option to work:\np = subprocess.Popen('start /B MOZILL~1.LNK', shell=True)\np.wait()\n\nThis however will still exit immediately (see @R. Bemrose).\nIf p.pid contains the correct pid (I'm not sure on windows), then you could use os.waitpid() to wait for the program to exit. Otherwise you may need to use some win32 com magic.\n",
"cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ):\n\nIf Command Extensions are enabled,\n external command invocation through\n the command line or the START command\n changes as follows:\n\n...\n\nWhen executing an application that is\n a 32-bit GUI application, CMD.EXE\n does not wait for the application to terminate before returning to\n the command prompt. This new behavior does NOT occur if executing\n within a command script.\n\nHow this is affected by the /wait flag, I'm not sure.\n",
"Note: I am simply adding on Jim's reply, with a small trick.\nWhat about using 'WAIT' option for start?\np = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True)\np.wait()\n\nThis should work.\n"
] | [
4,
3,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000349653_python_windows.txt |
Q:
Python for C++ Developers
I'm a long time C++/Java developer trying to get into Python and am looking for the stereotypical "Python for C++ Developers" article, but coming up blank. I've seen these sort of things for C#, Java, etc, and they're incredibly useful for getting up to speed on language features and noteworthy differences. Anyone have any references?
As a secondary bonus question, what open source Python program would you suggest looking at for clean design, commenting, and use of the language as a point of reference for study?
Thanks in advance.
A:
I never really understood the "Language X for Language Y developers" approach. When I go looking to learn Language X I want to learn how to program in it the way that Language X programmers do, not the way Language Y programmers do. I want to learn the features, idioms, etc. that are unique to the language that I am learning. I want to be able to take advantage of the things that make the language special and use that knowledge to expand my ways of thinking and solving problems. I don't think I would get the same sort of insights from a tutorial that was framed in the context of another language. If you can learn your first language without a tutorial geared towards something you already know you should be able to pick up a second language the same way (and in my experience, the more languages you know the easier it is to learn new ones).
With that said, I would recommend The Python Tutorial as a good, quick, and easy way to get going with Python and Dive Into Python as a more complete introduction, also available for free here. I would also agree with what others have said regarding looking at the code for the standard libraries as a source of good examples and design practices, the standard python libraries are pretty clean and easy to read.
A:
Dive Into Python is a Python book for experienced programmers.
A:
Dive Into Python is great, but don't forget PJE's Python Is Not Java.
A:
I learned a lot about Python by reading the source of the standard library that ships with Python. I seem to remember having a few "a-ha!" moments when reading urllib2.py in particular.
A:
To learn the language the free and online python tutorial is really all that you need to pick up the language and start writing apps. If you want a book, I've found Beginning Python from Apress to be an excellent reference and tutorial. Of course the best way to learn a language is to write code, thus I would recommend that you check out Boost.Python. If you have a C++ that needs to be a bit more flexible, Boost.Python can give you a good excuse to learn Python and get paid for it.
A:
Python is sufficiently different from C++ so that specific knowledge can't normally be transferred. There are a few language comparisons available. What you can carry over is knowledge of specific APIs, e.g. of the POSIX or socket APIs.
As an example for a typical Python (GUI) application, look at IDLE (as shipped for Python).
A:
C# and Java are seen as cleaner replacements for C++ in many application areas so there is often a "migration" from one to the other - which is why there are books available.
Python and C++ are very different beasts, and although they are both considered general purpose programming languages they are targetted towards different ends of the programming spectrum.
Don't try to write C++ in Python; in fact, try to forget C++ when writing Python.
I found it far better to learn the common Python paradigms and techniques and apply them to my C++ programs than the other way around.
A:
For the best examples of code of a language, the language's standard library is often a good place to look. Pick a recent piece, though - old parts are probably written for older versions and also sometimes were written before the library became big enough to warrant big standards - like PHP and Erlang's libraries, which have internal inconsistency.
For Python in particular, Python 3000 is cleaning up the library a lot, and so is probably a great source of good Python code (though it is written for a future Python version).
| Python for C++ Developers | I'm a long time C++/Java developer trying to get into Python and am looking for the stereotypical "Python for C++ Developers" article, but coming up blank. I've seen these sort of things for C#, Java, etc, and they're incredibly useful for getting up to speed on language features and noteworthy differences. Anyone have any references?
As a secondary bonus question, what open source Python program would you suggest looking at for clean design, commenting, and use of the language as a point of reference for study?
Thanks in advance.
| [
"I never really understood the \"Language X for Language Y developers\" approach. When I go looking to learn Language X I want to learn how to program in it the way that Language X programmers do, not the way Language Y programmers do. I want to learn the features, idioms, etc. that are unique to the language that I am learning. I want to be able to take advantage of the things that make the language special and use that knowledge to expand my ways of thinking and solving problems. I don't think I would get the same sort of insights from a tutorial that was framed in the context of another language. If you can learn your first language without a tutorial geared towards something you already know you should be able to pick up a second language the same way (and in my experience, the more languages you know the easier it is to learn new ones).\nWith that said, I would recommend The Python Tutorial as a good, quick, and easy way to get going with Python and Dive Into Python as a more complete introduction, also available for free here. I would also agree with what others have said regarding looking at the code for the standard libraries as a source of good examples and design practices, the standard python libraries are pretty clean and easy to read.\n",
"Dive Into Python is a Python book for experienced programmers.\n",
"Dive Into Python is great, but don't forget PJE's Python Is Not Java.\n",
"I learned a lot about Python by reading the source of the standard library that ships with Python. I seem to remember having a few \"a-ha!\" moments when reading urllib2.py in particular.\n",
"To learn the language the free and online python tutorial is really all that you need to pick up the language and start writing apps. If you want a book, I've found Beginning Python from Apress to be an excellent reference and tutorial. Of course the best way to learn a language is to write code, thus I would recommend that you check out Boost.Python. If you have a C++ that needs to be a bit more flexible, Boost.Python can give you a good excuse to learn Python and get paid for it.\n",
"Python is sufficiently different from C++ so that specific knowledge can't normally be transferred. There are a few language comparisons available. What you can carry over is knowledge of specific APIs, e.g. of the POSIX or socket APIs.\nAs an example for a typical Python (GUI) application, look at IDLE (as shipped for Python).\n",
"C# and Java are seen as cleaner replacements for C++ in many application areas so there is often a \"migration\" from one to the other - which is why there are books available.\nPython and C++ are very different beasts, and although they are both considered general purpose programming languages they are targetted towards different ends of the programming spectrum.\nDon't try to write C++ in Python; in fact, try to forget C++ when writing Python.\nI found it far better to learn the common Python paradigms and techniques and apply them to my C++ programs than the other way around.\n",
"For the best examples of code of a language, the language's standard library is often a good place to look. Pick a recent piece, though - old parts are probably written for older versions and also sometimes were written before the library became big enough to warrant big standards - like PHP and Erlang's libraries, which have internal inconsistency.\nFor Python in particular, Python 3000 is cleaning up the library a lot, and so is probably a great source of good Python code (though it is written for a future Python version).\n"
] | [
24,
13,
5,
4,
2,
1,
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0000328577_c++_python.txt |
Q:
Why is my Python C Extension leaking memory?
The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?
static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){
PyObject *o; //generic object
PyObject* pyDB = NULL; //this has to be a py file object
if (!PyArg_ParseTuple(args, "O", &pyDB)){
return NULL;
} else {
Py_INCREF(pyDB);
if (!PyFile_Check(pyDB)){
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle");
return NULL;
}
}
FILE *fhDB = PyFile_AsFile(pyDB);
long offset = 0;
DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER));
fseek(fhDB,offset,SEEK_SET); //at the beginning
fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB );
if (ferror(fhDB)){
fclose(fhDB);
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "failed reading database header");
return NULL;
}
Py_DECREF(pyDB);
PyObject *pyDBHeader = PyDict_New();
Py_INCREF(pyDBHeader);
o=PyInt_FromLong(pdbHeader->version_number);
PyDict_SetItemString(pyDBHeader, "version", o);
Py_DECREF(o);
PyObject *pyTimeList = PyList_New(0);
Py_INCREF(pyTimeList);
int i;
for (i=0; i<NUM_DRAWERS; i++){
//epochs
o=PyInt_FromLong(pdbHeader->last_good_test[i]);
PyList_Append(pyTimeList, o);
Py_DECREF(o);
}
PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList);
Py_DECREF(pyTimeList);
o=PyInt_FromLong(pdbHeader->temp);
PyDict_SetItemString(pyDBHeader, "temp", o);
Py_DECREF(o);
free(pdbHeader);
return (pyDBHeader);
}
Thanks for taking a look,
LarsenMTL
A:
PyDict_New() returns a new reference, check the docs for PyDict. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways.
You also don't need to incref pyTimeList. It's yours when you create it. However, you need to decref it, but you only decref it once, so it's leaked as well.
You also don't need to call Py_INCREF on pyDB. It's a borrowed reference and it won't go away as long as your function does not return, because it's still referenced in a lower stack frame.
Only if you want to keep the reference in another structure somewhere, you need to increse the refcount.
Cf. the API docs
A:
OT: Using successive calls to PyList_Append is a performance issue. Since you know how many results you'll get in advance, you can use:
PyObject *pyTimeList = PyList_New(NUM_DRAWERS);
int i;
for (i=0; i<NUM_DRAWERS; i++){
o = PyInt_FromLong(pdbHeader->last_good_test[i]);
PyList_SET_ITEM(pyTimeList, i, o);
}
Observe that you may not decrease the refcount of o after calling PyList_SET_ITEM, because it "steals" a reference. Check the docs.
A:
I don't know about Python-C. However, My experience with COM reference counting says that a newly created reference-counted object has a reference count of 1. So your Py_INCREF(pyDB) after PyArg_ParseTuple(args, "O", &pyDB) and PyObject *pyDBHeader = PyDict_New(); are the culprit. Their reference counts are already 2.
| Why is my Python C Extension leaking memory? | The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?
static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){
PyObject *o; //generic object
PyObject* pyDB = NULL; //this has to be a py file object
if (!PyArg_ParseTuple(args, "O", &pyDB)){
return NULL;
} else {
Py_INCREF(pyDB);
if (!PyFile_Check(pyDB)){
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle");
return NULL;
}
}
FILE *fhDB = PyFile_AsFile(pyDB);
long offset = 0;
DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER));
fseek(fhDB,offset,SEEK_SET); //at the beginning
fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB );
if (ferror(fhDB)){
fclose(fhDB);
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "failed reading database header");
return NULL;
}
Py_DECREF(pyDB);
PyObject *pyDBHeader = PyDict_New();
Py_INCREF(pyDBHeader);
o=PyInt_FromLong(pdbHeader->version_number);
PyDict_SetItemString(pyDBHeader, "version", o);
Py_DECREF(o);
PyObject *pyTimeList = PyList_New(0);
Py_INCREF(pyTimeList);
int i;
for (i=0; i<NUM_DRAWERS; i++){
//epochs
o=PyInt_FromLong(pdbHeader->last_good_test[i]);
PyList_Append(pyTimeList, o);
Py_DECREF(o);
}
PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList);
Py_DECREF(pyTimeList);
o=PyInt_FromLong(pdbHeader->temp);
PyDict_SetItemString(pyDBHeader, "temp", o);
Py_DECREF(o);
free(pdbHeader);
return (pyDBHeader);
}
Thanks for taking a look,
LarsenMTL
| [
"PyDict_New() returns a new reference, check the docs for PyDict. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways.\nYou also don't need to incref pyTimeList. It's yours when you create it. However, you need to decref it, but you only decref it once, so it's leaked as well.\nYou also don't need to call Py_INCREF on pyDB. It's a borrowed reference and it won't go away as long as your function does not return, because it's still referenced in a lower stack frame. \nOnly if you want to keep the reference in another structure somewhere, you need to increse the refcount.\nCf. the API docs\n",
"OT: Using successive calls to PyList_Append is a performance issue. Since you know how many results you'll get in advance, you can use:\nPyObject *pyTimeList = PyList_New(NUM_DRAWERS);\nint i;\nfor (i=0; i<NUM_DRAWERS; i++){\n o = PyInt_FromLong(pdbHeader->last_good_test[i]);\n PyList_SET_ITEM(pyTimeList, i, o);\n}\n\nObserve that you may not decrease the refcount of o after calling PyList_SET_ITEM, because it \"steals\" a reference. Check the docs.\n",
"I don't know about Python-C. However, My experience with COM reference counting says that a newly created reference-counted object has a reference count of 1. So your Py_INCREF(pyDB) after PyArg_ParseTuple(args, \"O\", &pyDB) and PyObject *pyDBHeader = PyDict_New(); are the culprit. Their reference counts are already 2.\n"
] | [
17,
5,
3
] | [] | [] | [
"c",
"python",
"refcounting"
] | stackoverflow_0000350647_c_python_refcounting.txt |
Q:
What does the function set use to check if two objects are different?
Simple code:
>>> set([2,2,1,2,2,2,3,3,5,1])
set([1, 2, 3, 5])
Ok, in the resulting sets there are no duplicates.
What if the object in the list are not int but are some defined by me?
What method does it check to understand if they are different? I implemented __eq__ and __cmp__ with some objects but set doesn't seems to use them :\
Does anyone know how to solve this?
A:
According to the set documentation, the elements must be hashable.
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.
EDIT: added proper Hashable definition thanks to Roberto
| What does the function set use to check if two objects are different? | Simple code:
>>> set([2,2,1,2,2,2,3,3,5,1])
set([1, 2, 3, 5])
Ok, in the resulting sets there are no duplicates.
What if the object in the list are not int but are some defined by me?
What method does it check to understand if they are different? I implemented __eq__ and __cmp__ with some objects but set doesn't seems to use them :\
Does anyone know how to solve this?
| [
"According to the set documentation, the elements must be hashable. \nAn object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.\nEDIT: added proper Hashable definition thanks to Roberto\n"
] | [
13
] | [] | [] | [
"methods",
"python",
"set"
] | stackoverflow_0000351271_methods_python_set.txt |
Q:
Determine record in multi record html form
In a html form, I'm displaying multiple records from a table, ready for update.
Right now I use: name=<column-name>_<pk-id> value=<value> for the fields.
Then in my python-script I go for:
for key in form.keys():
if key.startswith('<name-A>_'):
update <table> set <name-A> = <value> where pk=<pk-id>
if key.startswith('<name-B>_'):
update <table> set <name-B> = <value> where pk=<pk-id>
Is there a more 'organic' way to handle multi-record forms?
A:
In java apps, it's common to JSONify the name.
<input name="records[pk].fieldName"/>
pk being the primary key of the row and fieldName the field. Of course most frameworks handle this transparently. Each record ends up as a instance of a class with a property for each field, all of which are put into a list called "records". You may have to write some sort of interpreter, but that shouldn't be too hard.
| Determine record in multi record html form | In a html form, I'm displaying multiple records from a table, ready for update.
Right now I use: name=<column-name>_<pk-id> value=<value> for the fields.
Then in my python-script I go for:
for key in form.keys():
if key.startswith('<name-A>_'):
update <table> set <name-A> = <value> where pk=<pk-id>
if key.startswith('<name-B>_'):
update <table> set <name-B> = <value> where pk=<pk-id>
Is there a more 'organic' way to handle multi-record forms?
| [
"In java apps, it's common to JSONify the name.\n<input name=\"records[pk].fieldName\"/>\n\npk being the primary key of the row and fieldName the field. Of course most frameworks handle this transparently. Each record ends up as a instance of a class with a property for each field, all of which are put into a list called \"records\". You may have to write some sort of interpreter, but that shouldn't be too hard.\n"
] | [
1
] | [] | [] | [
"cgi",
"html",
"python"
] | stackoverflow_0000351440_cgi_html_python.txt |
Q:
How do I get data from stdin using os.system()
The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call os.system(). Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(0). Alternately somebody could show be how to properly use urllib.
A:
From Dive into Python:
import urllib
sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
htmlsource = sock.read()
sock.close()
print htmlsource
That will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.
Example using urllib2 from the Python Library Reference:
import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)
Edit: Also you might want to take a look at wget.
Edit2: Added urllib2 example based on S.Lott's advice
A:
Answering the question,
Python has a subprocess module which allows you to interact with spawned processes.http://docs.python.org/library/subprocess.html#subprocess.Popen
It allows you to read the stdout for the invoked process, and even send items to the stdin.
however as you said urllib is a much better option. if you search stackoverflow i am sure you will find at least 10 other related questions...
A:
As an alternetive to urllib, you could use the libCurl Python bindings.
| How do I get data from stdin using os.system() | The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call os.system(). Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(0). Alternately somebody could show be how to properly use urllib.
| [
"From Dive into Python: \nimport urllib\nsock = urllib.urlopen(\"http://en.wikipedia.org/wiki/Python_(programming_language)\")\nhtmlsource = sock.read()\nsock.close()\nprint htmlsource\n\nThat will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.\nExample using urllib2 from the Python Library Reference: \nimport urllib2\nf = urllib2.urlopen('http://www.python.org/')\nprint f.read(100)\n\nEdit: Also you might want to take a look at wget.\nEdit2: Added urllib2 example based on S.Lott's advice\n",
"Answering the question,\nPython has a subprocess module which allows you to interact with spawned processes.http://docs.python.org/library/subprocess.html#subprocess.Popen\nIt allows you to read the stdout for the invoked process, and even send items to the stdin.\nhowever as you said urllib is a much better option. if you search stackoverflow i am sure you will find at least 10 other related questions...\n",
"As an alternetive to urllib, you could use the libCurl Python bindings.\n"
] | [
7,
2,
0
] | [] | [] | [
"curl",
"os.system",
"python",
"shell",
"urllib"
] | stackoverflow_0000351456_curl_os.system_python_shell_urllib.txt |
Q:
Formatting a data structure into a comma-separated list of arguments
I need to convert a list (or a dict) into a comma-separated list for passing to another language.
Is there a nicer way of doing this than:
result = ''
args = ['a', 'b', 'c', 'd']
i = 0
for arg in args:
if i != 0: result += arg
else: result += arg + ', '
i += 1
result = 'function (' + result + ')
Thanks,
Dan
A:
', '.join(args) will do the trick.
A:
'function(%s)' % ', '.join(args)
produces
'function(a, b, c, d)'
A:
result = 'function (%s)' % ', '.join(map(str,args))
I recommend the map(str, args) instead of just args because some of your arguments could potentially not be strings and would cause a TypeError, for example, with an int argument in your list:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
When you get into dict objects you will probably want to comma-separate the values of the dict (presumably because the values are what you want to pass into this function). If you do the join method on the dict object itself, you will get the keys separated, like so:
>>> d = {'d':5, 'f':6.0, 'r':"BOB"}
>>> ','.join(d)
'r,d,f'
What you want is the following:
>>> d = {'d':5, 'f':6.0, 'r':"BOB"}
>>> result = 'function (%s)' % ', '.join(map(str, d.values()))
>>> result
'function (BOB, 5, 6.0)'
Note the new problem you encounter, however. When you pass a string argument through the join function, it loses its quoting. So if you planned to pass strings through, you have lost the quotes that usually would surround the string when passed into a function (strings are quoted in many general-purpose languages). If you're only passing numbers, however, this isn't a problem for you.
There is probably a nicer way of solving the problem I just described, but here's one method that could work for you.
>>> l = list()
>>> for val in d.values():
... try:
... v = float(val) #half-decent way of checking if something is an int, float, boolean
... l.append(val) #if it was, then append the original type to the list
... except:
... #wasn't a number, assume it's a string and surround with quotes
... l.append("\"" + val + "\"")
...
>>> result = 'function (%s)' % ', '.join(map(str, l))
>>> result
'function ("BOB", 5, 6.0)'
Now the string has quotes surrounding itself. If you are passing more complex types than numeric primitives and strings then you probably need a new question :)
One last note: I have been using d.values() to show how to extract the values from a dictionary, but in fact that will return the values from the dictionary in pretty much arbitrary order. Since your function most likely requires the arguments in a particular order, you should manually construct your list of values instead of calling d.values().
A:
Why not use a standard that both languages can parse, like JSON, XML, or YAML? simplejson is handy, and included as json in python 2.6.
| Formatting a data structure into a comma-separated list of arguments | I need to convert a list (or a dict) into a comma-separated list for passing to another language.
Is there a nicer way of doing this than:
result = ''
args = ['a', 'b', 'c', 'd']
i = 0
for arg in args:
if i != 0: result += arg
else: result += arg + ', '
i += 1
result = 'function (' + result + ')
Thanks,
Dan
| [
"', '.join(args) will do the trick.\n",
"'function(%s)' % ', '.join(args)\n\nproduces\n'function(a, b, c, d)'\n\n",
"result = 'function (%s)' % ', '.join(map(str,args))\n\nI recommend the map(str, args) instead of just args because some of your arguments could potentially not be strings and would cause a TypeError, for example, with an int argument in your list:\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: sequence item 0: expected string, int found\n\nWhen you get into dict objects you will probably want to comma-separate the values of the dict (presumably because the values are what you want to pass into this function). If you do the join method on the dict object itself, you will get the keys separated, like so:\n>>> d = {'d':5, 'f':6.0, 'r':\"BOB\"}\n>>> ','.join(d)\n'r,d,f'\n\nWhat you want is the following:\n>>> d = {'d':5, 'f':6.0, 'r':\"BOB\"}\n>>> result = 'function (%s)' % ', '.join(map(str, d.values()))\n>>> result\n'function (BOB, 5, 6.0)'\n\nNote the new problem you encounter, however. When you pass a string argument through the join function, it loses its quoting. So if you planned to pass strings through, you have lost the quotes that usually would surround the string when passed into a function (strings are quoted in many general-purpose languages). If you're only passing numbers, however, this isn't a problem for you.\nThere is probably a nicer way of solving the problem I just described, but here's one method that could work for you.\n>>> l = list()\n>>> for val in d.values():\n... try:\n... v = float(val) #half-decent way of checking if something is an int, float, boolean\n... l.append(val) #if it was, then append the original type to the list\n... except:\n... #wasn't a number, assume it's a string and surround with quotes\n... l.append(\"\\\"\" + val + \"\\\"\")\n...\n>>> result = 'function (%s)' % ', '.join(map(str, l))\n>>> result\n'function (\"BOB\", 5, 6.0)'\n\nNow the string has quotes surrounding itself. If you are passing more complex types than numeric primitives and strings then you probably need a new question :)\nOne last note: I have been using d.values() to show how to extract the values from a dictionary, but in fact that will return the values from the dictionary in pretty much arbitrary order. Since your function most likely requires the arguments in a particular order, you should manually construct your list of values instead of calling d.values().\n",
"Why not use a standard that both languages can parse, like JSON, XML, or YAML? simplejson is handy, and included as json in python 2.6.\n"
] | [
12,
11,
1,
0
] | [] | [] | [
"list",
"python",
"refactoring"
] | stackoverflow_0000349175_list_python_refactoring.txt |
Q:
destroying a Toplevel tk window in python
I was trying to write code that would auto-close a Toplevel Tk window in Python.
I ended up getting it to work, but ran into a little problem along the way that I wasn't able to figure out.
The second two buttons work, but the first one doesn't and I don't understand why...
Any ideas?
from Tkinter import *
root = Tk()
def doDestroy ():
TL.destroy()
TL = Toplevel()
TL.b = Button (TL, text="lambda destroy", command=lambda: TL.destroy)
TL.b.pack()
TL.b2 = Button (TL, text="callback destroy", command=doDestroy)
TL.b2.pack()
de = lambda: TL.destroy()
TL.b3 = Button (TL, text="lambda that works", command=de)
TL.b3.pack()
root.mainloop()
A:
Because it returns a function and not its result.
You should put:
command=TL.destroy
or if you used lambda:
command=lambda: TL.destroy()
| destroying a Toplevel tk window in python | I was trying to write code that would auto-close a Toplevel Tk window in Python.
I ended up getting it to work, but ran into a little problem along the way that I wasn't able to figure out.
The second two buttons work, but the first one doesn't and I don't understand why...
Any ideas?
from Tkinter import *
root = Tk()
def doDestroy ():
TL.destroy()
TL = Toplevel()
TL.b = Button (TL, text="lambda destroy", command=lambda: TL.destroy)
TL.b.pack()
TL.b2 = Button (TL, text="callback destroy", command=doDestroy)
TL.b2.pack()
de = lambda: TL.destroy()
TL.b3 = Button (TL, text="lambda that works", command=de)
TL.b3.pack()
root.mainloop()
| [
"Because it returns a function and not its result.\nYou should put:\ncommand=TL.destroy\n\nor if you used lambda:\ncommand=lambda: TL.destroy()\n\n"
] | [
8
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0000351821_python_tkinter.txt |
Q:
Return file from python module
Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV
A:
You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.
Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.
It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.
In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.
A:
Fully supported in CherryPy using
from cherrypy.lib.static import serve_file
As documented in the CherryPy docs - FileDownload:
import glob
import os.path
import cherrypy
from cherrypy.lib.static import serve_file
class Root:
def index(self, directory="."):
html = """<html><body><h2>Here are the files in the selected directory:</h2>
<a href="index?directory=%s">Up</a><br />
""" % os.path.dirname(os.path.abspath(directory))
for filename in glob.glob(directory + '/*'):
absPath = os.path.abspath(filename)
if os.path.isdir(absPath):
html += '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
else:
html += '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += """</body></html>"""
return html
index.exposed = True
class Download:
def index(self, filepath):
return serve_file(filepath, "application/x-download", "attachment")
index.exposed = True
if __name__ == '__main__':
root = Root()
root.download = Download()
cherrypy.quickstart(root)
A:
For information on MIME types (which are how downloads happen), start here: Properly Configure Server MIME Types.
For information on CherryPy, look at the attributes of a Response object. You can set the content type of the response. Also, you can use tools.response_headers to set the content type.
And, of course, there's an example of File Download.
| Return file from python module | Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV
| [
"You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.\nOr, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.\nIt is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.\nIn your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.\n",
"Fully supported in CherryPy using\nfrom cherrypy.lib.static import serve_file\n\nAs documented in the CherryPy docs - FileDownload:\nimport glob\nimport os.path\n\nimport cherrypy\nfrom cherrypy.lib.static import serve_file\n\n\nclass Root:\n def index(self, directory=\".\"):\n html = \"\"\"<html><body><h2>Here are the files in the selected directory:</h2>\n <a href=\"index?directory=%s\">Up</a><br />\n \"\"\" % os.path.dirname(os.path.abspath(directory))\n\n for filename in glob.glob(directory + '/*'):\n absPath = os.path.abspath(filename)\n if os.path.isdir(absPath):\n html += '<a href=\"/index?directory=' + absPath + '\">' + os.path.basename(filename) + \"</a> <br />\"\n else:\n html += '<a href=\"/download/?filepath=' + absPath + '\">' + os.path.basename(filename) + \"</a> <br />\"\n\n html += \"\"\"</body></html>\"\"\"\n return html\n index.exposed = True\n\nclass Download:\n def index(self, filepath):\n return serve_file(filepath, \"application/x-download\", \"attachment\")\n index.exposed = True\n\nif __name__ == '__main__':\n root = Root()\n root.download = Download()\n cherrypy.quickstart(root)\n\n",
"For information on MIME types (which are how downloads happen), start here: Properly Configure Server MIME Types.\nFor information on CherryPy, look at the attributes of a Response object. You can set the content type of the response. Also, you can use tools.response_headers to set the content type.\nAnd, of course, there's an example of File Download.\n"
] | [
2,
1,
0
] | [] | [] | [
"download",
"file",
"mime_types",
"python"
] | stackoverflow_0000352340_download_file_mime_types_python.txt |
Q:
Making Python default to another version installed on a shared host
I am on a shared host and can not change the symbolic link to Python2.4, it defaults to 2.3. I tried creating a sym link in the director I would be working on to 2.4, but it seems the the 'global' python interpreter under /usr/bin/python take presedence unless I run it as ./python. What alternative ways are there to override this behaviour?
A:
If you're working from the shell, you can create a symbolic link as suggested and update your path in the .profile. This is described in a previous post.
In case these are CGI/whatever scripts that you only run on your shared host, you can alter the shebang line at the top of your scripts that tell the system what interpreter to run the script with.
I.e. change
#!/usr/bin/env python
to
#!/whatever/the/path/to/your/version/python
A:
Create a symlink and prepend the path to your PATH variable:
ln -s /usr/bin/python2.4 $HOME/bin/python
export PATH="$HOME/bin:$PATH"
| Making Python default to another version installed on a shared host | I am on a shared host and can not change the symbolic link to Python2.4, it defaults to 2.3. I tried creating a sym link in the director I would be working on to 2.4, but it seems the the 'global' python interpreter under /usr/bin/python take presedence unless I run it as ./python. What alternative ways are there to override this behaviour?
| [
"If you're working from the shell, you can create a symbolic link as suggested and update your path in the .profile. This is described in a previous post.\nIn case these are CGI/whatever scripts that you only run on your shared host, you can alter the shebang line at the top of your scripts that tell the system what interpreter to run the script with.\nI.e. change\n#!/usr/bin/env python\n\nto\n#!/whatever/the/path/to/your/version/python\n\n",
"Create a symlink and prepend the path to your PATH variable:\nln -s /usr/bin/python2.4 $HOME/bin/python\nexport PATH=\"$HOME/bin:$PATH\"\n\n"
] | [
3,
2
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0000353148_linux_python.txt |
Q:
Python method arguments with spaces
I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing.
Syntax like this for defining a data element seems quite convenient.
Allocation(Param1 = Val1, Param2 = Val2 )
However, it does not support param names with spaces.
Allocation(Param 1 = Val1, Param 2 = Val2 )
Python parser friendly versions can look as follows, but not very user friendly.
Allocation(("Param 1",Val1), ("Param 2",Val1) )
Allocation(**{"Param 1":Val1, "Param 2":Val1} )
Is there a way to make this more readable in python?
A:
I'd imagine that there would be some way to do it. But I feel compelled to ask, is there really a big enough difference in readability from this
Allocation(Param1 = Val1, Param2 = Val2 )
To this:
Allocation(Param 1 = Val1, Param 2 = Val2 )
to make that big a difference? I'm sure there's a way to do what you want to do, but my first concern is if the effort involved would be worth the result.
my goal is to provide a DSL which can be used for data entry into the system. In the above scenario, params would be people names and values would be percentages.
I have a better understanding of what you want to do now, but I still think that you might end up having to sacrifice some readability to get what you want. Personally, I would go with something like:
Allocation(
{ 'name1' : value1,
'name1' : value2, }
)
If that's not something you can go with, then you might want to reconsider whether you want to use Python for your DSL or go with something home-grown. Allowing whitespace allows too many ambiguities for most programming languages to allow it.
If you still want to pursue this with using python, you might want to consider posting to the C-API SIG (SIGS) or maybe the python-dev list (as a last resort). The only way that I can see to do this would be to embed the python interpreter into a C/C++ program and do some kind of hacking with it (which can be difficult!).
A:
You can do this:
def Allocation(**kwargs):
print kwargs
myargs = {"Param 1":Val1, "Param 2":Val1}
Allocation(**myargs)
Edit:
Your edit now includes my answer so no, there is no easier way to have spaces in keyword arguments.
A:
Unless I am mistaking your basic premise here, there's nothing to stop you from writing a class that parses your own custom syntax, and then using that custom syntax as a single-argument string:
Allocation("Param 1=Check Up; Param 2=Mean Value Theorem;")
In this example, semicolons act as the name-value-pair separators, and equals represents the name-value separator. Moreover, you can easily configure your parser to accept custom delimiters as part of the object constructor.
If it seems too daunting to write a parser, consider that (for a syntax such as this) you could obtain your values by simply splitting the string on
/\s*;\s*/
and then on
/\s*=\s*/
to quickly obtain the name-value pairs. You also have the option to choose from any of several argument parsers already written for Python.
Admittedly, this does not use Python as the argument parser, which is a consideration you will have to balance against the simplicity of an approach such as this.
A:
Here's my preference.
AllocationSet(
Alloc( name="some name", value=1.23 ),
Alloc( name="another name", value=2.34 ),
Alloc( name="yet another name", value=4.56 ),
)
These are relatively easy class declarations to create. The resulting structure is pleasant to process, too.
| Python method arguments with spaces | I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing.
Syntax like this for defining a data element seems quite convenient.
Allocation(Param1 = Val1, Param2 = Val2 )
However, it does not support param names with spaces.
Allocation(Param 1 = Val1, Param 2 = Val2 )
Python parser friendly versions can look as follows, but not very user friendly.
Allocation(("Param 1",Val1), ("Param 2",Val1) )
Allocation(**{"Param 1":Val1, "Param 2":Val1} )
Is there a way to make this more readable in python?
| [
"I'd imagine that there would be some way to do it. But I feel compelled to ask, is there really a big enough difference in readability from this\nAllocation(Param1 = Val1, Param2 = Val2 )\n\nTo this:\nAllocation(Param 1 = Val1, Param 2 = Val2 )\n\nto make that big a difference? I'm sure there's a way to do what you want to do, but my first concern is if the effort involved would be worth the result.\n\nmy goal is to provide a DSL which can be used for data entry into the system. In the above scenario, params would be people names and values would be percentages.\n\nI have a better understanding of what you want to do now, but I still think that you might end up having to sacrifice some readability to get what you want. Personally, I would go with something like:\nAllocation(\n { 'name1' : value1,\n 'name1' : value2, }\n)\n\nIf that's not something you can go with, then you might want to reconsider whether you want to use Python for your DSL or go with something home-grown. Allowing whitespace allows too many ambiguities for most programming languages to allow it.\nIf you still want to pursue this with using python, you might want to consider posting to the C-API SIG (SIGS) or maybe the python-dev list (as a last resort). The only way that I can see to do this would be to embed the python interpreter into a C/C++ program and do some kind of hacking with it (which can be difficult!).\n",
"You can do this:\ndef Allocation(**kwargs):\n print kwargs\n\nmyargs = {\"Param 1\":Val1, \"Param 2\":Val1}\nAllocation(**myargs)\n\nEdit:\nYour edit now includes my answer so no, there is no easier way to have spaces in keyword arguments.\n",
"Unless I am mistaking your basic premise here, there's nothing to stop you from writing a class that parses your own custom syntax, and then using that custom syntax as a single-argument string:\nAllocation(\"Param 1=Check Up; Param 2=Mean Value Theorem;\")\n\nIn this example, semicolons act as the name-value-pair separators, and equals represents the name-value separator. Moreover, you can easily configure your parser to accept custom delimiters as part of the object constructor.\nIf it seems too daunting to write a parser, consider that (for a syntax such as this) you could obtain your values by simply splitting the string on \n/\\s*;\\s*/\n\nand then on\n/\\s*=\\s*/\n\nto quickly obtain the name-value pairs. You also have the option to choose from any of several argument parsers already written for Python.\nAdmittedly, this does not use Python as the argument parser, which is a consideration you will have to balance against the simplicity of an approach such as this.\n",
"Here's my preference.\nAllocationSet(\n Alloc( name=\"some name\", value=1.23 ),\n Alloc( name=\"another name\", value=2.34 ),\n Alloc( name=\"yet another name\", value=4.56 ),\n)\n\nThese are relatively easy class declarations to create. The resulting structure is pleasant to process, too.\n"
] | [
3,
1,
1,
1
] | [] | [] | [
"dsl",
"python"
] | stackoverflow_0000351760_dsl_python.txt |
Q:
Beginner: Trying to understand how apps interact in Django
I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.
For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.
Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:
mysite/blog/models.py
from django.db import models
class post(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
content = models.TextField()
mysite/comments/models.py
from django.db import models
from mysite.blog.models import post
class comment(models.Model):
id = models.AutoField()
post = models.ForeignKey(post)
author = models.CharField(max_length=200)
text = models.TextField()
Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?
Update
Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contentypes import generic
class comment(models.Model):
id = models.AutoField()
author = models.CharField(max_length=200)
text = models.TextField()
content_type = models.ForeignKey(ContentType)
content_object = generic.GenericForeignKey(content_type, id)
Would this be correct?
A:
Take a look at django's built-in contenttypes framework:
django.contrib.contenttypes
It allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in comment framework to attach a comment to any model in your project.
For instance, if you have some content object that you want to "attach" to other content objects of different types, like allowing each user to leave a "favorite" star on a blog post, image, or user profile, you can create a Favorite model with a generic relation field like so:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Favorite(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
In this way you can add a Favorite star from any user to any model in your project. If you want to add API access via the recipient model class you can either add a reverse generic relation field on the recipient model (although this would be "coupling" the two models, which you said you wanted to avoid), or do the lookup through the Favorite model with the content_type and object_id of the recipient instance, see the official docs for an example.
A:
"Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact?"
Yep. Works for me.
We have about 10 applications that borrow back and forth among themselves.
This leads to a kind of dependency in our unit test script.
It looks like this.
"ownership". We have a simple data ownership application that defines some core ownership concepts that other applications depend on. There are a few simple tables here.
"thing". [Not the real name]. Our thing application has data elements owned by different user groups. There are actually several complex tables the model for this app. It depends on "ownership".
"tables". [Not the real name]. Some of our users create fairly complex off-line models (probably with spreadsheets) and upload the results of that modeling in "tables". This has a cluster of fairly complex tables. It depends on "ownership".
"result". [Not the real name]. Our results are based on things which have owners. The results are based on things and tables, and are responses to customer requests. This isn't too complex, perhaps only two or three core tables. It depends on "things" and "table". No, it doesn't completely stand-alone. However, it is subject to more change than the other things on which it depends. That's why it's separate.
"processing". We schedule and monitor big batch jobs. This is in this application. It's really generic, and can be used in a variety of ways. It completely stands alone.
"welcome". We have a "welcome" app that presents a bunch of mostly static pages. This doesn't have too many tables. But it's on it's second incarnation because the first was too complex. It completely stands alone.
The only relationship among the dependent apps is some table names. As long as we preserve those tables (and their keys) we can rearrange other apps as we see fit.
A:
There's nothing wrong (imho) with making some app dependent on another. After all, apps are just operations on a set of models. you just have to always be aware of which app depends on which app (I guess you could call that a dependency map).
You can achieve loose coupling with the contenttypes framework. It allows an app to be truely portable/pluggable yet still integrated with other applications.
I wrote a comments app (yea, I re-invented the wheel), that can be integrated into any other application, with a few lines in the template of the page where comments should be posted (using custom tags).
Say you want a model "thread" to be pluggable into any other model. The idea is to create e generic foreign key (see django documentation on that), and write a small function that takes any object and returns a "thread" corresponding to it (or creates one if necessary), and write a custom template tag that uses that functionality, e.g. {% get_thread for arbitrary_object as thread %}. All posts are related to a thread, which is related to the object, which can be of any type.
You can think of the "thread" object as a kind of a proxy, so instead of having a post be related to a certain "article" or a "blog post", it's just related to a thread, which is abstract in a sense, what is is a thread? It's just a collection of posts. The thread then allows itself to be related to any object regardless of its type. (although it does more than that, it could hold extra information such as allowing/disallowing anon. posts, closing/opening comments on the page, etc ..)
EDIT
Here's how you can create a generic foreign key with the content types framework:
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Thread( models.Model ):
object_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('object_type', 'object_id')
You can make it more "transparent" by exploiting the implicit "common" interface that django assumes all objects implement ..
#inside the Thread class:
def __unicode__(self):
return unicode(self.object)
def get_absolute_url(self):
return self.object.get_absolute_url()
A:
Your code seems correct. I would keep the post and the comment in a blog app though. I am not saying this is the Django way, but those models are close enough to be in the same app.
How To Divide The Project
I would seperate an app if;
I plan to design it resuable. (and try loose coupling)
(for big projects) It consists of a major section of the project.
On the other hand; having many tiny apps (such as an app with a single model and two views) is hard to read and maintain IMHO.
How Apps Should Interact
This depends on the type of project and the type of the app again. For example if an app is implicitly dependent on another (ie not generic) importing and using references from the other app is acceptable. In this case the second app might be installed alone, but the first one needs the presence of the second.
If you want to make an app highly reusable and generic, such as a commenting app, you might need to integrate some setup mechanism. Maybe some new settings or additional URL configuration, or a special directive/method on your models... django.contrib.admin is a good example for this.
Apps shouldn't interact if it is not necessary though. Designing apps to avoid unnecessary coupling is very useful. It improves your app's flexibility and makes it more maintainable (but possibly with a higher cost in integrating).
| Beginner: Trying to understand how apps interact in Django | I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.
For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.
Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:
mysite/blog/models.py
from django.db import models
class post(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
content = models.TextField()
mysite/comments/models.py
from django.db import models
from mysite.blog.models import post
class comment(models.Model):
id = models.AutoField()
post = models.ForeignKey(post)
author = models.CharField(max_length=200)
text = models.TextField()
Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?
Update
Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contentypes import generic
class comment(models.Model):
id = models.AutoField()
author = models.CharField(max_length=200)
text = models.TextField()
content_type = models.ForeignKey(ContentType)
content_object = generic.GenericForeignKey(content_type, id)
Would this be correct?
| [
"Take a look at django's built-in contenttypes framework:\ndjango.contrib.contenttypes\nIt allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in comment framework to attach a comment to any model in your project.\nFor instance, if you have some content object that you want to \"attach\" to other content objects of different types, like allowing each user to leave a \"favorite\" star on a blog post, image, or user profile, you can create a Favorite model with a generic relation field like so:\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Favorite(models.Model):\n user = models.ForeignKey(User)\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n\nIn this way you can add a Favorite star from any user to any model in your project. If you want to add API access via the recipient model class you can either add a reverse generic relation field on the recipient model (although this would be \"coupling\" the two models, which you said you wanted to avoid), or do the lookup through the Favorite model with the content_type and object_id of the recipient instance, see the official docs for an example. \n",
"\"Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact?\"\nYep. Works for me.\nWe have about 10 applications that borrow back and forth among themselves.\nThis leads to a kind of dependency in our unit test script.\nIt looks like this.\n\n\"ownership\". We have a simple data ownership application that defines some core ownership concepts that other applications depend on. There are a few simple tables here.\n\"thing\". [Not the real name]. Our thing application has data elements owned by different user groups. There are actually several complex tables the model for this app. It depends on \"ownership\".\n\"tables\". [Not the real name]. Some of our users create fairly complex off-line models (probably with spreadsheets) and upload the results of that modeling in \"tables\". This has a cluster of fairly complex tables. It depends on \"ownership\".\n\"result\". [Not the real name]. Our results are based on things which have owners. The results are based on things and tables, and are responses to customer requests. This isn't too complex, perhaps only two or three core tables. It depends on \"things\" and \"table\". No, it doesn't completely stand-alone. However, it is subject to more change than the other things on which it depends. That's why it's separate.\n\"processing\". We schedule and monitor big batch jobs. This is in this application. It's really generic, and can be used in a variety of ways. It completely stands alone.\n\"welcome\". We have a \"welcome\" app that presents a bunch of mostly static pages. This doesn't have too many tables. But it's on it's second incarnation because the first was too complex. It completely stands alone.\n\nThe only relationship among the dependent apps is some table names. As long as we preserve those tables (and their keys) we can rearrange other apps as we see fit.\n",
"There's nothing wrong (imho) with making some app dependent on another. After all, apps are just operations on a set of models. you just have to always be aware of which app depends on which app (I guess you could call that a dependency map).\nYou can achieve loose coupling with the contenttypes framework. It allows an app to be truely portable/pluggable yet still integrated with other applications.\nI wrote a comments app (yea, I re-invented the wheel), that can be integrated into any other application, with a few lines in the template of the page where comments should be posted (using custom tags).\nSay you want a model \"thread\" to be pluggable into any other model. The idea is to create e generic foreign key (see django documentation on that), and write a small function that takes any object and returns a \"thread\" corresponding to it (or creates one if necessary), and write a custom template tag that uses that functionality, e.g. {% get_thread for arbitrary_object as thread %}. All posts are related to a thread, which is related to the object, which can be of any type.\nYou can think of the \"thread\" object as a kind of a proxy, so instead of having a post be related to a certain \"article\" or a \"blog post\", it's just related to a thread, which is abstract in a sense, what is is a thread? It's just a collection of posts. The thread then allows itself to be related to any object regardless of its type. (although it does more than that, it could hold extra information such as allowing/disallowing anon. posts, closing/opening comments on the page, etc ..)\nEDIT\nHere's how you can create a generic foreign key with the content types framework:\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\n\nclass Thread( models.Model ):\n object_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n object = generic.GenericForeignKey('object_type', 'object_id')\n\nYou can make it more \"transparent\" by exploiting the implicit \"common\" interface that django assumes all objects implement ..\n #inside the Thread class:\n def __unicode__(self):\n return unicode(self.object)\n def get_absolute_url(self):\n return self.object.get_absolute_url()\n\n",
"Your code seems correct. I would keep the post and the comment in a blog app though. I am not saying this is the Django way, but those models are close enough to be in the same app.\nHow To Divide The Project\nI would seperate an app if;\n\nI plan to design it resuable. (and try loose coupling)\n(for big projects) It consists of a major section of the project.\n\nOn the other hand; having many tiny apps (such as an app with a single model and two views) is hard to read and maintain IMHO.\nHow Apps Should Interact\nThis depends on the type of project and the type of the app again. For example if an app is implicitly dependent on another (ie not generic) importing and using references from the other app is acceptable. In this case the second app might be installed alone, but the first one needs the presence of the second.\nIf you want to make an app highly reusable and generic, such as a commenting app, you might need to integrate some setup mechanism. Maybe some new settings or additional URL configuration, or a special directive/method on your models... django.contrib.admin is a good example for this.\nApps shouldn't interact if it is not necessary though. Designing apps to avoid unnecessary coupling is very useful. It improves your app's flexibility and makes it more maintainable (but possibly with a higher cost in integrating).\n"
] | [
22,
4,
3,
2
] | [] | [] | [
"django",
"django_apps",
"django_models",
"python"
] | stackoverflow_0000353571_django_django_apps_django_models_python.txt |
Q:
Cleaner way to query on a dynamic number of columns in Django?
In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:
for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
Now it works but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.
Is there a way I can condense this into one filter query?
A:
Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method.
op_kwargs = {}
for op in self.cleaned_data['options']:
op_kwargs[op] = True
cars = CarModel.objects.filter(**op_kwargs)
This is covered in the django documentation and has been covered on SO as well.
A:
Django's query sets are lazy, so what you're currently doing is actually pretty efficient. The database won't be hit until you try to access one of the fields in the QuerySet... assuming, that is, that you didn't edit out some code, and it is effectively like this:
cars = CarModel.objects.all()
for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
More information here.
| Cleaner way to query on a dynamic number of columns in Django? | In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:
for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
Now it works but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.
Is there a way I can condense this into one filter query?
| [
"Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method.\nop_kwargs = {}\nfor op in self.cleaned_data['options']:\n op_kwargs[op] = True\ncars = CarModel.objects.filter(**op_kwargs)\n\nThis is covered in the django documentation and has been covered on SO as well.\n",
"Django's query sets are lazy, so what you're currently doing is actually pretty efficient. The database won't be hit until you try to access one of the fields in the QuerySet... assuming, that is, that you didn't edit out some code, and it is effectively like this:\ncars = CarModel.objects.all()\nfor op in self.cleaned_data['options']:\n cars = cars.filter((op, True))\n\nMore information here.\n"
] | [
9,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000353489_django_python.txt |
Q:
How to blend drawn circles with pygame
I am trying to create an application like the one here:
http://www.eigenfaces.com/
Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:
import sys, random, time
import pygame
from pygame.locals import *
from pygame import draw
rand = random.randint
pygame.init( )
W = 320
H = 320
size = (W, H)
screen = pygame.display.set_mode(size)
run = True
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE :
run = not run
else:
sys.exit()
if run:
xc = rand(1, W)
yc = rand(1, H)
rc = rand(1, 25)
red = rand(1, 255)
grn = rand(1, 255)
blu = rand(1, 255)
draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0)
pygame.display.flip()
A:
I got it to work by drawing to a surface that is not the display and combining the set colorkey and set alpha functions.
import pygame
from pygame.locals import *
TRANSPARENT = (255,0,255)
pygame.init()
screen = pygame.display.set_mode((500,500))
surf1 = pygame.Surface((200,200))
surf1.fill(TRANSPARENT)
surf1.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf1, (0,0,200,100),(100,100), 100)
surf2 = pygame.Surface((200,200))
surf2.fill(TRANSPARENT)
surf2.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf2, (200,0,0,100),(100,100), 100)
surf1.set_alpha(100)
surf2.set_alpha(100)
while True:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
screen.blit(surf1, (100,100,100,100))
screen.blit(surf2, (200,200,100,100))
pygame.display.flip()
P.S
There's also the blend flags that you can put in the blit() arguments:
Pygame.org - Surface.blit
A:
I am Dave. Creator of the images at eigenfaces.com. Good luck with your experiments. I posted the code here:
http://www.eigenfaces.com/
Let me know if it's of use.
By the way.. I have also experimented with movies... Here is about 20 frames with about 1000 generations each:
http://www.eigenfaces.com/img/morphs/anim-100x20.gif
| How to blend drawn circles with pygame | I am trying to create an application like the one here:
http://www.eigenfaces.com/
Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:
import sys, random, time
import pygame
from pygame.locals import *
from pygame import draw
rand = random.randint
pygame.init( )
W = 320
H = 320
size = (W, H)
screen = pygame.display.set_mode(size)
run = True
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE :
run = not run
else:
sys.exit()
if run:
xc = rand(1, W)
yc = rand(1, H)
rc = rand(1, 25)
red = rand(1, 255)
grn = rand(1, 255)
blu = rand(1, 255)
draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0)
pygame.display.flip()
| [
"I got it to work by drawing to a surface that is not the display and combining the set colorkey and set alpha functions.\nimport pygame\nfrom pygame.locals import *\n\nTRANSPARENT = (255,0,255)\npygame.init()\nscreen = pygame.display.set_mode((500,500))\n\nsurf1 = pygame.Surface((200,200))\nsurf1.fill(TRANSPARENT)\nsurf1.set_colorkey(TRANSPARENT)\npygame.draw.circle(surf1, (0,0,200,100),(100,100), 100)\n\nsurf2 = pygame.Surface((200,200))\nsurf2.fill(TRANSPARENT)\nsurf2.set_colorkey(TRANSPARENT)\npygame.draw.circle(surf2, (200,0,0,100),(100,100), 100)\n\nsurf1.set_alpha(100)\nsurf2.set_alpha(100)\n\nwhile True:\n screen.fill((255,255,255))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n\n screen.blit(surf1, (100,100,100,100))\n screen.blit(surf2, (200,200,100,100))\n pygame.display.flip()\n\nP.S\nThere's also the blend flags that you can put in the blit() arguments:\nPygame.org - Surface.blit\n",
"I am Dave. Creator of the images at eigenfaces.com. Good luck with your experiments. I posted the code here:\nhttp://www.eigenfaces.com/\nLet me know if it's of use.\nBy the way.. I have also experimented with movies... Here is about 20 frames with about 1000 generations each:\nhttp://www.eigenfaces.com/img/morphs/anim-100x20.gif\n"
] | [
6,
3
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0000353297_pygame_python.txt |
Q:
How is ** implemented in Python?
I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction?
A:
The python grammar definition (from which the parser is generated using pgen), look for 'power': Gramar/Gramar
The python ast, look for 'ast_for_power': Python/ast.c
The python eval loop, look for 'BINARY_POWER': Python/ceval.c
Which calls PyNumber_Power (implemented in Objects/abstract.c):
PyObject *
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
{
return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
}
Essentially, invoke the pow slot. For long objects (the only default integer type in 3.0) this is implemented in the long_pow function Objects/longobject.c, for int objects (in the 2.x branches) it is implemented in the int_pow function Object/intobject.c
If you dig into long_pow, you can see that after vetting the arguments and doing a bit of set up, the heart of the exponentiation can be see here:
if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
/* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
/* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
for (i = Py_SIZE(b) - 1; i >= 0; --i) {
digit bi = b->ob_digit[i];
for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
MULT(z, z, z)
if (bi & j)
MULT(z, a, z)
}
}
}
else {
/* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
Py_INCREF(z); /* still holds 1L */
table[0] = z;
for (i = 1; i < 32; ++i)
MULT(table[i-1], a, table[i])
for (i = Py_SIZE(b) - 1; i >= 0; --i) {
const digit bi = b->ob_digit[i];
for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
const int index = (bi >> j) & 0x1f;
for (k = 0; k < 5; ++k)
MULT(z, z, z)
if (index)
MULT(z, table[index], z)
}
}
}
Which uses algorithms discussed in Chapter 14.6 of the Handbook of Applied Cryptography which describes efficient exponentiation algorithms for arbitrary precision arithmetic.
A:
There are two different implementations one for int (long in 3.0) objects and another one for float objects.
The float pow is the float_pow(PyObject *v, PyObject *w, PyObject *z) function defined in Objects/floatobject.c file of the Python source code. This functions calls pow() from C stdlib's math.h
The int pow has its own implementation, is the function int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z) defined in Objects/intobject.c (longobject.c for 3.0) of the Python source code.
A:
I think caseysrandomthoughts are asking about asterisks at functions definition.
You could find answer at this Python doc page: http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions
When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter.
I've sow description of this stuff somewhere else at python doc but I can't to remember.
A:
It's the power to operator
python.org doc - Power operator
Edit: Oh, dang, the code, right. Hope the link still helps. Sloppy read from my part
| How is ** implemented in Python? | I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction?
| [
"The python grammar definition (from which the parser is generated using pgen), look for 'power': Gramar/Gramar\nThe python ast, look for 'ast_for_power': Python/ast.c\nThe python eval loop, look for 'BINARY_POWER': Python/ceval.c\nWhich calls PyNumber_Power (implemented in Objects/abstract.c):\nPyObject *\nPyNumber_Power(PyObject *v, PyObject *w, PyObject *z)\n{\n return ternary_op(v, w, z, NB_SLOT(nb_power), \"** or pow()\");\n}\n\nEssentially, invoke the pow slot. For long objects (the only default integer type in 3.0) this is implemented in the long_pow function Objects/longobject.c, for int objects (in the 2.x branches) it is implemented in the int_pow function Object/intobject.c\nIf you dig into long_pow, you can see that after vetting the arguments and doing a bit of set up, the heart of the exponentiation can be see here:\nif (Py_SIZE(b) <= FIVEARY_CUTOFF) {\n /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */\n /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */\n for (i = Py_SIZE(b) - 1; i >= 0; --i) {\n digit bi = b->ob_digit[i];\n\n for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {\n MULT(z, z, z)\n if (bi & j)\n MULT(z, a, z)\n }\n }\n}\nelse {\n /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */\n Py_INCREF(z); /* still holds 1L */\n table[0] = z;\n for (i = 1; i < 32; ++i)\n MULT(table[i-1], a, table[i])\n\n for (i = Py_SIZE(b) - 1; i >= 0; --i) {\n const digit bi = b->ob_digit[i];\n\n for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {\n const int index = (bi >> j) & 0x1f;\n for (k = 0; k < 5; ++k)\n MULT(z, z, z)\n if (index)\n MULT(z, table[index], z)\n }\n }\n}\n\nWhich uses algorithms discussed in Chapter 14.6 of the Handbook of Applied Cryptography which describes efficient exponentiation algorithms for arbitrary precision arithmetic.\n",
"There are two different implementations one for int (long in 3.0) objects and another one for float objects. \nThe float pow is the float_pow(PyObject *v, PyObject *w, PyObject *z) function defined in Objects/floatobject.c file of the Python source code. This functions calls pow() from C stdlib's math.h\nThe int pow has its own implementation, is the function int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z) defined in Objects/intobject.c (longobject.c for 3.0) of the Python source code.\n",
"I think caseysrandomthoughts are asking about asterisks at functions definition.\nYou could find answer at this Python doc page: http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions\nWhen a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter.\nI've sow description of this stuff somewhere else at python doc but I can't to remember.\n",
"It's the power to operator\npython.org doc - Power operator\nEdit: Oh, dang, the code, right. Hope the link still helps. Sloppy read from my part\n"
] | [
26,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000354421_python.txt |
Q:
How can I get the number of records that reference a particular foreign key in Django?
I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.
Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?
A:
Comments.objects.filter(post=post).count()
or:
post.comment_set.count()
A:
You can add field CommentCount to you Post model, and update it in pre_save, pre_delete signals.
It's a hard for the db to calculate comments count at every view call and number of queries will be grow.
| How can I get the number of records that reference a particular foreign key in Django? | I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.
Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?
| [
"Comments.objects.filter(post=post).count()\n\nor:\npost.comment_set.count()\n\n",
"You can add field CommentCount to you Post model, and update it in pre_save, pre_delete signals.\nIt's a hard for the db to calculate comments count at every view call and number of queries will be grow.\n"
] | [
6,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000354755_django_django_models_python.txt |
Q:
Save a deque in a text file
I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?
A:
As an alternative, you could set up an exit function, and pickle the deque on exit.
Exit function
Pickle
A:
You should be able to use pickle to serialize your lists.
A:
I am not sure if I understood the question right, I am just curious, so here are few questions and suggestions:
Are you planning to catch the Ctrl+C interrupt and do the deque?
What happens if the crawler crashes for some arbitrary reason like an unhandled exception or crash? You loose the queue status and start over again?
from the documentation:
Note
The exit function is not called when
the program is killed by a signal,
when a Python fatal internal error is
detected, or when os._exit() is
called.
What happens when you happen to visit the same URI again, are you maintaining a visited list or something?
I think you should be maintaining some kind of visit and session information / status for each URI you crawl.
You can use the visit information to decide to crawl a URI or not when you visit the same URI next time.
The other info - session information - for the last session with that URI will help in picking up only the incremental stuff and if the page is not change no need to pick it up saving some db I/O costs, duplicates, etc.
That way you won't have to worry about the ctrl+C or a crash. If the crawler goes down for any reason, lets say after crawling 60K posts when 40K more were left, the next time crawler fills in the queue, though the queue may be huge but the crawler can check if the it has already visited the URI or not and what was the state of the page when it was crawled - optimization - does the page requires a new pick up coz it has changed or not.
I hope that is of some help.
A:
Some things that come to my mind:
leave the file handle open (don't close the file everytime you wrote something)
or write the file every n items and catch a close signal to write the current non-written items
| Save a deque in a text file | I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?
| [
"As an alternative, you could set up an exit function, and pickle the deque on exit.\nExit function\nPickle\n",
"You should be able to use pickle to serialize your lists.\n",
"I am not sure if I understood the question right, I am just curious, so here are few questions and suggestions:\nAre you planning to catch the Ctrl+C interrupt and do the deque?\nWhat happens if the crawler crashes for some arbitrary reason like an unhandled exception or crash? You loose the queue status and start over again? \nfrom the documentation:\n\nNote\nThe exit function is not called when\n the program is killed by a signal,\n when a Python fatal internal error is\n detected, or when os._exit() is\n called.\n\nWhat happens when you happen to visit the same URI again, are you maintaining a visited list or something?\nI think you should be maintaining some kind of visit and session information / status for each URI you crawl.\nYou can use the visit information to decide to crawl a URI or not when you visit the same URI next time. \nThe other info - session information - for the last session with that URI will help in picking up only the incremental stuff and if the page is not change no need to pick it up saving some db I/O costs, duplicates, etc.\nThat way you won't have to worry about the ctrl+C or a crash. If the crawler goes down for any reason, lets say after crawling 60K posts when 40K more were left, the next time crawler fills in the queue, though the queue may be huge but the crawler can check if the it has already visited the URI or not and what was the state of the page when it was crawled - optimization - does the page requires a new pick up coz it has changed or not.\nI hope that is of some help. \n",
"Some things that come to my mind:\n\nleave the file handle open (don't close the file everytime you wrote something)\nor write the file every n items and catch a close signal to write the current non-written items\n\n"
] | [
4,
2,
1,
0
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0000355739_python_web_crawler.txt |
Q:
A get() like method for checking for Python attributes
If I had a dictionary dict and I wanted to check for dict['key'] I could either do so in a try block (bleh!) or use the get() method, with False as a default value.
I'd like to do the same thing for object.attribute. That is, I already have object to return False if it hasn't been set, but then that gives me errors like
AttributeError: 'bool' object has no attribute 'attribute'
A:
A more direct analogue to dict.get(key, default) than hasattr is getattr.
val = getattr(obj, 'attr_to_check', default_value)
(Where default_value is optional, raising an exception on no attribute if not found.)
For your example, you would pass False.
A:
Do you mean hasattr() perhaps?
hasattr(object, "attribute name") #Returns True or False
Python.org doc - Built in functions - hasattr()
You can also do this, which is a bit more cluttered and doesn't work for methods.
"attribute" in obj.__dict__
A:
For checking if a key is in a dictionary you can use in: 'key' in dictionary.
For checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')
| A get() like method for checking for Python attributes | If I had a dictionary dict and I wanted to check for dict['key'] I could either do so in a try block (bleh!) or use the get() method, with False as a default value.
I'd like to do the same thing for object.attribute. That is, I already have object to return False if it hasn't been set, but then that gives me errors like
AttributeError: 'bool' object has no attribute 'attribute'
| [
"A more direct analogue to dict.get(key, default) than hasattr is getattr.\nval = getattr(obj, 'attr_to_check', default_value)\n\n(Where default_value is optional, raising an exception on no attribute if not found.)\nFor your example, you would pass False.\n",
"Do you mean hasattr() perhaps?\nhasattr(object, \"attribute name\") #Returns True or False\n\nPython.org doc - Built in functions - hasattr()\nYou can also do this, which is a bit more cluttered and doesn't work for methods.\n\"attribute\" in obj.__dict__\n\n",
"For checking if a key is in a dictionary you can use in: 'key' in dictionary.\nFor checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')\n"
] | [
140,
21,
7
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0000355539_attributes_python.txt |
Q:
Python regex findall numbers and dots
I'm using re.findall() to extract some version numbers from an HTML file:
>>> import re
>>> text = "<table><td><a href=\"url\">Test0.2.1.zip</a></td><td>Test0.2.1</td></table> Test0.2.1"
>>> re.findall("Test([\.0-9]*)", text)
['0.2.1.', '0.2.1', '0.2.1']
but I would like to only get the ones that do not end in a dot.
The filename might not always be .zip so I can't just stick .zip in the regex.
I wanna end up with:
['0.2.1', '0.2.1']
Can anyone suggest a better regex to use? :)
A:
re.findall(r"Test([0-9.]*[0-9]+)", text)
or, a bit shorter:
re.findall(r"Test([\d.]*\d+)", text)
By the way - you do not need to escape the dot in a character class. Inside [] the . has no special meaning, it just matches a literal dot. Escaping it has no effect.
| Python regex findall numbers and dots | I'm using re.findall() to extract some version numbers from an HTML file:
>>> import re
>>> text = "<table><td><a href=\"url\">Test0.2.1.zip</a></td><td>Test0.2.1</td></table> Test0.2.1"
>>> re.findall("Test([\.0-9]*)", text)
['0.2.1.', '0.2.1', '0.2.1']
but I would like to only get the ones that do not end in a dot.
The filename might not always be .zip so I can't just stick .zip in the regex.
I wanna end up with:
['0.2.1', '0.2.1']
Can anyone suggest a better regex to use? :)
| [
"re.findall(r\"Test([0-9.]*[0-9]+)\", text)\n\nor, a bit shorter:\nre.findall(r\"Test([\\d.]*\\d+)\", text)\n\nBy the way - you do not need to escape the dot in a character class. Inside [] the . has no special meaning, it just matches a literal dot. Escaping it has no effect.\n"
] | [
23
] | [] | [] | [
"findall",
"python",
"regex"
] | stackoverflow_0000356483_findall_python_regex.txt |
Q:
How would you parse indentation (python style)?
How would you define your parser and lexer rules to parse a language that uses indentation for defining scope.
I have already googled and found a clever approach for parsing it by generating INDENT and DEDENT tokens in the lexer.
I will go deeper on this problem and post an answer if I come to something interesting, but I would like to see other approaches to the problem.
EDIT:
As Charlie pointed out, there is already another thread very similar if not the same. Should my post be deleted?
A:
This is kind of hypothetical, as it would depend on what technology you have for your lexer and parser, but the easiest way would seem to be to have BEGINBLOCK and ENDBLOCK tokens analogous to braces in C. Using the "offsides rule" your lexer needs to keep track of a stack of indendtation levels. When the indent level increases, emit a BEGINBLOCK for the parser; when the indentation level decreases, emit ENDBLOCK and pop levels off the stack.
Here's another discussion of this on SO, btw.
A:
Also you can track somewhere in lexer how many ident items are preceding first line and pass it to parser. Most interesting part would be trying to pass it to parser correctly :) If your parser uses lookahead (here I mean parser may query for variable number of tokens before it really going to match even one) then trying to pass it through one global variable seems to be very bad idea (because lexer can slip on next line and change value of indent counter while parser is still trying to parse previous line). Also globals are evil in many other cases ;) Marking first line 'real' token in someway with indent counter is more reasonable. I can't give you exact example (I don't even know what parser and lexer generators are you going to use if any...) but something like storing data on first line tokens (it could be non comfortable if you can't easily get such token from parser) or saving custom data (map that links tokens to indent, array where every line in source code as index and indent value as element value) seems to be enough. One downside of this approach is additional complexity to parser that will need to distinguish between ident values and change its behavior based on it. Something like LOOKAHEAD({ yourConditionInJava }) for JavaCC may work here but it is NOT a very good idea. A lot of additional tokens in your approach seems to be less evil thing to use :)
As another alternative I would suggest is to mix this two approaches. You could generate additional tokens only when indent counter changes its value on next line. It is like artificial BEGIN and END token. In this way you may lower number of 'artificial' tokens in your stream fed into parser from lexer. Only your parser grammar should be adjusted to understand additional tokens...
I didn't tried this (have no real experience with such languages parsing), just sharing my thoughts about possible solutions. Checking already built parsers for this kinds of languages could be of great value for you. Open source is your friend ;)
| How would you parse indentation (python style)? | How would you define your parser and lexer rules to parse a language that uses indentation for defining scope.
I have already googled and found a clever approach for parsing it by generating INDENT and DEDENT tokens in the lexer.
I will go deeper on this problem and post an answer if I come to something interesting, but I would like to see other approaches to the problem.
EDIT:
As Charlie pointed out, there is already another thread very similar if not the same. Should my post be deleted?
| [
"This is kind of hypothetical, as it would depend on what technology you have for your lexer and parser, but the easiest way would seem to be to have BEGINBLOCK and ENDBLOCK tokens analogous to braces in C. Using the \"offsides rule\" your lexer needs to keep track of a stack of indendtation levels. When the indent level increases, emit a BEGINBLOCK for the parser; when the indentation level decreases, emit ENDBLOCK and pop levels off the stack.\nHere's another discussion of this on SO, btw.\n",
"Also you can track somewhere in lexer how many ident items are preceding first line and pass it to parser. Most interesting part would be trying to pass it to parser correctly :) If your parser uses lookahead (here I mean parser may query for variable number of tokens before it really going to match even one) then trying to pass it through one global variable seems to be very bad idea (because lexer can slip on next line and change value of indent counter while parser is still trying to parse previous line). Also globals are evil in many other cases ;) Marking first line 'real' token in someway with indent counter is more reasonable. I can't give you exact example (I don't even know what parser and lexer generators are you going to use if any...) but something like storing data on first line tokens (it could be non comfortable if you can't easily get such token from parser) or saving custom data (map that links tokens to indent, array where every line in source code as index and indent value as element value) seems to be enough. One downside of this approach is additional complexity to parser that will need to distinguish between ident values and change its behavior based on it. Something like LOOKAHEAD({ yourConditionInJava }) for JavaCC may work here but it is NOT a very good idea. A lot of additional tokens in your approach seems to be less evil thing to use :)\nAs another alternative I would suggest is to mix this two approaches. You could generate additional tokens only when indent counter changes its value on next line. It is like artificial BEGIN and END token. In this way you may lower number of 'artificial' tokens in your stream fed into parser from lexer. Only your parser grammar should be adjusted to understand additional tokens...\nI didn't tried this (have no real experience with such languages parsing), just sharing my thoughts about possible solutions. Checking already built parsers for this kinds of languages could be of great value for you. Open source is your friend ;)\n"
] | [
12,
1
] | [] | [] | [
"indentation",
"lexer",
"parsing",
"python"
] | stackoverflow_0000356638_indentation_lexer_parsing_python.txt |
Q:
Problem with Python implementation of Conway's Game of Life
I am working on Conway's Game of Life currently and have gotten stuck. My code doesn't work.
When I run my code in GUI, it says:
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
Here is my code:
'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about import "neighbours" to function "apply_rules", is that right way to do this?
A:
Well, I guess that you are also quite new to programming per se, otherwise you should not have any problems in interpreting that simple error message.
I'll help you dissect it:
First, all "current" line numbers of your project's files are displayed, in calling order.
Then, it shows you the function in which the error occured: number_neighbours
Then, it shows you the contents of the line that contains the error: neighbours+=1
Finally, it tells you what the problem with that line is: UnboundLocalError: local variable 'neighbours' referenced before assignment
Now, what does that mean? Let's see what the += operator does: it adds something to the current value of neighbours. That means that it reads the current value, adds something to it, and finally stores it back. "Reading" is called "reference" with respect to variables.
What is the current value of neighbours? Well, it has never been used before, so it doesn't have any value -- there has never been a value assigned to it. Adding something to 'no value' is not a sensible thing to do. I guess that you expect it to have the value 0, but you have to tell it to your interpreter. To do this, add the following statement before, at the start of your function: neighbours = 0
A:
You're trying to increment a variable that doesn't exist yet. Python can't increment something if it doesn't know what is. Try adding the following line at the top of your def number_neighbours function.
neighbours = 0
A:
A cursory glance shows that your number_neighbors indices are off.
Also, you never initialize neighbors.
Response to Comment:
def number_neighbours(universe_array,iy,ix):
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
You say, neighbors +=1, which means add 1 to neighbors, but you never told it to start at 0, so it doesn't know what do add 1 to.
Also, notice the first and 3rd lines are exactly the same. I'm pretty sure this is not what you intended. That's what I meant by "your indices are off".
Response to Comment 2:
apply_rules has several lines where you want to assign a value to something (which is '='), but you use '==' instead.
A:
This is an extremely low-grade lazy question, but your number_neighbours function is broken, it checks universe_array[iy,ix-1] twice (and hence omits a check it should be doing).
| Problem with Python implementation of Conway's Game of Life | I am working on Conway's Game of Life currently and have gotten stuck. My code doesn't work.
When I run my code in GUI, it says:
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
Here is my code:
'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about import "neighbours" to function "apply_rules", is that right way to do this?
| [
"Well, I guess that you are also quite new to programming per se, otherwise you should not have any problems in interpreting that simple error message.\nI'll help you dissect it:\n\nFirst, all \"current\" line numbers of your project's files are displayed, in calling order.\nThen, it shows you the function in which the error occured: number_neighbours\nThen, it shows you the contents of the line that contains the error: neighbours+=1\nFinally, it tells you what the problem with that line is: UnboundLocalError: local variable 'neighbours' referenced before assignment\n\nNow, what does that mean? Let's see what the += operator does: it adds something to the current value of neighbours. That means that it reads the current value, adds something to it, and finally stores it back. \"Reading\" is called \"reference\" with respect to variables.\nWhat is the current value of neighbours? Well, it has never been used before, so it doesn't have any value -- there has never been a value assigned to it. Adding something to 'no value' is not a sensible thing to do. I guess that you expect it to have the value 0, but you have to tell it to your interpreter. To do this, add the following statement before, at the start of your function: neighbours = 0\n",
"You're trying to increment a variable that doesn't exist yet. Python can't increment something if it doesn't know what is. Try adding the following line at the top of your def number_neighbours function.\nneighbours = 0\n\n",
"A cursory glance shows that your number_neighbors indices are off.\nAlso, you never initialize neighbors.\nResponse to Comment:\ndef number_neighbours(universe_array,iy,ix):\n if universe_array[iy,ix-1]==1:\n neighbours+=1\n if universe_array[iy,ix-1]==1:\n neighbours+=1\n if universe_array[iy+1,ix-1]==1:\n neighbours+=1\n\nYou say, neighbors +=1, which means add 1 to neighbors, but you never told it to start at 0, so it doesn't know what do add 1 to. \nAlso, notice the first and 3rd lines are exactly the same. I'm pretty sure this is not what you intended. That's what I meant by \"your indices are off\".\n Response to Comment 2: \napply_rules has several lines where you want to assign a value to something (which is '='), but you use '==' instead.\n",
"This is an extremely low-grade lazy question, but your number_neighbours function is broken, it checks universe_array[iy,ix-1] twice (and hence omits a check it should be doing).\n"
] | [
13,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0000357968_python.txt |
Q:
A small question about python's variable scope
I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
A:
The scope of functions hello and hi are entirely different. They do not have any variables in common.
Note that the result of calling hi(x,y) is some object. You save that object with the name good in the function hello.
The variable named good in hello is a different variable, unrelated to the variable named good in the function hi.
They're spelled the same, but the exist in different namespaces. To prove this, change the spelling the good variable in one of the two functions, you'll see that things still work.
Edit. Follow-up: "so what should i do if i want use the result of hi function in hello function?"
Nothing unusual. Look at hello closely.
def hello(x,y):
fordf150 = hi(y,x)
"then do somethings,and use the variable 'fordf150'."
return something
def hi( ix, iy ):
"compute some value, good."
return good
Some script evaluates hello( 2, 3).
Python creates a new namespace for the evaluation of hello.
In hello, x is bound to the object 2. Binding is done position order.
In hello, y is bound to the object 3.
In hello, Python evaluates the first statement, fordf150 = hi( y, x ), y is 3, x is 2.
a. Python creates a new namespace for the evaluation of hi.
b. In hi, ix is bound to the object 3. Binding is done position order.
c. In hi, iy is bound to the object 2.
d. In hi, something happens and good is bound to some object, say 3.1415926.
e. In hi, a return is executed; identifying an object as the value for hi. In this case, the object is named by good and is the object 3.1415926.
f. The hi namespace is discarded. good, ix and iy vanish. The object (3.1415926), however, remains as the value of evaluating hi.
In hello, Python finishes the first statement, fordf150 = hi( y, x ), y is 3, x is 2. The value of hi is 3.1415926.
a. fordf150 is bound to the object created by evaluating hi, 3.1415926.
In hello, Python moves on to other statements.
At some point something is bound to an object, say, 2.718281828459045.
In hello, a return is executed; identifying an object as the value for hello. In this case, the object is named by something and is the object 2.718281828459045.
The namespace is discarded. fordf150 and something vanish, as do x and y. The object (2.718281828459045), however, remains as the value of evaluating hello.
Whatever program or script called hello gets the answer.
A:
If you want to define a variable to the global namespace from inside a function, and thereby make it accessible by other functions in this space, you can use the global keyword. Here's some examples
varA = 5 #A normal declaration of an integer in the main "global" namespace
def funcA():
print varA #This works, because the variable was defined in the global namespace
#and functions have read access to this.
def changeA():
varA = 2 #This however, defines a variable in the function's own namespace
#Because of this, it's not accessible by other functions.
#It has also replaced the global variable, though only inside this function
def newVar():
global varB #By using the global keyword, you assign this variable to the global namespace
varB = 5
def funcB():
print varB #Making it accessible to other functions
Conclusion: variables defined in a function stays in the function's namespace. It still has access to the global namespace for reading only, unless the variable has been called with the global keyword.
The term global isn't entirely global as it may seem at first. It's practically only a link to the lowest namespace in the file you're working in. Global keywords cannot be accessed in another module.
As a mild warning, this may be considered to be less "good practice" by some.
A:
your example program works, because the two instances of 'good' are different variables (you just happen to have both variables with the same name). The following code is exactly the same:
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return great
A:
More details on the python scoping rules are here :
Short Description of Python Scoping Rules
A:
The "hello" function doesn't mind you calling the "hi" function which is hasn't been defined yet, provided you don't try to actually use the "hello" function until after the both functions have been defined.
| A small question about python's variable scope | I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
| [
"The scope of functions hello and hi are entirely different. They do not have any variables in common.\nNote that the result of calling hi(x,y) is some object. You save that object with the name good in the function hello.\nThe variable named good in hello is a different variable, unrelated to the variable named good in the function hi.\nThey're spelled the same, but the exist in different namespaces. To prove this, change the spelling the good variable in one of the two functions, you'll see that things still work.\n\nEdit. Follow-up: \"so what should i do if i want use the result of hi function in hello function?\"\nNothing unusual. Look at hello closely.\ndef hello(x,y):\n fordf150 = hi(y,x)\n \"then do somethings,and use the variable 'fordf150'.\"\n return something\n\ndef hi( ix, iy ):\n \"compute some value, good.\"\n return good\n\nSome script evaluates hello( 2, 3).\n\nPython creates a new namespace for the evaluation of hello.\nIn hello, x is bound to the object 2. Binding is done position order.\nIn hello, y is bound to the object 3.\nIn hello, Python evaluates the first statement, fordf150 = hi( y, x ), y is 3, x is 2.\na. Python creates a new namespace for the evaluation of hi.\nb. In hi, ix is bound to the object 3. Binding is done position order.\nc. In hi, iy is bound to the object 2.\nd. In hi, something happens and good is bound to some object, say 3.1415926.\ne. In hi, a return is executed; identifying an object as the value for hi. In this case, the object is named by good and is the object 3.1415926.\nf. The hi namespace is discarded. good, ix and iy vanish. The object (3.1415926), however, remains as the value of evaluating hi.\nIn hello, Python finishes the first statement, fordf150 = hi( y, x ), y is 3, x is 2. The value of hi is 3.1415926.\na. fordf150 is bound to the object created by evaluating hi, 3.1415926.\nIn hello, Python moves on to other statements.\nAt some point something is bound to an object, say, 2.718281828459045.\nIn hello, a return is executed; identifying an object as the value for hello. In this case, the object is named by something and is the object 2.718281828459045.\nThe namespace is discarded. fordf150 and something vanish, as do x and y. The object (2.718281828459045), however, remains as the value of evaluating hello.\n\nWhatever program or script called hello gets the answer.\n",
"If you want to define a variable to the global namespace from inside a function, and thereby make it accessible by other functions in this space, you can use the global keyword. Here's some examples\nvarA = 5 #A normal declaration of an integer in the main \"global\" namespace\n\ndef funcA():\n print varA #This works, because the variable was defined in the global namespace\n #and functions have read access to this.\ndef changeA():\n varA = 2 #This however, defines a variable in the function's own namespace\n #Because of this, it's not accessible by other functions.\n #It has also replaced the global variable, though only inside this function\ndef newVar():\n global varB #By using the global keyword, you assign this variable to the global namespace\n varB = 5\n\ndef funcB():\n print varB #Making it accessible to other functions\n\nConclusion: variables defined in a function stays in the function's namespace. It still has access to the global namespace for reading only, unless the variable has been called with the global keyword.\nThe term global isn't entirely global as it may seem at first. It's practically only a link to the lowest namespace in the file you're working in. Global keywords cannot be accessed in another module.\nAs a mild warning, this may be considered to be less \"good practice\" by some.\n",
"your example program works, because the two instances of 'good' are different variables (you just happen to have both variables with the same name). The following code is exactly the same:\ndef hello(x,y):\n good=hi(iy,ix)\n \"then do somethings,and use the parameter'good'.\"\n return something\n\ndef hi(iy,ix):\n \"code\"\n return great\n\n",
"More details on the python scoping rules are here :\nShort Description of Python Scoping Rules\n",
"The \"hello\" function doesn't mind you calling the \"hi\" function which is hasn't been defined yet, provided you don't try to actually use the \"hello\" function until after the both functions have been defined.\n"
] | [
5,
3,
2,
2,
1
] | [] | [] | [
"python",
"scope",
"variables"
] | stackoverflow_0000357810_python_scope_variables.txt |
Q:
log4j with timestamp per log entry
this is my log output
INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or no attachments supported
INFO main digestemails - updating database
INFO main digestemails - email -> COMPLETED folder
INFO main digestemails -
I would like a time stamp per log message ie
INFO 2008-12-25 13:14:00 digestemails - email -> COMPLETED folder
here is my log4j config file
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
How do I do it?
A:
Use %d in your PatternLayout.
Also %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want. When the format pattern is omitted the date will be in ISO8601 format.
A:
A extract from my properties file
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C:/log/client.log
log4j.appender.logfile.MaxFileSize=5MB
log4j.appender.logfile.MaxBackupIndex=0
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
A:
You can find more conversion characters usage in log4j javadoc.For example, at http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html.
| log4j with timestamp per log entry | this is my log output
INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or no attachments supported
INFO main digestemails - updating database
INFO main digestemails - email -> COMPLETED folder
INFO main digestemails -
I would like a time stamp per log message ie
INFO 2008-12-25 13:14:00 digestemails - email -> COMPLETED folder
here is my log4j config file
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
How do I do it?
| [
"Use %d in your PatternLayout.\nAlso %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want. When the format pattern is omitted the date will be in ISO8601 format.\n",
"A extract from my properties file\nlog4j.rootLogger=INFO, stdout, logfile\n\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n\n\nlog4j.appender.logfile=org.apache.log4j.RollingFileAppender\nlog4j.appender.logfile.File=C:/log/client.log\nlog4j.appender.logfile.MaxFileSize=5MB\nlog4j.appender.logfile.MaxBackupIndex=0\nlog4j.appender.logfile.layout=org.apache.log4j.PatternLayout\nlog4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n\n\n",
"You can find more conversion characters usage in log4j javadoc.For example, at http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html.\n"
] | [
104,
18,
6
] | [] | [] | [
"java",
"jython",
"log4j",
"python"
] | stackoverflow_0000358225_java_jython_log4j_python.txt |
Q:
Django Template System: How do I solve this looping / grouping / counting?
I have a list of articles, and each article belongs to a section.
class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
I want to display the articles, grouped by section.
Sponsorships, Advertising & Marketing
1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams
2. Phil Jackson Questions Harrah's Signage At New Orleans Arena
3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account
4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider
5. Marketplace Roundup
Sports Media
6. Many Patriots Fans In New England Will Not See Tonight's Game
7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation
8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09
9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic
10. Media Notes
Leagues & Governing Bodies
11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team
12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed
13. Average Ticket Price For NFL Playoff Games To Drop By 10%
I figured out how to do most of it with Django's template system.
{% regroup articles by section as articles_by_section %}
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
<ul>
{% for item in article.list %}
<li>{{ forloop.counter }}. {{ item.headline }}</li>
{% endfor %}
</ul>
{% endfor %}
I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?
A:
Following Jeb's suggeston in a comment, I created a custom template tag.
I replaced {{ forloop.counter }} with {% counter %}, a tag that simply prints how many times it's been called.
Here's the code for my counter tag.
class CounterNode(template.Node):
def __init__(self):
self.count = 0
def render(self, context):
self.count += 1
return self.count
@register.tag
def counter(parser, token):
return CounterNode()
A:
This isn't exactly neat, but may be appropriate for someone:
{% for article in articles %}
{% ifchanged article.section %}
{% if not forloop.first %}</ul>{% endif %}
<h4>{{article.section}}</h4>
<ul>
{% endifchanged %}
<li>{{forloop.counter}}. {{ article.headline }}</li>
{% if forloop.last %}</ul>{% endif %}
{% endfor %}
| Django Template System: How do I solve this looping / grouping / counting? | I have a list of articles, and each article belongs to a section.
class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
I want to display the articles, grouped by section.
Sponsorships, Advertising & Marketing
1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams
2. Phil Jackson Questions Harrah's Signage At New Orleans Arena
3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account
4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider
5. Marketplace Roundup
Sports Media
6. Many Patriots Fans In New England Will Not See Tonight's Game
7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation
8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09
9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic
10. Media Notes
Leagues & Governing Bodies
11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team
12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed
13. Average Ticket Price For NFL Playoff Games To Drop By 10%
I figured out how to do most of it with Django's template system.
{% regroup articles by section as articles_by_section %}
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
<ul>
{% for item in article.list %}
<li>{{ forloop.counter }}. {{ item.headline }}</li>
{% endfor %}
</ul>
{% endfor %}
I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?
| [
"Following Jeb's suggeston in a comment, I created a custom template tag.\nI replaced {{ forloop.counter }} with {% counter %}, a tag that simply prints how many times it's been called.\nHere's the code for my counter tag. \nclass CounterNode(template.Node):\n\n def __init__(self):\n self.count = 0\n\n def render(self, context):\n self.count += 1\n return self.count\n\n@register.tag\ndef counter(parser, token):\n return CounterNode()\n\n",
"This isn't exactly neat, but may be appropriate for someone:\n{% for article in articles %} \n {% ifchanged article.section %}\n {% if not forloop.first %}</ul>{% endif %}\n <h4>{{article.section}}</h4>\n <ul>\n {% endifchanged %}\n <li>{{forloop.counter}}. {{ article.headline }}</li>\n {% if forloop.last %}</ul>{% endif %}\n{% endfor %}\n\n"
] | [
4,
1
] | [
"I think you can use forloop.parentloop.counter inside of the inner loop to achieve the numbering you're after.\n",
"You could just use an ordered list instead of unordered:\n{% regroup articles by section as articles_by_section %}\n\n<ol>\n{% for article in articles_by_section %} \n <h4>{{ article.grouper }}</h4>\n {% for item in article.list %} \n <li>{{ item.headline }}</li>\n {% endfor %}\n{% endfor %}\n</ol>\n\n"
] | [
-1,
-1
] | [
"django",
"django_templates",
"python"
] | stackoverflow_0000290397_django_django_templates_python.txt |
Q:
python, set terminal type in pexpect
I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.
The problem I have, I think, is that this program uses a coloured prompt.
This is what I do
import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
This is the output:
> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.
Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?
I am using tcsh shell
A:
Ok, I found the answer. csl's answer set me on the right path.
pexpect has a "env" option which I thought I could use. like this:
a = pexpect.spawn('program', env = {"TERM": "dumb"})
But this spawns a new shell which does not work for me, our development environment
depends on a lot of environmental variables :/
But if I do this before spawning a shell:
import os
os.environ["TERM"] = "dumb"
I change the current "TERM" and "dumb" does not support colours, which fixed my issue.
A:
Couldn't find anything in the pexpect documentation for setting terminals, but you could probably start your program explicitly with a shell, and then set the terminal type there:
shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
You could try something like
child = pexpect.spawn('TERM=vt100 /bin/bash', ['-c', shell_cmd])
You can also start bash with --norc and similar to avoid reading the initialization files. Check out the bash man page.
| python, set terminal type in pexpect | I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.
The problem I have, I think, is that this program uses a coloured prompt.
This is what I do
import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
This is the output:
> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.
Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?
I am using tcsh shell
| [
"Ok, I found the answer. csl's answer set me on the right path.\npexpect has a \"env\" option which I thought I could use. like this:\na = pexpect.spawn('program', env = {\"TERM\": \"dumb\"})\n\nBut this spawns a new shell which does not work for me, our development environment \ndepends on a lot of environmental variables :/\nBut if I do this before spawning a shell:\nimport os\nos.environ[\"TERM\"] = \"dumb\"\n\nI change the current \"TERM\" and \"dumb\" does not support colours, which fixed my issue.\n",
"Couldn't find anything in the pexpect documentation for setting terminals, but you could probably start your program explicitly with a shell, and then set the terminal type there:\nshell_cmd = 'ls -l | grep LOG > log_list.txt'\nchild = pexpect.spawn('/bin/bash', ['-c', shell_cmd])\nchild.expect(pexpect.EOF)\n\nYou could try something like\nchild = pexpect.spawn('TERM=vt100 /bin/bash', ['-c', shell_cmd])\n\nYou can also start bash with --norc and similar to avoid reading the initialization files. Check out the bash man page.\n"
] | [
8,
2
] | [] | [] | [
"pexpect",
"python"
] | stackoverflow_0000358783_pexpect_python.txt |
Q:
Comparing List of Arguments to it self?
Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.
E.g:
a = ['foo', 'foo', 'boo'] #not valid
b = ['foo', 'foo', 'foo'] #valid
Whats the best way to go about doing that?
FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.
A:
Use list.count to get the number of items in a list that match a value. If that number doesn't match the number of items, you know they aren't all the same.
if a.count( "foo" ) != len(a)
Which would look like...
if a.count( a[0] ) != len(a)
...in production code.
A:
Perhaps
all(a[0] == x for x in a)
is the most readable way.
A:
FYI. 5000 iterations of both matching and unmatching versions of a test on different sizes of the input list.
List Size 10
0.00530 aList.count(aList[0] ) == len(aList)
0.00699 for with return False if no match found.
0.00892 aList == [aList[0]] * len(aList)
0.00974 len(set(aList)) == 1
0.02334 all(aList[0] == x for x in aList)
0.02693 reduce(lambda x,y:x==y and x,aList)
List Size 100
0.01547 aList.count(aList[0] ) == len(aList)
0.01623 aList == [aList[0]] * len(aList)
0.03525 for with return False if no match found.
0.05122 len(set(aList)) == 1
0.08079 all(aList[0] == x for x in aList)
0.22797 reduce(lambda x,y:x==y and x,aList)
List Size 1000
0.09198 aList == [aList[0]] * len(aList)
0.11862 aList.count(aList[0] ) == len(aList)
0.31874 for with return False if no match found.
0.36145 len(set(aList)) == 1
0.65861 all(aList[0] == x for x in aList)
2.24386 reduce(lambda x,y:x==y and x,aList)
Clear winners and losers. count rules.
Here's the quickExit version that runs pretty quickly, but isn't a one-liner.
def quickExit( aList ):
"""for with return False if no match found."""
value= aList[0]
for x in aList:
if x != value: return False
return True
A:
Try creating a set from that list:
if len(set(my_list)) != 1:
return False
Sets can't have duplicate items.
EDIT: S.Lott's suggestion is cleaner:
all_items_are_same = len(set(my_list)) == 1
Think of it like this:
# Equality returns True or False
all_items_are_same = (len(set(my_list)) == 1)
A:
No matter what function you use you have to iterate over the entire array at least once.
So just use a for loop and compare the first value to each subsequent value. Nothing else could be faster, and it'll be three lines. Anything that does it in less lines will probably be more computationally complex actually.
A:
try (if the lists are not too long):
b == [b[0]] * len(b) #valid
a == [a[0]] * len(a) #not valid
this lets you compare the list to a list of the same size that is all of the same first element
A:
I think that this should be something you do with a reduce function...
>>> a = ['foo', 'foo', 'boo'] #not valid
>>> b = ['foo', 'foo', 'foo'] #valid
>>> reduce(lambda x,y:x==y and x,a)
False
>>> reduce(lambda x,y:x==y and x,b)
'foo'
I'm not sure if this has any advantages over the turning it into a set solution, though. It fails if you want to test if every value in the array is False.
| Comparing List of Arguments to it self? | Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.
E.g:
a = ['foo', 'foo', 'boo'] #not valid
b = ['foo', 'foo', 'foo'] #valid
Whats the best way to go about doing that?
FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.
| [
"Use list.count to get the number of items in a list that match a value. If that number doesn't match the number of items, you know they aren't all the same.\nif a.count( \"foo\" ) != len(a)\n\nWhich would look like...\nif a.count( a[0] ) != len(a)\n\n...in production code.\n",
"Perhaps\nall(a[0] == x for x in a)\n\nis the most readable way.\n",
"FYI. 5000 iterations of both matching and unmatching versions of a test on different sizes of the input list.\nList Size 10\n0.00530 aList.count(aList[0] ) == len(aList)\n0.00699 for with return False if no match found.\n0.00892 aList == [aList[0]] * len(aList)\n0.00974 len(set(aList)) == 1\n0.02334 all(aList[0] == x for x in aList)\n0.02693 reduce(lambda x,y:x==y and x,aList)\n\nList Size 100\n0.01547 aList.count(aList[0] ) == len(aList)\n0.01623 aList == [aList[0]] * len(aList)\n0.03525 for with return False if no match found.\n0.05122 len(set(aList)) == 1\n0.08079 all(aList[0] == x for x in aList)\n0.22797 reduce(lambda x,y:x==y and x,aList)\n\nList Size 1000\n0.09198 aList == [aList[0]] * len(aList)\n0.11862 aList.count(aList[0] ) == len(aList)\n0.31874 for with return False if no match found.\n0.36145 len(set(aList)) == 1\n0.65861 all(aList[0] == x for x in aList)\n2.24386 reduce(lambda x,y:x==y and x,aList)\n\nClear winners and losers. count rules.\nHere's the quickExit version that runs pretty quickly, but isn't a one-liner.\ndef quickExit( aList ):\n \"\"\"for with return False if no match found.\"\"\"\n value= aList[0]\n for x in aList:\n if x != value: return False\n return True\n\n",
"Try creating a set from that list:\nif len(set(my_list)) != 1:\n return False\n\nSets can't have duplicate items.\nEDIT: S.Lott's suggestion is cleaner:\nall_items_are_same = len(set(my_list)) == 1\n\nThink of it like this:\n# Equality returns True or False\nall_items_are_same = (len(set(my_list)) == 1)\n\n",
"No matter what function you use you have to iterate over the entire array at least once. \nSo just use a for loop and compare the first value to each subsequent value. Nothing else could be faster, and it'll be three lines. Anything that does it in less lines will probably be more computationally complex actually.\n",
"try (if the lists are not too long):\nb == [b[0]] * len(b) #valid\na == [a[0]] * len(a) #not valid\n\nthis lets you compare the list to a list of the same size that is all of the same first element\n",
"I think that this should be something you do with a reduce function...\n>>> a = ['foo', 'foo', 'boo'] #not valid\n>>> b = ['foo', 'foo', 'foo'] #valid\n>>> reduce(lambda x,y:x==y and x,a)\nFalse\n>>> reduce(lambda x,y:x==y and x,b)\n'foo'\n\nI'm not sure if this has any advantages over the turning it into a set solution, though. It fails if you want to test if every value in the array is False.\n"
] | [
5,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000359903_python.txt |
Q:
Keeping a variable around from post to get?
I have a class called myClass which defines post() and get() methods.
From index.html, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to new.html.
now, new.html has a form which calls myClass.get().
I want the get() method to know the value of the variables I got in post(). That is is main point here.
I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html.
Is there a way to access the "post instance" somehow?
Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit?
more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called?
A:
What you're talking about is establishing a "session". That is, a way to remember the user and the state of their transaction.
There are several ways of tackling this, all of which rely on techniques for remembering that you're in a session in the first place.
HTTP provides you no help. You have to find some place to save session state on the server, and some place to record session identification on the client. The two big techniques are
Use a cookie to identify the session. Seamless and silent.
Use a query string in the URL to identify the session. Obvious because you have a ?sessionid=SomeSessionGUID in your URL's. This exposes a lot and makes bookmarking annoying. After the session is cleaned up, you still have this session id floating around in people's bookmarks.
In a limited way, you can also use hidden fields in a form. This only works if you have forms on every page. Not always true.
Here's how it plays out in practice.
GET response. Check for the cookie in the header.
a. No cookie. First time user. Create a session. Save it somewhere (memory, file, database). Put the unique ID into a cookie. Respond knowing this is their first time.
b. Cookie. Been here recently. Try to get the cookie.
FInd the session object. Respond using information in the cookie.
Drat. No session. Old cookie. Create a new one and act like this is their first visit.
POST response. Check for the cookie in the header.
a. No cookie. WTF? Stupid kids. Get off my lawn! Someone bookmarked a POST or is trying to mess with your head. Respond as if it was a first-time GET.
b. Cookie. Excellent. Get the cookie.
Find the session object. Find the thing you need in the session object. Respond.
Drat. No session. Old cookie. Create a new one and respond as if was a first-time GET.
You can do the same thing with a query string instead of a cookie. Or a hidden field on a form.
A:
It is not a problem of how the instances are managed. Because HTTP is stateless, your program is, virtually, stateless too. (For long running processes, like GAE, it is possible to make it otherwise, but I am not sure you would need this complexity here)
You haven't supplied any code, but I am assuming you get a POST and then you redirect to results (which is a GET). So it should be easy to preserve the parameter:
def save_foo(request):
if request.method == 'POST':
save(request.POST)
return HttpRedirect(reverse(
'Some_Target',
{'bar': 'baz', 'foo': request.POST['foo']}))
else:
# do something else
This view, in case of a POST, casues the client to issue a GET request to whatever URL is aliased Some_Target. And this GET will include foo parameter from the POST.
This solution is for a single view. If you need this behaviour project-wise you can use a middleware for it. And this time caching the variable makes sense.
There are two things that make me a little uncomfortable with this approach:
Mixing GET and POST parameters. GET parameters should be used for instructions with no side effects, like filtering. POST parameter should be used for insructions with side effects, ie modifying the data. Moving a parameter from POST to get should be avoided IMHO.
If we need persistence, using object instances (or function scopes as in my example) is usually not a good idea.
If it is non sensitive information with with lower retention needs cookies are the way to go. They are a mechanism of persistence on the client side, so you can just grab them form the request and unless you change them they are retained (until expiration of course.)
If you need more control over retention you should use local persistence mechanisms. Server cache (of any kind), filesystem, database... Then of course you will need to filter per user manually.
In any case I would avoid caching on instances.
A:
HTTP is stateless, so you have no (built-in) way of knowing if the user that loads one page is the same user that loaded another. Further, even if you do know that, thanks to session cookies, for example, you have no way of telling if the browser window they're loading the subsequent page in is the same one they loaded the prior page in. The user could have multiple tabs accessing your site, and you don't want one page's state change to clobber another's.
With that in mind, your best option is to include query parameters in the link to the page being fetched with GET, encoding the variables you want to send to the 'get' page (make sure they're not sensitive, since the user can modify them!). Then you can access them through self.request.GET in the get request.
A:
I don't know specifically about the google app engine, but normally, here's what happens:
The server would have some kind of thread pool. Every time an http request is sent to the server, a thread is selected from the pool or created.
In that thread an instance of some kind of controller object will be created. This object will decide what to do with the request (like instantiating other classes and preprocessing the http request parameters). Usually, this object is the core of web frameworks. The request parameters are also resent by the browser every time (the server cannot guess what the browser wants).
Web servers usually have state stores for objects in a permanent or a session state. The session is represented by a unique user (usually by a cookie or a GUID in the url), which expires after a certain time.
Now in your case, you would need to take the values you got from your first function, store that in the session store and in the second function, get those values back from the session store.
Another solution would be to send the items back to the page as url parameters in your generated HTML from the first function and then you would get those back "as usual" from your second function.
A:
Why not just use memcache to temporarily store the variable, and then redirect to the POST URL? That seems like the easiest solution.
A:
OK -- Thanks everyone.
I'll try some of these ideas out, soon, and get back to you all.
It seems I can work around some these things by doing a lot of writing and reading from the datastore*, but I thought there might be an easier way of keeping that instance of the class around (I'm trying to use my known techniques in a web framework that I don't completely get yet).
*For instance, creating a unique record based on the data in the POST, and letting some variables "tag along". Is this a bad practice?
| Keeping a variable around from post to get? | I have a class called myClass which defines post() and get() methods.
From index.html, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to new.html.
now, new.html has a form which calls myClass.get().
I want the get() method to know the value of the variables I got in post(). That is is main point here.
I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html.
Is there a way to access the "post instance" somehow?
Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit?
more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called?
| [
"What you're talking about is establishing a \"session\". That is, a way to remember the user and the state of their transaction.\nThere are several ways of tackling this, all of which rely on techniques for remembering that you're in a session in the first place.\nHTTP provides you no help. You have to find some place to save session state on the server, and some place to record session identification on the client. The two big techniques are\n\nUse a cookie to identify the session. Seamless and silent.\nUse a query string in the URL to identify the session. Obvious because you have a ?sessionid=SomeSessionGUID in your URL's. This exposes a lot and makes bookmarking annoying. After the session is cleaned up, you still have this session id floating around in people's bookmarks.\nIn a limited way, you can also use hidden fields in a form. This only works if you have forms on every page. Not always true.\n\nHere's how it plays out in practice.\n\nGET response. Check for the cookie in the header.\na. No cookie. First time user. Create a session. Save it somewhere (memory, file, database). Put the unique ID into a cookie. Respond knowing this is their first time.\nb. Cookie. Been here recently. Try to get the cookie. \n\nFInd the session object. Respond using information in the cookie.\nDrat. No session. Old cookie. Create a new one and act like this is their first visit.\n\nPOST response. Check for the cookie in the header.\na. No cookie. WTF? Stupid kids. Get off my lawn! Someone bookmarked a POST or is trying to mess with your head. Respond as if it was a first-time GET.\nb. Cookie. Excellent. Get the cookie. \n\nFind the session object. Find the thing you need in the session object. Respond.\nDrat. No session. Old cookie. Create a new one and respond as if was a first-time GET.\n\n\nYou can do the same thing with a query string instead of a cookie. Or a hidden field on a form. \n",
"It is not a problem of how the instances are managed. Because HTTP is stateless, your program is, virtually, stateless too. (For long running processes, like GAE, it is possible to make it otherwise, but I am not sure you would need this complexity here)\nYou haven't supplied any code, but I am assuming you get a POST and then you redirect to results (which is a GET). So it should be easy to preserve the parameter:\ndef save_foo(request):\n if request.method == 'POST':\n save(request.POST)\n return HttpRedirect(reverse(\n 'Some_Target',\n {'bar': 'baz', 'foo': request.POST['foo']}))\n else:\n # do something else\n\nThis view, in case of a POST, casues the client to issue a GET request to whatever URL is aliased Some_Target. And this GET will include foo parameter from the POST.\nThis solution is for a single view. If you need this behaviour project-wise you can use a middleware for it. And this time caching the variable makes sense.\nThere are two things that make me a little uncomfortable with this approach:\n\nMixing GET and POST parameters. GET parameters should be used for instructions with no side effects, like filtering. POST parameter should be used for insructions with side effects, ie modifying the data. Moving a parameter from POST to get should be avoided IMHO.\nIf we need persistence, using object instances (or function scopes as in my example) is usually not a good idea.\n\n\nIf it is non sensitive information with with lower retention needs cookies are the way to go. They are a mechanism of persistence on the client side, so you can just grab them form the request and unless you change them they are retained (until expiration of course.)\nIf you need more control over retention you should use local persistence mechanisms. Server cache (of any kind), filesystem, database... Then of course you will need to filter per user manually.\n\n\nIn any case I would avoid caching on instances.\n",
"HTTP is stateless, so you have no (built-in) way of knowing if the user that loads one page is the same user that loaded another. Further, even if you do know that, thanks to session cookies, for example, you have no way of telling if the browser window they're loading the subsequent page in is the same one they loaded the prior page in. The user could have multiple tabs accessing your site, and you don't want one page's state change to clobber another's.\nWith that in mind, your best option is to include query parameters in the link to the page being fetched with GET, encoding the variables you want to send to the 'get' page (make sure they're not sensitive, since the user can modify them!). Then you can access them through self.request.GET in the get request.\n",
"I don't know specifically about the google app engine, but normally, here's what happens:\nThe server would have some kind of thread pool. Every time an http request is sent to the server, a thread is selected from the pool or created.\nIn that thread an instance of some kind of controller object will be created. This object will decide what to do with the request (like instantiating other classes and preprocessing the http request parameters). Usually, this object is the core of web frameworks. The request parameters are also resent by the browser every time (the server cannot guess what the browser wants).\nWeb servers usually have state stores for objects in a permanent or a session state. The session is represented by a unique user (usually by a cookie or a GUID in the url), which expires after a certain time.\nNow in your case, you would need to take the values you got from your first function, store that in the session store and in the second function, get those values back from the session store.\nAnother solution would be to send the items back to the page as url parameters in your generated HTML from the first function and then you would get those back \"as usual\" from your second function.\n",
"Why not just use memcache to temporarily store the variable, and then redirect to the POST URL? That seems like the easiest solution. \n",
"OK -- Thanks everyone. \nI'll try some of these ideas out, soon, and get back to you all. \nIt seems I can work around some these things by doing a lot of writing and reading from the datastore*, but I thought there might be an easier way of keeping that instance of the class around (I'm trying to use my known techniques in a web framework that I don't completely get yet). \n*For instance, creating a unique record based on the data in the POST, and letting some variables \"tag along\". Is this a bad practice? \n"
] | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"get",
"google_app_engine",
"post",
"python"
] | stackoverflow_0000358398_get_google_app_engine_post_python.txt |
Q:
Split HTML after N words in python
Is there any way to split a long string of HTML after N words? Obviously I could use:
' '.join(foo.split(' ')[:n])
to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.
I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.
For example, say I have the text:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit of linked text in it
</a>.
</p>
And I ask it to split after 5 words, it should return:
<p>This is some text with</p>
7 words:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit
</a>
</p>
A:
Take a look at the truncate_html_words function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want.
A:
I've heard that Beautiful Soup is very good at parsing html. It will probably be able to help you get correct html out.
A:
I was going to mention the base HTMLParser that's built in Python, since I'm not sure what the end-result your trying to get to is, it may or may not get you there, you'll work with the handlers primarily
A:
You can use a mix of regex, BeautifulSoup or Tidy (I prefer BeautifulSoup).
The idea is simple - strip all the HTML tags first. Find the nth word (n=7 here), find the number of times the nth word appears in the string till n words - coz u are looking only for the last occurrence to be used for truncation.
Here is a piece of code, though a bit messy but works
import re
from BeautifulSoup import BeautifulSoup
import tidy
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
input_string='<p>This is some text with a <a href="http://www.example.com/" '\
'title="Example link">bit of linked text in it</a></p>'
s=remove_html_tags(input_string).split(' ')[:7]
###required to ensure that only the last occurrence of the nth word is
# taken into account for truncating.
# coz if the nth word could be 'a'/'and'/'is'....etc
# which may occur multiple times within n words
temp=input_string
k=s.count(s[-1])
i=1
j=0
while i<=k:
j+=temp.find(s[-1])
temp=temp[j+len(s[-1]):]
i+=1
####
output_string=input_string[:j+len(s[-1])]
print "\nBeautifulSoup\n", BeautifulSoup(output_string)
print "\nTidy\n", tidy.parseString(output_string)
The output is what u want
BeautifulSoup
<p>This is some text with a <a href="http://www.example.com/" title="Example link">bit</a></p>
Tidy
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org">
<title></title>
</head>
<body>
<p>This is some text with a <a href="http://www.example.com/"
title="Example link">bit</a></p>
</body>
</html>
Hope this helps
Edit: A better regex
`p = re.compile(r'<[^<]*?>')`
| Split HTML after N words in python | Is there any way to split a long string of HTML after N words? Obviously I could use:
' '.join(foo.split(' ')[:n])
to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.
I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.
For example, say I have the text:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit of linked text in it
</a>.
</p>
And I ask it to split after 5 words, it should return:
<p>This is some text with</p>
7 words:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit
</a>
</p>
| [
"Take a look at the truncate_html_words function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want.\n",
"I've heard that Beautiful Soup is very good at parsing html. It will probably be able to help you get correct html out.\n",
"I was going to mention the base HTMLParser that's built in Python, since I'm not sure what the end-result your trying to get to is, it may or may not get you there, you'll work with the handlers primarily\n",
"You can use a mix of regex, BeautifulSoup or Tidy (I prefer BeautifulSoup).\nThe idea is simple - strip all the HTML tags first. Find the nth word (n=7 here), find the number of times the nth word appears in the string till n words - coz u are looking only for the last occurrence to be used for truncation.\nHere is a piece of code, though a bit messy but works\nimport re\nfrom BeautifulSoup import BeautifulSoup\nimport tidy\n\ndef remove_html_tags(data):\n p = re.compile(r'<.*?>')\n return p.sub('', data)\n\ninput_string='<p>This is some text with a <a href=\"http://www.example.com/\" '\\\n 'title=\"Example link\">bit of linked text in it</a></p>'\n\ns=remove_html_tags(input_string).split(' ')[:7]\n\n###required to ensure that only the last occurrence of the nth word is \n# taken into account for truncating. \n# coz if the nth word could be 'a'/'and'/'is'....etc \n# which may occur multiple times within n words \ntemp=input_string\nk=s.count(s[-1])\ni=1\nj=0\nwhile i<=k:\n j+=temp.find(s[-1])\n temp=temp[j+len(s[-1]):]\n i+=1\n#### \noutput_string=input_string[:j+len(s[-1])]\n\nprint \"\\nBeautifulSoup\\n\", BeautifulSoup(output_string)\nprint \"\\nTidy\\n\", tidy.parseString(output_string)\n\nThe output is what u want\nBeautifulSoup\n<p>This is some text with a <a href=\"http://www.example.com/\" title=\"Example link\">bit</a></p>\n\nTidy\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n<html>\n<head>\n<meta name=\"generator\" content=\n\"HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org\">\n<title></title>\n</head>\n<body>\n<p>This is some text with a <a href=\"http://www.example.com/\"\ntitle=\"Example link\">bit</a></p>\n</body>\n</html>\n\nHope this helps\nEdit: A better regex \n`p = re.compile(r'<[^<]*?>')`\n\n"
] | [
6,
3,
0,
0
] | [] | [] | [
"html",
"plone",
"python",
"zope"
] | stackoverflow_0000360036_html_plone_python_zope.txt |
Q:
Regular Expressions in unicode strings
I have some unicode text that I want to clean up using regular expressions. For example I have cases where u'(2'. This exists because for formatting reasons the closing paren ends up in an adjacent html cell. My initial solution to this problem was to look ahead at the contents of the next cell and using a string function determine if it held the closing paren. I knew this was not a great solution but it worked. Now I want to fix it but I can't seem to make the regular expression work.
missingParen=re.compile(r"^\(\d[^\)]$")
My understanding of what I think I am doing:
^ at the beginning of the string I want to find
( an open paren, the paren has to be backslashed because it is a special character
\d I also want to find a single digit
[ I am creating a special character class
^ I don't want to find what follows
) which is a close paren
$ at the end of the string
And of course the plot thickens I made a silly assumption that because I placed a \d I would not find (33 but I am wrong so I added a {1} to my regular expression and that did not help, it matched (3333, so my problem is more complicated than I thought. I want the string to be only an open paren and a single digit. Is this the more clever approach
missingParen=re.compile(r"^\(\d$")
And note S Lott _I already tagged it beginner so you can't pick up any cheap points Not that I don't appreciate your insights I keep meaning to read your book, it probably has the answer
A:
Okay sorry for using this a a stream of consciousness thinking stimulator but it appears that writing out my original question got me on the path. It seems to me that this is a solution for what I am trying to do:
missingParen=re.compile(r"^\(\d$")
| Regular Expressions in unicode strings | I have some unicode text that I want to clean up using regular expressions. For example I have cases where u'(2'. This exists because for formatting reasons the closing paren ends up in an adjacent html cell. My initial solution to this problem was to look ahead at the contents of the next cell and using a string function determine if it held the closing paren. I knew this was not a great solution but it worked. Now I want to fix it but I can't seem to make the regular expression work.
missingParen=re.compile(r"^\(\d[^\)]$")
My understanding of what I think I am doing:
^ at the beginning of the string I want to find
( an open paren, the paren has to be backslashed because it is a special character
\d I also want to find a single digit
[ I am creating a special character class
^ I don't want to find what follows
) which is a close paren
$ at the end of the string
And of course the plot thickens I made a silly assumption that because I placed a \d I would not find (33 but I am wrong so I added a {1} to my regular expression and that did not help, it matched (3333, so my problem is more complicated than I thought. I want the string to be only an open paren and a single digit. Is this the more clever approach
missingParen=re.compile(r"^\(\d$")
And note S Lott _I already tagged it beginner so you can't pick up any cheap points Not that I don't appreciate your insights I keep meaning to read your book, it probably has the answer
| [
"Okay sorry for using this a a stream of consciousness thinking stimulator but it appears that writing out my original question got me on the path. It seems to me that this is a solution for what I am trying to do:\n missingParen=re.compile(r\"^\\(\\d$\")\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000360600_python_regex.txt |
Q:
Access CVS through Apache service using SSPI
I'm running an Apache server (v2.2.10) with mod_python, Python 2.5 and Django. I have a small web app that will show the current projects we have in CVS and allow users to make a build of the different projects (the build checks out the project, and copies certain files over with the source stripped out).
On the Django dev server, everything works fine. I can see the list of projects in cvs, check out, etc. On the production server (the Apache one) I get the following error:
[8009030d] The credentials supplied to the package were not recognized
I'm trying to log in to the CVS server using SSPI. Entering the same command into a shell will execute properly.
This is the code I'm using:
def __execute(self, command = ''):
command = 'cvs.exe -d :sspi:user:password@cvs-serv.example.com:/Projects ls'
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
return p.communicate()
I've tried a number of different variations of things, and I can't seem to get it to work. Right now I believe that Apache is the culprit.
Any help would be appreciated
A:
Usage of SSPI make me think you are using CVSNT, thus a Windows system; what is the user you are running Apache into? Default user for services is SYSTEM, which does not share the same registry as your current user.
| Access CVS through Apache service using SSPI | I'm running an Apache server (v2.2.10) with mod_python, Python 2.5 and Django. I have a small web app that will show the current projects we have in CVS and allow users to make a build of the different projects (the build checks out the project, and copies certain files over with the source stripped out).
On the Django dev server, everything works fine. I can see the list of projects in cvs, check out, etc. On the production server (the Apache one) I get the following error:
[8009030d] The credentials supplied to the package were not recognized
I'm trying to log in to the CVS server using SSPI. Entering the same command into a shell will execute properly.
This is the code I'm using:
def __execute(self, command = ''):
command = 'cvs.exe -d :sspi:user:password@cvs-serv.example.com:/Projects ls'
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
return p.communicate()
I've tried a number of different variations of things, and I can't seem to get it to work. Right now I believe that Apache is the culprit.
Any help would be appreciated
| [
"Usage of SSPI make me think you are using CVSNT, thus a Windows system; what is the user you are running Apache into? Default user for services is SYSTEM, which does not share the same registry as your current user.\n"
] | [
0
] | [] | [] | [
"apache",
"cvs",
"python",
"sspi"
] | stackoverflow_0000360911_apache_cvs_python_sspi.txt |
Q:
What GUI toolkit looks best for a native LAF for Python in Windows and Linux?
I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?
If possible, cite strengths and weaknesses of the suggested toolkit.
Thank you,
Luis
A:
Python binding of Wx is very strong since at least one of the core developer is a python guy itself. WxWdgets is robust, time proven stable, mature, but also bit more than just GUI. Even is a lot is left out in WxPython - because Python itself offers that already - you might find that extra convenient for your project. Wx is the fastest especially on Win, because it lets render the OS and yes WxLicense is de facto LGPL. With XRC you have also a way like Glade to click you to a UI that you can reuse by different projects and languages. What is one major reason for me to use Wx is the fast and helping mailing list, never seen a flamewar, you get even often answers from core developers there, like the notorious vadim zeitlin++. The only thing con to Wx is the API that once grew out of MS MFC and has still its darker(unelegant) corners, but with every version you have some improvements on that as well.
QT done some nice stuff, especially warping the language but under python that don't count. They invented also a lot of extra widgets. In wx you have also combined, more complex widgets like e.g. for config dialog, but that goes not that far as in QT.
And you could of course use GTK. almost no difference under linux to Wx but a bit alien and slower under win. but also free.
A:
For KDE and Windows, Qt is the best option. Qt is fine for Gnome/Windows too, but in that case you might prefer WxWidgets.
Qt bindings for python are here.
Remember that for closed source development you need a Qt license, plus a PyQt license.
For open source it should be free, but I'm not very familiar with the PyQt licensing.
A:
Like others said, PyQt or wxPython... The technical difference between the two is more or less imaginary - it's a question of your comfort with the toolkit that matters, really.
| What GUI toolkit looks best for a native LAF for Python in Windows and Linux? | I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?
If possible, cite strengths and weaknesses of the suggested toolkit.
Thank you,
Luis
| [
"Python binding of Wx is very strong since at least one of the core developer is a python guy itself. WxWdgets is robust, time proven stable, mature, but also bit more than just GUI. Even is a lot is left out in WxPython - because Python itself offers that already - you might find that extra convenient for your project. Wx is the fastest especially on Win, because it lets render the OS and yes WxLicense is de facto LGPL. With XRC you have also a way like Glade to click you to a UI that you can reuse by different projects and languages. What is one major reason for me to use Wx is the fast and helping mailing list, never seen a flamewar, you get even often answers from core developers there, like the notorious vadim zeitlin++. The only thing con to Wx is the API that once grew out of MS MFC and has still its darker(unelegant) corners, but with every version you have some improvements on that as well.\nQT done some nice stuff, especially warping the language but under python that don't count. They invented also a lot of extra widgets. In wx you have also combined, more complex widgets like e.g. for config dialog, but that goes not that far as in QT. \nAnd you could of course use GTK. almost no difference under linux to Wx but a bit alien and slower under win. but also free.\n",
"For KDE and Windows, Qt is the best option. Qt is fine for Gnome/Windows too, but in that case you might prefer WxWidgets.\nQt bindings for python are here.\nRemember that for closed source development you need a Qt license, plus a PyQt license.\nFor open source it should be free, but I'm not very familiar with the PyQt licensing.\n",
"Like others said, PyQt or wxPython... The technical difference between the two is more or less imaginary - it's a question of your comfort with the toolkit that matters, really.\n"
] | [
8,
2,
0
] | [] | [] | [
"gui_toolkit",
"linux",
"native",
"python",
"windows"
] | stackoverflow_0000360602_gui_toolkit_linux_native_python_windows.txt |
Q:
Techniques for data comparison between different schemas
Are there techniques for comparing the same data stored in different schemas? The situation is something like this. If I have a db with schema A and it stores data for a feature in say, 5 tables. Schema A -> Schema B is done during an upgrade process. During the upgrade process some transformation logic is applied and the data is stored in 7 tables in Schema B.
What i'm after is some way to verify data integrity, basically i would have to compare different schemas while factoring in the transformation logic. Short of writing some custom t-sql sprocs to compare the data, is there an alternate method? I'm leaning towards python to automate this, are there any python modules that would help me out?
To better illustrate my question the following diagram is a rough picture of one of the many data sets i would need to compare, Properties 1,2,3 and 4 are migrated from Schema source to destination, but they are spread across different tables.
Table1Src Table1Dest
| |
--ID(Primary Key) --ID(Primary Key)
--Property1 --Property1
--Property2 --Property5
--Property3 --Property6
Table2Src Table2Dest
| |
--ID(Foreign Key->Table1Src) --ID(Foreign Key->Table1Dest)
--Property4 --Property2
--Property3
Table3Dest
|
--ID(Foreign Key->Table1Dest)
--Property4
--Property7
A:
Make "views" on both the schemas that translate to the same buisness representation of data. Export these views to flat files and then you can use any plain vanilla file diff utility to compare and point out differences.
A:
Basically, you should create object representations for both schema versions, and then compare objects. This is best done if they all fit into memory simultaneously; if not, you need to iterate over all objects in one representation, fetch the corresponding object in the other representation, compare them, and then do the same vice versa.
The difficult part may be to obtain object representations; you can see whether SQLAlchemy can be used conveniently for your tables. SQLAlchemy is, in principle, capable of mapping existing schema definitions onto objects.
A:
I've used SQLAlchemy successfully for migration between one schema and another - that's a similar process (as indicated by Martin v. Löwis) as comparison. Especially if you use an .equals(other) method.
| Techniques for data comparison between different schemas | Are there techniques for comparing the same data stored in different schemas? The situation is something like this. If I have a db with schema A and it stores data for a feature in say, 5 tables. Schema A -> Schema B is done during an upgrade process. During the upgrade process some transformation logic is applied and the data is stored in 7 tables in Schema B.
What i'm after is some way to verify data integrity, basically i would have to compare different schemas while factoring in the transformation logic. Short of writing some custom t-sql sprocs to compare the data, is there an alternate method? I'm leaning towards python to automate this, are there any python modules that would help me out?
To better illustrate my question the following diagram is a rough picture of one of the many data sets i would need to compare, Properties 1,2,3 and 4 are migrated from Schema source to destination, but they are spread across different tables.
Table1Src Table1Dest
| |
--ID(Primary Key) --ID(Primary Key)
--Property1 --Property1
--Property2 --Property5
--Property3 --Property6
Table2Src Table2Dest
| |
--ID(Foreign Key->Table1Src) --ID(Foreign Key->Table1Dest)
--Property4 --Property2
--Property3
Table3Dest
|
--ID(Foreign Key->Table1Dest)
--Property4
--Property7
| [
"Make \"views\" on both the schemas that translate to the same buisness representation of data. Export these views to flat files and then you can use any plain vanilla file diff utility to compare and point out differences. \n",
"Basically, you should create object representations for both schema versions, and then compare objects. This is best done if they all fit into memory simultaneously; if not, you need to iterate over all objects in one representation, fetch the corresponding object in the other representation, compare them, and then do the same vice versa.\nThe difficult part may be to obtain object representations; you can see whether SQLAlchemy can be used conveniently for your tables. SQLAlchemy is, in principle, capable of mapping existing schema definitions onto objects.\n",
"I've used SQLAlchemy successfully for migration between one schema and another - that's a similar process (as indicated by Martin v. Löwis) as comparison. Especially if you use an .equals(other) method.\n"
] | [
2,
1,
0
] | [] | [] | [
"database",
"python",
"sql"
] | stackoverflow_0000361945_database_python_sql.txt |
Q:
Python: Finding partial string matches in a large corpus of strings
I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string.
What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:
matches = [s for s in allfiles if s.startswith(input)]
I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?
A:
For exact matching, generally the way to implement something like this is to store your corpus in a trie. The idea is that you store each letter as a node in the tree, linking to the next letter in a word. Finding the matches is simply walking the tree, and showing all children of your current location. eg. "cat", "cow" and "car" would be stored as:
a--t
/ \
c r
\
o--w
When you get a c, you start at the c node, an a will then take you to the c/a node (children
"t" and "r", making cat and car as your completions).
Note that you'll also need to mark nodes that are complete words to handle names that are substrings of others (eg "car" and "cart")
To get the desired fuzzy matching, you may need to make some changes however.
A:
I used Lucene to autocomplete a text field with more then a hundred thousand possibilities and I perceived it as instantaneous.
A:
Maybe the readline module is what you are looking for. It is an interface to the GNU readline library Python Documentation.
Maybe you can supply your own completition function with set_completer().
A:
The flexibility you want for matching your string is called Fuzzy Matching or Fuzzy Searching . I am not aware of any python implementation (but I haven't looked deeply in the subject) but there are C/C++ implementations that you can reuse, like the TRE packaged that supports regexp with fuzzy parameters.
Apart from that, there is always the question of whether the total list of your words fits in memory or not. If not, keeping them in a list is not feasible and will have to cache something to disk or to a database.
A:
(addressing just the string matching part of the question)
If you want to try something quickly yourself, why not create a few dictionaries, each mapping initial patterns to lists of strings where
Each dictionary is keyed on initial patterns of a particular length
All the strings in a string list start with the initial pattern
An initial pattern/string list pair is only created if there are less than a certain number (say 10) of strings in the list
So, when the user has typed three characters, for example, you look in the dictionary with keys of length 3. If there is a match, it means you have between 1 and 10 possibilities immediately available.
| Python: Finding partial string matches in a large corpus of strings | I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string.
What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:
matches = [s for s in allfiles if s.startswith(input)]
I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?
| [
"For exact matching, generally the way to implement something like this is to store your corpus in a trie. The idea is that you store each letter as a node in the tree, linking to the next letter in a word. Finding the matches is simply walking the tree, and showing all children of your current location. eg. \"cat\", \"cow\" and \"car\" would be stored as:\n a--t\n / \\ \nc r\n \\\n o--w\n\nWhen you get a c, you start at the c node, an a will then take you to the c/a node (children\n\"t\" and \"r\", making cat and car as your completions).\nNote that you'll also need to mark nodes that are complete words to handle names that are substrings of others (eg \"car\" and \"cart\")\nTo get the desired fuzzy matching, you may need to make some changes however.\n",
"I used Lucene to autocomplete a text field with more then a hundred thousand possibilities and I perceived it as instantaneous.\n",
"Maybe the readline module is what you are looking for. It is an interface to the GNU readline library Python Documentation.\nMaybe you can supply your own completition function with set_completer().\n",
"The flexibility you want for matching your string is called Fuzzy Matching or Fuzzy Searching . I am not aware of any python implementation (but I haven't looked deeply in the subject) but there are C/C++ implementations that you can reuse, like the TRE packaged that supports regexp with fuzzy parameters.\nApart from that, there is always the question of whether the total list of your words fits in memory or not. If not, keeping them in a list is not feasible and will have to cache something to disk or to a database.\n",
"(addressing just the string matching part of the question)\nIf you want to try something quickly yourself, why not create a few dictionaries, each mapping initial patterns to lists of strings where\n\nEach dictionary is keyed on initial patterns of a particular length\nAll the strings in a string list start with the initial pattern\nAn initial pattern/string list pair is only created if there are less than a certain number (say 10) of strings in the list\n\nSo, when the user has typed three characters, for example, you look in the dictionary with keys of length 3. If there is a match, it means you have between 1 and 10 possibilities immediately available.\n"
] | [
7,
3,
1,
0,
0
] | [] | [] | [
"python",
"search"
] | stackoverflow_0000362231_python_search.txt |
Q:
mssql handles line returns rather awkwardly
Here is the problem:
for your reference:
database entries 1,2 and 3 are made using jython 2.2.1 using jdbc1.2.
database entry 4 is made using vb the old to be replace program using odbc.
We have found that if I copy and paste both jython and vb MailBody entries to wordpad directly from that SQL Server Enterprise Manager software it outputs the format perfectly with correct line returns. if I compare the bytes of each file with a hex editor or KDiff3 they are binary identically the same.
There is a 3rd party program which consumes this data. Sadly that 3rd party program reads the data and for entries 1 to 3 it displays the data without line returns. though for entry 4 it correctly formats the text. As futher proof we can see in the picture, the data in the database is displayed differently.
Somehow the line returns are preserved in the database for the vb entries but the jython entries they are overlooked. if I click on the 'MailBody' field of entry 4 i can press down i can see the rest of the email. Whereas the data for jython is displayed in one row.
What gives, what am i missing, and how do I handle this?
Here is a snippet of the code where I actually send it to the database.
EDIT: FYI: please disregard the discrepancies in the 'Processed' column, it is irrelevant.
EDIT: what i want to do is make the jython program input the data in the same way as the vb program. So that the 3rd party program will come along and correctly display the data.
so what it will look like is every entry in 'MailBody' will display "This is a testing only!" then next line "etc etc" so if I was to do a screendump all entries would resemble database entry 4.
SOLVED
add _force_CRLF to the mix:
def _force_CRLF(self, data):
'''Make sure data uses CRLF for line termination.
Nicked the regex from smtplib.quotedata. '''
print data
newdata = re.sub(r'(?:\r\n|\n|\r(?!\n))', "\r\n", data)
print newdata
return newdata
def _execute_insert(self):
try:
self._stmt=self._con.prepareStatement(\
"INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\
VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))")
self._stmt.setString(1,self._emailEntryId)
self._stmt.setString(2,self._subject)
self._stmt.setString(3,self._fromWho)
self._stmt.setString(4,self._toWho)
self._stmt.setString(5,self._format_date(self._emailRecv))
self._stmt.setString(6,self._format_date(self._emailSent))
self._stmt.setString(7,str(self._attachmentCount))
self._stmt.setString(8,self._force_CRLF(self._format_email_body()))
self._stmt.execute()
self._prepare_inserting_attachment_data()
self._insert_attachment_data()
except:
raise
def _format_email_body(self):
if not self._emailBody:
return "could not extract email body"
if len(self._emailBody) > BODY_TRUNCATE_LENGTH:
return self._clean_body(self._emailBody[:BODY_TRUNCATE_LENGTH])
else:
return self._clean_body(self._emailBody)
def _clean_body(self,dirty):
'''this method simply deletes any occurrence of an '=20' that plagues my output after much testing this is not related to the line return issue, even if i comment it out I still have the problem.'''
dirty=str(dirty)
dirty=dirty.replace(r"=20","")
return r"%s"%dirty
A:
I suggest to add a debug output to your program, dumping character codes before insertion in DB. There are chances that Jython replace CrLf pair with single character and doesn't restore it when written to DB.
A:
You should look at the quopri module (and others regarding email) so you don't have to use dirty tricks as _clean_body
| mssql handles line returns rather awkwardly | Here is the problem:
for your reference:
database entries 1,2 and 3 are made using jython 2.2.1 using jdbc1.2.
database entry 4 is made using vb the old to be replace program using odbc.
We have found that if I copy and paste both jython and vb MailBody entries to wordpad directly from that SQL Server Enterprise Manager software it outputs the format perfectly with correct line returns. if I compare the bytes of each file with a hex editor or KDiff3 they are binary identically the same.
There is a 3rd party program which consumes this data. Sadly that 3rd party program reads the data and for entries 1 to 3 it displays the data without line returns. though for entry 4 it correctly formats the text. As futher proof we can see in the picture, the data in the database is displayed differently.
Somehow the line returns are preserved in the database for the vb entries but the jython entries they are overlooked. if I click on the 'MailBody' field of entry 4 i can press down i can see the rest of the email. Whereas the data for jython is displayed in one row.
What gives, what am i missing, and how do I handle this?
Here is a snippet of the code where I actually send it to the database.
EDIT: FYI: please disregard the discrepancies in the 'Processed' column, it is irrelevant.
EDIT: what i want to do is make the jython program input the data in the same way as the vb program. So that the 3rd party program will come along and correctly display the data.
so what it will look like is every entry in 'MailBody' will display "This is a testing only!" then next line "etc etc" so if I was to do a screendump all entries would resemble database entry 4.
SOLVED
add _force_CRLF to the mix:
def _force_CRLF(self, data):
'''Make sure data uses CRLF for line termination.
Nicked the regex from smtplib.quotedata. '''
print data
newdata = re.sub(r'(?:\r\n|\n|\r(?!\n))', "\r\n", data)
print newdata
return newdata
def _execute_insert(self):
try:
self._stmt=self._con.prepareStatement(\
"INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\
VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))")
self._stmt.setString(1,self._emailEntryId)
self._stmt.setString(2,self._subject)
self._stmt.setString(3,self._fromWho)
self._stmt.setString(4,self._toWho)
self._stmt.setString(5,self._format_date(self._emailRecv))
self._stmt.setString(6,self._format_date(self._emailSent))
self._stmt.setString(7,str(self._attachmentCount))
self._stmt.setString(8,self._force_CRLF(self._format_email_body()))
self._stmt.execute()
self._prepare_inserting_attachment_data()
self._insert_attachment_data()
except:
raise
def _format_email_body(self):
if not self._emailBody:
return "could not extract email body"
if len(self._emailBody) > BODY_TRUNCATE_LENGTH:
return self._clean_body(self._emailBody[:BODY_TRUNCATE_LENGTH])
else:
return self._clean_body(self._emailBody)
def _clean_body(self,dirty):
'''this method simply deletes any occurrence of an '=20' that plagues my output after much testing this is not related to the line return issue, even if i comment it out I still have the problem.'''
dirty=str(dirty)
dirty=dirty.replace(r"=20","")
return r"%s"%dirty
| [
"I suggest to add a debug output to your program, dumping character codes before insertion in DB. There are chances that Jython replace CrLf pair with single character and doesn't restore it when written to DB.\n",
"You should look at the quopri module (and others regarding email) so you don't have to use dirty tricks as _clean_body\n"
] | [
1,
1
] | [] | [] | [
"formatting",
"java",
"jython",
"python",
"sql_server"
] | stackoverflow_0000355135_formatting_java_jython_python_sql_server.txt |
Q:
Python Canvas library for geometric shapes
I'm looking for a Python library for creating canvases for manipulating geometric shapes. Specifically I need the ability to create arbitrary polygons and place them on the canvas, the polygons need to have the ability to be transparent/have an alpha channel, I need to be able to edit polygons that are currently on the canvas, and I need to be able to get the actual color of a given pixel(the aggregate of all the transparent piece that are there).
Basically I'm trying to make this: http://alteredqualia.com/visualization/evolve/ in python.
A:
I think cairo will do a lot of what you want. They have python bindings, too.
The one requirement that that won't help you with is modifying previously-drawn polygons, but I don't know of any canvas that will do that for you.
A:
Sounds like a job for OpenGL.
My advice is that, whichever library you choose, you make a data structure for your polygons that suits your algorithms so that they can be more simple and readable rather then try to get these algorithms to manipulate a canvas directly. Then you can write the code that draws them separate (i.e. independent) of the main logic.
A:
This discussion on Stackoverflow has some comparisons and code snippets on various GUI toolkits for Python. I'm pretty sure that the QGraphicsView on QT will do transparency. Nokia (nee Troll) make a demo suite for QT that should give you an idea of its capabilities.
A:
Pygame should be able to do this for you.
See pygame.draw.polygon
A:
Try pyglet. It is a graphics library for Python with OpenGL. If you've done OpenGL programming before, it is certainly the easiest way to get what you want.
A:
I believe the HTML canvas lets you modify elements
It does not. You can check out my HTML canvas tutorial to see how you draw a moving ball; you wipe the screen and draw a new circle at the spot you want.
You can draw simple shapes to a canvas in all of pyglet, pygame, QT, Tkinter, wxPython and cairo.
Generally, you will have objects called "sprites" or "shapes" that represent objects drawn to the screen, and you'll store them all in a container. Then the library or framework will, at every frame, render them all to the canvas. Thus it will seem to the user (you) that you can modify the objects on screen; you set a ball's x and y coordinates and in the next frame it's rendered there. However, at a low level, everything's being wiped and redrawn again.
For computationally intensive animation, a technique called double-buffering will be employed whereby a bitmap in memory will be modified instead of the one onscreen, and then the drawing process will simply be to copy that bitmap to the screen.
alter the item in the list and then create a new canvas, which seems like it would have a significant overhead.
All of the frameworks mentioned above will give you a nice abstraction for the list of objects to draw, so that you won't need to maintain it manually, and you can program as if the sprites/shapes you've drawn can be directly moved onscreen, even though they really aren't at a low level.
A:
I believe the HTML canvas lets you modify elements, which makes me believe there might be another canvas that can as well. However, if there is not that would basically require me to keep a separate list of all the polygons and when I wanted to make a change, alter the item in the list and then create a new canvas, which seems like it would have a significant overhead.
A:
Both Qt and wxWidgets have some canvas drawing abilities (Qt calls it GraphicsView). Quick Google searches will get you a lot of examples so you can see if it fits your requirements.
| Python Canvas library for geometric shapes | I'm looking for a Python library for creating canvases for manipulating geometric shapes. Specifically I need the ability to create arbitrary polygons and place them on the canvas, the polygons need to have the ability to be transparent/have an alpha channel, I need to be able to edit polygons that are currently on the canvas, and I need to be able to get the actual color of a given pixel(the aggregate of all the transparent piece that are there).
Basically I'm trying to make this: http://alteredqualia.com/visualization/evolve/ in python.
| [
"I think cairo will do a lot of what you want. They have python bindings, too.\nThe one requirement that that won't help you with is modifying previously-drawn polygons, but I don't know of any canvas that will do that for you. \n",
"Sounds like a job for OpenGL.\nMy advice is that, whichever library you choose, you make a data structure for your polygons that suits your algorithms so that they can be more simple and readable rather then try to get these algorithms to manipulate a canvas directly. Then you can write the code that draws them separate (i.e. independent) of the main logic.\n",
"This discussion on Stackoverflow has some comparisons and code snippets on various GUI toolkits for Python. I'm pretty sure that the QGraphicsView on QT will do transparency. Nokia (nee Troll) make a demo suite for QT that should give you an idea of its capabilities.\n",
"Pygame should be able to do this for you.\nSee pygame.draw.polygon\n",
"Try pyglet. It is a graphics library for Python with OpenGL. If you've done OpenGL programming before, it is certainly the easiest way to get what you want.\n",
"\nI believe the HTML canvas lets you modify elements\n\nIt does not. You can check out my HTML canvas tutorial to see how you draw a moving ball; you wipe the screen and draw a new circle at the spot you want.\nYou can draw simple shapes to a canvas in all of pyglet, pygame, QT, Tkinter, wxPython and cairo. \nGenerally, you will have objects called \"sprites\" or \"shapes\" that represent objects drawn to the screen, and you'll store them all in a container. Then the library or framework will, at every frame, render them all to the canvas. Thus it will seem to the user (you) that you can modify the objects on screen; you set a ball's x and y coordinates and in the next frame it's rendered there. However, at a low level, everything's being wiped and redrawn again.\nFor computationally intensive animation, a technique called double-buffering will be employed whereby a bitmap in memory will be modified instead of the one onscreen, and then the drawing process will simply be to copy that bitmap to the screen.\n\nalter the item in the list and then create a new canvas, which seems like it would have a significant overhead.\n\nAll of the frameworks mentioned above will give you a nice abstraction for the list of objects to draw, so that you won't need to maintain it manually, and you can program as if the sprites/shapes you've drawn can be directly moved onscreen, even though they really aren't at a low level.\n",
"I believe the HTML canvas lets you modify elements, which makes me believe there might be another canvas that can as well. However, if there is not that would basically require me to keep a separate list of all the polygons and when I wanted to make a change, alter the item in the list and then create a new canvas, which seems like it would have a significant overhead.\n",
"Both Qt and wxWidgets have some canvas drawing abilities (Qt calls it GraphicsView). Quick Google searches will get you a lot of examples so you can see if it fits your requirements.\n"
] | [
5,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"canvas",
"drawing",
"python"
] | stackoverflow_0000361889_algorithm_canvas_drawing_python.txt |
Q:
How to script an OLE component using Python
I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?
I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?
A:
"Python and COM" contains an example. OLE is related to COM and ActiveX so you should look for those terms.
"Python Programming on Win32" is a useful book. There is also a "Python Win32" mailing list.
A:
You need the win32com package. Some examples:
from win32com.client.dynamic import Dispatch
# Excel
excel = Dispatch('Excel.Application')
# Vim
vim = Dispatch('Vim.Application')
And then call whatever you like on them.
A:
win32com is a good package to use if you want to use the IDispatch interface to control your objects, but it's slow.
comtypes is a better, native Python, package that uses the raw COM approach to talk to your controls.
WxPython uses comtypes to give you an ActiveX container window from Python.
A:
Please take a look at the python-win32 package, and, in particular, at its win32com API.
A:
PythonWin (http://sourceforge.net/projects/pywin32/), bundled with python-win32, comes with its own COM browser as part of its shell and debugging environment.
| How to script an OLE component using Python | I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?
I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?
| [
"\"Python and COM\" contains an example. OLE is related to COM and ActiveX so you should look for those terms. \n\"Python Programming on Win32\" is a useful book. There is also a \"Python Win32\" mailing list.\n",
"You need the win32com package. Some examples:\nfrom win32com.client.dynamic import Dispatch\n\n# Excel\nexcel = Dispatch('Excel.Application')\n\n# Vim\nvim = Dispatch('Vim.Application')\n\nAnd then call whatever you like on them.\n",
"win32com is a good package to use if you want to use the IDispatch interface to control your objects, but it's slow.\ncomtypes is a better, native Python, package that uses the raw COM approach to talk to your controls.\nWxPython uses comtypes to give you an ActiveX container window from Python.\n",
"Please take a look at the python-win32 package, and, in particular, at its win32com API.\n",
"PythonWin (http://sourceforge.net/projects/pywin32/), bundled with python-win32, comes with its own COM browser as part of its shell and debugging environment.\n"
] | [
3,
2,
2,
0,
0
] | [] | [] | [
"activex",
"ole",
"python",
"scripting",
"windows"
] | stackoverflow_0000279094_activex_ole_python_scripting_windows.txt |